]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
MFV r305562: 7259 DS_FIELD_LARGE_BLOCKS is unused
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaExpr.cpp
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/ExprOpenMP.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68
69   // See if this function is unavailable.
70   if (D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73
74   return true;
75 }
76
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (D->hasAttr<UnusedAttr>()) {
80     const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
81     if (DC && !DC->hasAttr<UnusedAttr>())
82       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
83   }
84 }
85
86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
87   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
88   if (!OMD)
89     return false;
90   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
91   if (!OID)
92     return false;
93
94   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
95     if (ObjCMethodDecl *CatMeth =
96             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
97       if (!CatMeth->hasAttr<AvailabilityAttr>())
98         return true;
99   return false;
100 }
101
102 static AvailabilityResult
103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
104                            const ObjCInterfaceDecl *UnknownObjCClass,
105                            bool ObjCPropertyAccess) {
106   // See if this declaration is unavailable or deprecated.
107   std::string Message;
108   AvailabilityResult Result = D->getAvailability(&Message);
109
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(&Message);
117         continue;
118       }
119     }
120     break;
121   }
122     
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(&Message);
128     }
129   }
130
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(&Message);
136     }
137
138   const ObjCPropertyDecl *ObjCPDecl = nullptr;
139   if (Result == AR_Deprecated || Result == AR_Unavailable ||
140       AR_NotYetIntroduced) {
141     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
142       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
143         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
144         if (PDeclResult == Result)
145           ObjCPDecl = PD;
146       }
147     }
148   }
149   
150   switch (Result) {
151     case AR_Available:
152       break;
153
154     case AR_Deprecated:
155       if (S.getCurContextAvailability() != AR_Deprecated)
156         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
157                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
158                                   ObjCPropertyAccess);
159       break;
160
161     case AR_NotYetIntroduced: {
162       // Don't do this for enums, they can't be redeclared.
163       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
164         break;
165  
166       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
167       // Objective-C method declarations in categories are not modelled as
168       // redeclarations, so manually look for a redeclaration in a category
169       // if necessary.
170       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
171         Warn = false;
172       // In general, D will point to the most recent redeclaration. However,
173       // for `@class A;` decls, this isn't true -- manually go through the
174       // redecl chain in that case.
175       if (Warn && isa<ObjCInterfaceDecl>(D))
176         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
177              Redecl = Redecl->getPreviousDecl())
178           if (!Redecl->hasAttr<AvailabilityAttr>() ||
179               Redecl->getAttr<AvailabilityAttr>()->isInherited())
180             Warn = false;
181  
182       if (Warn)
183         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
184                                   UnknownObjCClass, ObjCPDecl,
185                                   ObjCPropertyAccess);
186       break;
187     }
188
189     case AR_Unavailable:
190       if (S.getCurContextAvailability() != AR_Unavailable)
191         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
192                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
193                                   ObjCPropertyAccess);
194       break;
195
196     }
197     return Result;
198 }
199
200 /// \brief Emit a note explaining that this function is deleted.
201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
202   assert(Decl->isDeleted());
203
204   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
205
206   if (Method && Method->isDeleted() && Method->isDefaulted()) {
207     // If the method was explicitly defaulted, point at that declaration.
208     if (!Method->isImplicit())
209       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
210
211     // Try to diagnose why this special member function was implicitly
212     // deleted. This might fail, if that reason no longer applies.
213     CXXSpecialMember CSM = getSpecialMember(Method);
214     if (CSM != CXXInvalid)
215       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
216
217     return;
218   }
219
220   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
221     if (CXXConstructorDecl *BaseCD =
222             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
223       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
224       if (BaseCD->isDeleted()) {
225         NoteDeletedFunction(BaseCD);
226       } else {
227         // FIXME: An explanation of why exactly it can't be inherited
228         // would be nice.
229         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
230       }
231       return;
232     }
233   }
234
235   Diag(Decl->getLocation(), diag::note_availability_specified_here)
236     << Decl << true;
237 }
238
239 /// \brief Determine whether a FunctionDecl was ever declared with an
240 /// explicit storage class.
241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
242   for (auto I : D->redecls()) {
243     if (I->getStorageClass() != SC_None)
244       return true;
245   }
246   return false;
247 }
248
249 /// \brief Check whether we're in an extern inline function and referring to a
250 /// variable or function with internal linkage (C11 6.7.4p3).
251 ///
252 /// This is only a warning because we used to silently accept this code, but
253 /// in many cases it will not behave correctly. This is not enabled in C++ mode
254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
255 /// and so while there may still be user mistakes, most of the time we can't
256 /// prove that there are errors.
257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
258                                                       const NamedDecl *D,
259                                                       SourceLocation Loc) {
260   // This is disabled under C++; there are too many ways for this to fire in
261   // contexts where the warning is a false positive, or where it is technically
262   // correct but benign.
263   if (S.getLangOpts().CPlusPlus)
264     return;
265
266   // Check if this is an inlined function or method.
267   FunctionDecl *Current = S.getCurFunctionDecl();
268   if (!Current)
269     return;
270   if (!Current->isInlined())
271     return;
272   if (!Current->isExternallyVisible())
273     return;
274
275   // Check if the decl has internal linkage.
276   if (D->getFormalLinkage() != InternalLinkage)
277     return;
278
279   // Downgrade from ExtWarn to Extension if
280   //  (1) the supposedly external inline function is in the main file,
281   //      and probably won't be included anywhere else.
282   //  (2) the thing we're referencing is a pure function.
283   //  (3) the thing we're referencing is another inline function.
284   // This last can give us false negatives, but it's better than warning on
285   // wrappers for simple C library functions.
286   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
287   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
288   if (!DowngradeWarning && UsedFn)
289     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
290
291   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
292                                : diag::ext_internal_in_extern_inline)
293     << /*IsVar=*/!UsedFn << D;
294
295   S.MaybeSuggestAddingStaticToDecl(Current);
296
297   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
298       << D;
299 }
300
301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
302   const FunctionDecl *First = Cur->getFirstDecl();
303
304   // Suggest "static" on the function, if possible.
305   if (!hasAnyExplicitStorageClass(First)) {
306     SourceLocation DeclBegin = First->getSourceRange().getBegin();
307     Diag(DeclBegin, diag::note_convert_inline_to_static)
308       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
309   }
310 }
311
312 /// \brief Determine whether the use of this declaration is valid, and
313 /// emit any corresponding diagnostics.
314 ///
315 /// This routine diagnoses various problems with referencing
316 /// declarations that can occur when using a declaration. For example,
317 /// it might warn if a deprecated or unavailable declaration is being
318 /// used, or produce an error (and return true) if a C++0x deleted
319 /// function is being used.
320 ///
321 /// \returns true if there was an error (this declaration cannot be
322 /// referenced), false otherwise.
323 ///
324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
325                              const ObjCInterfaceDecl *UnknownObjCClass,
326                              bool ObjCPropertyAccess) {
327   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
328     // If there were any diagnostics suppressed by template argument deduction,
329     // emit them now.
330     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
331     if (Pos != SuppressedDiagnostics.end()) {
332       for (const PartialDiagnosticAt &Suppressed : Pos->second)
333         Diag(Suppressed.first, Suppressed.second);
334
335       // Clear out the list of suppressed diagnostics, so that we don't emit
336       // them again for this specialization. However, we don't obsolete this
337       // entry from the table, because we want to avoid ever emitting these
338       // diagnostics again.
339       Pos->second.clear();
340     }
341
342     // C++ [basic.start.main]p3:
343     //   The function 'main' shall not be used within a program.
344     if (cast<FunctionDecl>(D)->isMain())
345       Diag(Loc, diag::ext_main_used);
346   }
347
348   // See if this is an auto-typed variable whose initializer we are parsing.
349   if (ParsingInitForAutoVars.count(D)) {
350     const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
351
352     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
353       << D->getDeclName() << (unsigned)AT->getKeyword();
354     return true;
355   }
356
357   // See if this is a deleted function.
358   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
359     if (FD->isDeleted()) {
360       Diag(Loc, diag::err_deleted_function_use);
361       NoteDeletedFunction(FD);
362       return true;
363     }
364
365     // If the function has a deduced return type, and we can't deduce it,
366     // then we can't use it either.
367     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
368         DeduceReturnType(FD, Loc))
369       return true;
370   }
371   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
372                              ObjCPropertyAccess);
373
374   DiagnoseUnusedOfDecl(*this, D, Loc);
375
376   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
377
378   return false;
379 }
380
381 /// \brief Retrieve the message suffix that should be added to a
382 /// diagnostic complaining about the given function being deleted or
383 /// unavailable.
384 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
385   std::string Message;
386   if (FD->getAvailability(&Message))
387     return ": " + Message;
388
389   return std::string();
390 }
391
392 /// DiagnoseSentinelCalls - This routine checks whether a call or
393 /// message-send is to a declaration with the sentinel attribute, and
394 /// if so, it checks that the requirements of the sentinel are
395 /// satisfied.
396 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
397                                  ArrayRef<Expr *> Args) {
398   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
399   if (!attr)
400     return;
401
402   // The number of formal parameters of the declaration.
403   unsigned numFormalParams;
404
405   // The kind of declaration.  This is also an index into a %select in
406   // the diagnostic.
407   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
408
409   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
410     numFormalParams = MD->param_size();
411     calleeType = CT_Method;
412   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
413     numFormalParams = FD->param_size();
414     calleeType = CT_Function;
415   } else if (isa<VarDecl>(D)) {
416     QualType type = cast<ValueDecl>(D)->getType();
417     const FunctionType *fn = nullptr;
418     if (const PointerType *ptr = type->getAs<PointerType>()) {
419       fn = ptr->getPointeeType()->getAs<FunctionType>();
420       if (!fn) return;
421       calleeType = CT_Function;
422     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
423       fn = ptr->getPointeeType()->castAs<FunctionType>();
424       calleeType = CT_Block;
425     } else {
426       return;
427     }
428
429     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
430       numFormalParams = proto->getNumParams();
431     } else {
432       numFormalParams = 0;
433     }
434   } else {
435     return;
436   }
437
438   // "nullPos" is the number of formal parameters at the end which
439   // effectively count as part of the variadic arguments.  This is
440   // useful if you would prefer to not have *any* formal parameters,
441   // but the language forces you to have at least one.
442   unsigned nullPos = attr->getNullPos();
443   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
444   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
445
446   // The number of arguments which should follow the sentinel.
447   unsigned numArgsAfterSentinel = attr->getSentinel();
448
449   // If there aren't enough arguments for all the formal parameters,
450   // the sentinel, and the args after the sentinel, complain.
451   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
452     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
453     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
454     return;
455   }
456
457   // Otherwise, find the sentinel expression.
458   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
459   if (!sentinelExpr) return;
460   if (sentinelExpr->isValueDependent()) return;
461   if (Context.isSentinelNullExpr(sentinelExpr)) return;
462
463   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
464   // or 'NULL' if those are actually defined in the context.  Only use
465   // 'nil' for ObjC methods, where it's much more likely that the
466   // variadic arguments form a list of object pointers.
467   SourceLocation MissingNilLoc
468     = getLocForEndOfToken(sentinelExpr->getLocEnd());
469   std::string NullValue;
470   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
471     NullValue = "nil";
472   else if (getLangOpts().CPlusPlus11)
473     NullValue = "nullptr";
474   else if (PP.isMacroDefined("NULL"))
475     NullValue = "NULL";
476   else
477     NullValue = "(void*) 0";
478
479   if (MissingNilLoc.isInvalid())
480     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
481   else
482     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
483       << int(calleeType)
484       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
485   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
486 }
487
488 SourceRange Sema::getExprRange(Expr *E) const {
489   return E ? E->getSourceRange() : SourceRange();
490 }
491
492 //===----------------------------------------------------------------------===//
493 //  Standard Promotions and Conversions
494 //===----------------------------------------------------------------------===//
495
496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
498   // Handle any placeholder expressions which made it here.
499   if (E->getType()->isPlaceholderType()) {
500     ExprResult result = CheckPlaceholderExpr(E);
501     if (result.isInvalid()) return ExprError();
502     E = result.get();
503   }
504   
505   QualType Ty = E->getType();
506   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
507
508   if (Ty->isFunctionType()) {
509     // If we are here, we are not calling a function but taking
510     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
511     if (getLangOpts().OpenCL) {
512       if (Diagnose)
513         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
514       return ExprError();
515     }
516
517     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
518       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
519         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
520           return ExprError();
521
522     E = ImpCastExprToType(E, Context.getPointerType(Ty),
523                           CK_FunctionToPointerDecay).get();
524   } else if (Ty->isArrayType()) {
525     // In C90 mode, arrays only promote to pointers if the array expression is
526     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
527     // type 'array of type' is converted to an expression that has type 'pointer
528     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
529     // that has type 'array of type' ...".  The relevant change is "an lvalue"
530     // (C90) to "an expression" (C99).
531     //
532     // C++ 4.2p1:
533     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
534     // T" can be converted to an rvalue of type "pointer to T".
535     //
536     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
537       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
538                             CK_ArrayToPointerDecay).get();
539   }
540   return E;
541 }
542
543 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
544   // Check to see if we are dereferencing a null pointer.  If so,
545   // and if not volatile-qualified, this is undefined behavior that the
546   // optimizer will delete, so warn about it.  People sometimes try to use this
547   // to get a deterministic trap and are surprised by clang's behavior.  This
548   // only handles the pattern "*null", which is a very syntactic check.
549   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
550     if (UO->getOpcode() == UO_Deref &&
551         UO->getSubExpr()->IgnoreParenCasts()->
552           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
553         !UO->getType().isVolatileQualified()) {
554     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
555                           S.PDiag(diag::warn_indirection_through_null)
556                             << UO->getSubExpr()->getSourceRange());
557     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
558                         S.PDiag(diag::note_indirection_through_null));
559   }
560 }
561
562 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
563                                     SourceLocation AssignLoc,
564                                     const Expr* RHS) {
565   const ObjCIvarDecl *IV = OIRE->getDecl();
566   if (!IV)
567     return;
568   
569   DeclarationName MemberName = IV->getDeclName();
570   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
571   if (!Member || !Member->isStr("isa"))
572     return;
573   
574   const Expr *Base = OIRE->getBase();
575   QualType BaseType = Base->getType();
576   if (OIRE->isArrow())
577     BaseType = BaseType->getPointeeType();
578   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
579     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
580       ObjCInterfaceDecl *ClassDeclared = nullptr;
581       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
582       if (!ClassDeclared->getSuperClass()
583           && (*ClassDeclared->ivar_begin()) == IV) {
584         if (RHS) {
585           NamedDecl *ObjectSetClass =
586             S.LookupSingleName(S.TUScope,
587                                &S.Context.Idents.get("object_setClass"),
588                                SourceLocation(), S.LookupOrdinaryName);
589           if (ObjectSetClass) {
590             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
591             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
592             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
593             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
594                                                      AssignLoc), ",") <<
595             FixItHint::CreateInsertion(RHSLocEnd, ")");
596           }
597           else
598             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
599         } else {
600           NamedDecl *ObjectGetClass =
601             S.LookupSingleName(S.TUScope,
602                                &S.Context.Idents.get("object_getClass"),
603                                SourceLocation(), S.LookupOrdinaryName);
604           if (ObjectGetClass)
605             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
606             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
607             FixItHint::CreateReplacement(
608                                          SourceRange(OIRE->getOpLoc(),
609                                                      OIRE->getLocEnd()), ")");
610           else
611             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
612         }
613         S.Diag(IV->getLocation(), diag::note_ivar_decl);
614       }
615     }
616 }
617
618 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
619   // Handle any placeholder expressions which made it here.
620   if (E->getType()->isPlaceholderType()) {
621     ExprResult result = CheckPlaceholderExpr(E);
622     if (result.isInvalid()) return ExprError();
623     E = result.get();
624   }
625   
626   // C++ [conv.lval]p1:
627   //   A glvalue of a non-function, non-array type T can be
628   //   converted to a prvalue.
629   if (!E->isGLValue()) return E;
630
631   QualType T = E->getType();
632   assert(!T.isNull() && "r-value conversion on typeless expression?");
633
634   // We don't want to throw lvalue-to-rvalue casts on top of
635   // expressions of certain types in C++.
636   if (getLangOpts().CPlusPlus &&
637       (E->getType() == Context.OverloadTy ||
638        T->isDependentType() ||
639        T->isRecordType()))
640     return E;
641
642   // The C standard is actually really unclear on this point, and
643   // DR106 tells us what the result should be but not why.  It's
644   // generally best to say that void types just doesn't undergo
645   // lvalue-to-rvalue at all.  Note that expressions of unqualified
646   // 'void' type are never l-values, but qualified void can be.
647   if (T->isVoidType())
648     return E;
649
650   // OpenCL usually rejects direct accesses to values of 'half' type.
651   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
652       T->isHalfType()) {
653     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
654       << 0 << T;
655     return ExprError();
656   }
657
658   CheckForNullPointerDereference(*this, E);
659   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
660     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
661                                      &Context.Idents.get("object_getClass"),
662                                      SourceLocation(), LookupOrdinaryName);
663     if (ObjectGetClass)
664       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
665         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
666         FixItHint::CreateReplacement(
667                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
668     else
669       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
670   }
671   else if (const ObjCIvarRefExpr *OIRE =
672             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
673     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
674
675   // C++ [conv.lval]p1:
676   //   [...] If T is a non-class type, the type of the prvalue is the
677   //   cv-unqualified version of T. Otherwise, the type of the
678   //   rvalue is T.
679   //
680   // C99 6.3.2.1p2:
681   //   If the lvalue has qualified type, the value has the unqualified
682   //   version of the type of the lvalue; otherwise, the value has the
683   //   type of the lvalue.
684   if (T.hasQualifiers())
685     T = T.getUnqualifiedType();
686
687   // Under the MS ABI, lock down the inheritance model now.
688   if (T->isMemberPointerType() &&
689       Context.getTargetInfo().getCXXABI().isMicrosoft())
690     (void)isCompleteType(E->getExprLoc(), T);
691
692   UpdateMarkingForLValueToRValue(E);
693   
694   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
695   // balance that.
696   if (getLangOpts().ObjCAutoRefCount &&
697       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
698     ExprNeedsCleanups = true;
699
700   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
701                                             nullptr, VK_RValue);
702
703   // C11 6.3.2.1p2:
704   //   ... if the lvalue has atomic type, the value has the non-atomic version 
705   //   of the type of the lvalue ...
706   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
707     T = Atomic->getValueType().getUnqualifiedType();
708     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
709                                    nullptr, VK_RValue);
710   }
711   
712   return Res;
713 }
714
715 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
716   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
717   if (Res.isInvalid())
718     return ExprError();
719   Res = DefaultLvalueConversion(Res.get());
720   if (Res.isInvalid())
721     return ExprError();
722   return Res;
723 }
724
725 /// CallExprUnaryConversions - a special case of an unary conversion
726 /// performed on a function designator of a call expression.
727 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
728   QualType Ty = E->getType();
729   ExprResult Res = E;
730   // Only do implicit cast for a function type, but not for a pointer
731   // to function type.
732   if (Ty->isFunctionType()) {
733     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
734                             CK_FunctionToPointerDecay).get();
735     if (Res.isInvalid())
736       return ExprError();
737   }
738   Res = DefaultLvalueConversion(Res.get());
739   if (Res.isInvalid())
740     return ExprError();
741   return Res.get();
742 }
743
744 /// UsualUnaryConversions - Performs various conversions that are common to most
745 /// operators (C99 6.3). The conversions of array and function types are
746 /// sometimes suppressed. For example, the array->pointer conversion doesn't
747 /// apply if the array is an argument to the sizeof or address (&) operators.
748 /// In these instances, this routine should *not* be called.
749 ExprResult Sema::UsualUnaryConversions(Expr *E) {
750   // First, convert to an r-value.
751   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
752   if (Res.isInvalid())
753     return ExprError();
754   E = Res.get();
755
756   QualType Ty = E->getType();
757   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
758
759   // Half FP have to be promoted to float unless it is natively supported
760   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
761     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
762
763   // Try to perform integral promotions if the object has a theoretically
764   // promotable type.
765   if (Ty->isIntegralOrUnscopedEnumerationType()) {
766     // C99 6.3.1.1p2:
767     //
768     //   The following may be used in an expression wherever an int or
769     //   unsigned int may be used:
770     //     - an object or expression with an integer type whose integer
771     //       conversion rank is less than or equal to the rank of int
772     //       and unsigned int.
773     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
774     //
775     //   If an int can represent all values of the original type, the
776     //   value is converted to an int; otherwise, it is converted to an
777     //   unsigned int. These are called the integer promotions. All
778     //   other types are unchanged by the integer promotions.
779
780     QualType PTy = Context.isPromotableBitField(E);
781     if (!PTy.isNull()) {
782       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
783       return E;
784     }
785     if (Ty->isPromotableIntegerType()) {
786       QualType PT = Context.getPromotedIntegerType(Ty);
787       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
788       return E;
789     }
790   }
791   return E;
792 }
793
794 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
795 /// do not have a prototype. Arguments that have type float or __fp16
796 /// are promoted to double. All other argument types are converted by
797 /// UsualUnaryConversions().
798 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
799   QualType Ty = E->getType();
800   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
801
802   ExprResult Res = UsualUnaryConversions(E);
803   if (Res.isInvalid())
804     return ExprError();
805   E = Res.get();
806
807   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
808   // double.
809   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
810   if (BTy && (BTy->getKind() == BuiltinType::Half ||
811               BTy->getKind() == BuiltinType::Float))
812     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
813
814   // C++ performs lvalue-to-rvalue conversion as a default argument
815   // promotion, even on class types, but note:
816   //   C++11 [conv.lval]p2:
817   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
818   //     operand or a subexpression thereof the value contained in the
819   //     referenced object is not accessed. Otherwise, if the glvalue
820   //     has a class type, the conversion copy-initializes a temporary
821   //     of type T from the glvalue and the result of the conversion
822   //     is a prvalue for the temporary.
823   // FIXME: add some way to gate this entire thing for correctness in
824   // potentially potentially evaluated contexts.
825   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
826     ExprResult Temp = PerformCopyInitialization(
827                        InitializedEntity::InitializeTemporary(E->getType()),
828                                                 E->getExprLoc(), E);
829     if (Temp.isInvalid())
830       return ExprError();
831     E = Temp.get();
832   }
833
834   return E;
835 }
836
837 /// Determine the degree of POD-ness for an expression.
838 /// Incomplete types are considered POD, since this check can be performed
839 /// when we're in an unevaluated context.
840 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
841   if (Ty->isIncompleteType()) {
842     // C++11 [expr.call]p7:
843     //   After these conversions, if the argument does not have arithmetic,
844     //   enumeration, pointer, pointer to member, or class type, the program
845     //   is ill-formed.
846     //
847     // Since we've already performed array-to-pointer and function-to-pointer
848     // decay, the only such type in C++ is cv void. This also handles
849     // initializer lists as variadic arguments.
850     if (Ty->isVoidType())
851       return VAK_Invalid;
852
853     if (Ty->isObjCObjectType())
854       return VAK_Invalid;
855     return VAK_Valid;
856   }
857
858   if (Ty.isCXX98PODType(Context))
859     return VAK_Valid;
860
861   // C++11 [expr.call]p7:
862   //   Passing a potentially-evaluated argument of class type (Clause 9)
863   //   having a non-trivial copy constructor, a non-trivial move constructor,
864   //   or a non-trivial destructor, with no corresponding parameter,
865   //   is conditionally-supported with implementation-defined semantics.
866   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
867     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
868       if (!Record->hasNonTrivialCopyConstructor() &&
869           !Record->hasNonTrivialMoveConstructor() &&
870           !Record->hasNonTrivialDestructor())
871         return VAK_ValidInCXX11;
872
873   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
874     return VAK_Valid;
875
876   if (Ty->isObjCObjectType())
877     return VAK_Invalid;
878
879   if (getLangOpts().MSVCCompat)
880     return VAK_MSVCUndefined;
881
882   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
883   // permitted to reject them. We should consider doing so.
884   return VAK_Undefined;
885 }
886
887 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
888   // Don't allow one to pass an Objective-C interface to a vararg.
889   const QualType &Ty = E->getType();
890   VarArgKind VAK = isValidVarArgType(Ty);
891
892   // Complain about passing non-POD types through varargs.
893   switch (VAK) {
894   case VAK_ValidInCXX11:
895     DiagRuntimeBehavior(
896         E->getLocStart(), nullptr,
897         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
898           << Ty << CT);
899     // Fall through.
900   case VAK_Valid:
901     if (Ty->isRecordType()) {
902       // This is unlikely to be what the user intended. If the class has a
903       // 'c_str' member function, the user probably meant to call that.
904       DiagRuntimeBehavior(E->getLocStart(), nullptr,
905                           PDiag(diag::warn_pass_class_arg_to_vararg)
906                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
907     }
908     break;
909
910   case VAK_Undefined:
911   case VAK_MSVCUndefined:
912     DiagRuntimeBehavior(
913         E->getLocStart(), nullptr,
914         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
915           << getLangOpts().CPlusPlus11 << Ty << CT);
916     break;
917
918   case VAK_Invalid:
919     if (Ty->isObjCObjectType())
920       DiagRuntimeBehavior(
921           E->getLocStart(), nullptr,
922           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
923             << Ty << CT);
924     else
925       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
926         << isa<InitListExpr>(E) << Ty << CT;
927     break;
928   }
929 }
930
931 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
932 /// will create a trap if the resulting type is not a POD type.
933 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
934                                                   FunctionDecl *FDecl) {
935   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
936     // Strip the unbridged-cast placeholder expression off, if applicable.
937     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
938         (CT == VariadicMethod ||
939          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
940       E = stripARCUnbridgedCast(E);
941
942     // Otherwise, do normal placeholder checking.
943     } else {
944       ExprResult ExprRes = CheckPlaceholderExpr(E);
945       if (ExprRes.isInvalid())
946         return ExprError();
947       E = ExprRes.get();
948     }
949   }
950   
951   ExprResult ExprRes = DefaultArgumentPromotion(E);
952   if (ExprRes.isInvalid())
953     return ExprError();
954   E = ExprRes.get();
955
956   // Diagnostics regarding non-POD argument types are
957   // emitted along with format string checking in Sema::CheckFunctionCall().
958   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
959     // Turn this into a trap.
960     CXXScopeSpec SS;
961     SourceLocation TemplateKWLoc;
962     UnqualifiedId Name;
963     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
964                        E->getLocStart());
965     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
966                                           Name, true, false);
967     if (TrapFn.isInvalid())
968       return ExprError();
969
970     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
971                                     E->getLocStart(), None,
972                                     E->getLocEnd());
973     if (Call.isInvalid())
974       return ExprError();
975
976     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
977                                   Call.get(), E);
978     if (Comma.isInvalid())
979       return ExprError();
980     return Comma.get();
981   }
982
983   if (!getLangOpts().CPlusPlus &&
984       RequireCompleteType(E->getExprLoc(), E->getType(),
985                           diag::err_call_incomplete_argument))
986     return ExprError();
987
988   return E;
989 }
990
991 /// \brief Converts an integer to complex float type.  Helper function of
992 /// UsualArithmeticConversions()
993 ///
994 /// \return false if the integer expression is an integer type and is
995 /// successfully converted to the complex type.
996 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
997                                                   ExprResult &ComplexExpr,
998                                                   QualType IntTy,
999                                                   QualType ComplexTy,
1000                                                   bool SkipCast) {
1001   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1002   if (SkipCast) return false;
1003   if (IntTy->isIntegerType()) {
1004     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1005     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1006     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1007                                   CK_FloatingRealToComplex);
1008   } else {
1009     assert(IntTy->isComplexIntegerType());
1010     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1011                                   CK_IntegralComplexToFloatingComplex);
1012   }
1013   return false;
1014 }
1015
1016 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1017 /// UsualArithmeticConversions()
1018 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1019                                              ExprResult &RHS, QualType LHSType,
1020                                              QualType RHSType,
1021                                              bool IsCompAssign) {
1022   // if we have an integer operand, the result is the complex type.
1023   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1024                                              /*skipCast*/false))
1025     return LHSType;
1026   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1027                                              /*skipCast*/IsCompAssign))
1028     return RHSType;
1029
1030   // This handles complex/complex, complex/float, or float/complex.
1031   // When both operands are complex, the shorter operand is converted to the
1032   // type of the longer, and that is the type of the result. This corresponds
1033   // to what is done when combining two real floating-point operands.
1034   // The fun begins when size promotion occur across type domains.
1035   // From H&S 6.3.4: When one operand is complex and the other is a real
1036   // floating-point type, the less precise type is converted, within it's
1037   // real or complex domain, to the precision of the other type. For example,
1038   // when combining a "long double" with a "double _Complex", the
1039   // "double _Complex" is promoted to "long double _Complex".
1040
1041   // Compute the rank of the two types, regardless of whether they are complex.
1042   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1043
1044   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1045   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1046   QualType LHSElementType =
1047       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1048   QualType RHSElementType =
1049       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1050
1051   QualType ResultType = S.Context.getComplexType(LHSElementType);
1052   if (Order < 0) {
1053     // Promote the precision of the LHS if not an assignment.
1054     ResultType = S.Context.getComplexType(RHSElementType);
1055     if (!IsCompAssign) {
1056       if (LHSComplexType)
1057         LHS =
1058             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1059       else
1060         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1061     }
1062   } else if (Order > 0) {
1063     // Promote the precision of the RHS.
1064     if (RHSComplexType)
1065       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1066     else
1067       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1068   }
1069   return ResultType;
1070 }
1071
1072 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1073 /// of UsualArithmeticConversions()
1074 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1075                                            ExprResult &IntExpr,
1076                                            QualType FloatTy, QualType IntTy,
1077                                            bool ConvertFloat, bool ConvertInt) {
1078   if (IntTy->isIntegerType()) {
1079     if (ConvertInt)
1080       // Convert intExpr to the lhs floating point type.
1081       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1082                                     CK_IntegralToFloating);
1083     return FloatTy;
1084   }
1085      
1086   // Convert both sides to the appropriate complex float.
1087   assert(IntTy->isComplexIntegerType());
1088   QualType result = S.Context.getComplexType(FloatTy);
1089
1090   // _Complex int -> _Complex float
1091   if (ConvertInt)
1092     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1093                                   CK_IntegralComplexToFloatingComplex);
1094
1095   // float -> _Complex float
1096   if (ConvertFloat)
1097     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1098                                     CK_FloatingRealToComplex);
1099
1100   return result;
1101 }
1102
1103 /// \brief Handle arithmethic conversion with floating point types.  Helper
1104 /// function of UsualArithmeticConversions()
1105 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1106                                       ExprResult &RHS, QualType LHSType,
1107                                       QualType RHSType, bool IsCompAssign) {
1108   bool LHSFloat = LHSType->isRealFloatingType();
1109   bool RHSFloat = RHSType->isRealFloatingType();
1110
1111   // If we have two real floating types, convert the smaller operand
1112   // to the bigger result.
1113   if (LHSFloat && RHSFloat) {
1114     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1115     if (order > 0) {
1116       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1117       return LHSType;
1118     }
1119
1120     assert(order < 0 && "illegal float comparison");
1121     if (!IsCompAssign)
1122       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1123     return RHSType;
1124   }
1125
1126   if (LHSFloat) {
1127     // Half FP has to be promoted to float unless it is natively supported
1128     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1129       LHSType = S.Context.FloatTy;
1130
1131     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1132                                       /*convertFloat=*/!IsCompAssign,
1133                                       /*convertInt=*/ true);
1134   }
1135   assert(RHSFloat);
1136   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1137                                     /*convertInt=*/ true,
1138                                     /*convertFloat=*/!IsCompAssign);
1139 }
1140
1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1142
1143 namespace {
1144 /// These helper callbacks are placed in an anonymous namespace to
1145 /// permit their use as function template parameters.
1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1147   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1148 }
1149
1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1151   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1152                              CK_IntegralComplexCast);
1153 }
1154 }
1155
1156 /// \brief Handle integer arithmetic conversions.  Helper function of
1157 /// UsualArithmeticConversions()
1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1160                                         ExprResult &RHS, QualType LHSType,
1161                                         QualType RHSType, bool IsCompAssign) {
1162   // The rules for this case are in C99 6.3.1.8
1163   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1164   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1165   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1166   if (LHSSigned == RHSSigned) {
1167     // Same signedness; use the higher-ranked type
1168     if (order >= 0) {
1169       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1170       return LHSType;
1171     } else if (!IsCompAssign)
1172       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1173     return RHSType;
1174   } else if (order != (LHSSigned ? 1 : -1)) {
1175     // The unsigned type has greater than or equal rank to the
1176     // signed type, so use the unsigned type
1177     if (RHSSigned) {
1178       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1179       return LHSType;
1180     } else if (!IsCompAssign)
1181       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1182     return RHSType;
1183   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1184     // The two types are different widths; if we are here, that
1185     // means the signed type is larger than the unsigned type, so
1186     // use the signed type.
1187     if (LHSSigned) {
1188       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1189       return LHSType;
1190     } else if (!IsCompAssign)
1191       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1192     return RHSType;
1193   } else {
1194     // The signed type is higher-ranked than the unsigned type,
1195     // but isn't actually any bigger (like unsigned int and long
1196     // on most 32-bit systems).  Use the unsigned type corresponding
1197     // to the signed type.
1198     QualType result =
1199       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1200     RHS = (*doRHSCast)(S, RHS.get(), result);
1201     if (!IsCompAssign)
1202       LHS = (*doLHSCast)(S, LHS.get(), result);
1203     return result;
1204   }
1205 }
1206
1207 /// \brief Handle conversions with GCC complex int extension.  Helper function
1208 /// of UsualArithmeticConversions()
1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1210                                            ExprResult &RHS, QualType LHSType,
1211                                            QualType RHSType,
1212                                            bool IsCompAssign) {
1213   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1214   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1215
1216   if (LHSComplexInt && RHSComplexInt) {
1217     QualType LHSEltType = LHSComplexInt->getElementType();
1218     QualType RHSEltType = RHSComplexInt->getElementType();
1219     QualType ScalarType =
1220       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1221         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1222
1223     return S.Context.getComplexType(ScalarType);
1224   }
1225
1226   if (LHSComplexInt) {
1227     QualType LHSEltType = LHSComplexInt->getElementType();
1228     QualType ScalarType =
1229       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1230         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1231     QualType ComplexType = S.Context.getComplexType(ScalarType);
1232     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1233                               CK_IntegralRealToComplex);
1234  
1235     return ComplexType;
1236   }
1237
1238   assert(RHSComplexInt);
1239
1240   QualType RHSEltType = RHSComplexInt->getElementType();
1241   QualType ScalarType =
1242     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1243       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1244   QualType ComplexType = S.Context.getComplexType(ScalarType);
1245   
1246   if (!IsCompAssign)
1247     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1248                               CK_IntegralRealToComplex);
1249   return ComplexType;
1250 }
1251
1252 /// UsualArithmeticConversions - Performs various conversions that are common to
1253 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1254 /// routine returns the first non-arithmetic type found. The client is
1255 /// responsible for emitting appropriate error diagnostics.
1256 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1257                                           bool IsCompAssign) {
1258   if (!IsCompAssign) {
1259     LHS = UsualUnaryConversions(LHS.get());
1260     if (LHS.isInvalid())
1261       return QualType();
1262   }
1263
1264   RHS = UsualUnaryConversions(RHS.get());
1265   if (RHS.isInvalid())
1266     return QualType();
1267
1268   // For conversion purposes, we ignore any qualifiers.
1269   // For example, "const float" and "float" are equivalent.
1270   QualType LHSType =
1271     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1272   QualType RHSType =
1273     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1274
1275   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1276   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1277     LHSType = AtomicLHS->getValueType();
1278
1279   // If both types are identical, no conversion is needed.
1280   if (LHSType == RHSType)
1281     return LHSType;
1282
1283   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1284   // The caller can deal with this (e.g. pointer + int).
1285   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1286     return QualType();
1287
1288   // Apply unary and bitfield promotions to the LHS's type.
1289   QualType LHSUnpromotedType = LHSType;
1290   if (LHSType->isPromotableIntegerType())
1291     LHSType = Context.getPromotedIntegerType(LHSType);
1292   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1293   if (!LHSBitfieldPromoteTy.isNull())
1294     LHSType = LHSBitfieldPromoteTy;
1295   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1296     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1297
1298   // If both types are identical, no conversion is needed.
1299   if (LHSType == RHSType)
1300     return LHSType;
1301
1302   // At this point, we have two different arithmetic types.
1303
1304   // Handle complex types first (C99 6.3.1.8p1).
1305   if (LHSType->isComplexType() || RHSType->isComplexType())
1306     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1307                                         IsCompAssign);
1308
1309   // Now handle "real" floating types (i.e. float, double, long double).
1310   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1311     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1312                                  IsCompAssign);
1313
1314   // Handle GCC complex int extension.
1315   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1316     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1317                                       IsCompAssign);
1318
1319   // Finally, we have two differing integer types.
1320   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1321            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1322 }
1323
1324
1325 //===----------------------------------------------------------------------===//
1326 //  Semantic Analysis for various Expression Types
1327 //===----------------------------------------------------------------------===//
1328
1329
1330 ExprResult
1331 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1332                                 SourceLocation DefaultLoc,
1333                                 SourceLocation RParenLoc,
1334                                 Expr *ControllingExpr,
1335                                 ArrayRef<ParsedType> ArgTypes,
1336                                 ArrayRef<Expr *> ArgExprs) {
1337   unsigned NumAssocs = ArgTypes.size();
1338   assert(NumAssocs == ArgExprs.size());
1339
1340   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1341   for (unsigned i = 0; i < NumAssocs; ++i) {
1342     if (ArgTypes[i])
1343       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1344     else
1345       Types[i] = nullptr;
1346   }
1347
1348   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1349                                              ControllingExpr,
1350                                              llvm::makeArrayRef(Types, NumAssocs),
1351                                              ArgExprs);
1352   delete [] Types;
1353   return ER;
1354 }
1355
1356 ExprResult
1357 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1358                                  SourceLocation DefaultLoc,
1359                                  SourceLocation RParenLoc,
1360                                  Expr *ControllingExpr,
1361                                  ArrayRef<TypeSourceInfo *> Types,
1362                                  ArrayRef<Expr *> Exprs) {
1363   unsigned NumAssocs = Types.size();
1364   assert(NumAssocs == Exprs.size());
1365
1366   // Decay and strip qualifiers for the controlling expression type, and handle
1367   // placeholder type replacement. See committee discussion from WG14 DR423.
1368   {
1369     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1370     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1371     if (R.isInvalid())
1372       return ExprError();
1373     ControllingExpr = R.get();
1374   }
1375
1376   // The controlling expression is an unevaluated operand, so side effects are
1377   // likely unintended.
1378   if (ActiveTemplateInstantiations.empty() &&
1379       ControllingExpr->HasSideEffects(Context, false))
1380     Diag(ControllingExpr->getExprLoc(),
1381          diag::warn_side_effects_unevaluated_context);
1382
1383   bool TypeErrorFound = false,
1384        IsResultDependent = ControllingExpr->isTypeDependent(),
1385        ContainsUnexpandedParameterPack
1386          = ControllingExpr->containsUnexpandedParameterPack();
1387
1388   for (unsigned i = 0; i < NumAssocs; ++i) {
1389     if (Exprs[i]->containsUnexpandedParameterPack())
1390       ContainsUnexpandedParameterPack = true;
1391
1392     if (Types[i]) {
1393       if (Types[i]->getType()->containsUnexpandedParameterPack())
1394         ContainsUnexpandedParameterPack = true;
1395
1396       if (Types[i]->getType()->isDependentType()) {
1397         IsResultDependent = true;
1398       } else {
1399         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1400         // complete object type other than a variably modified type."
1401         unsigned D = 0;
1402         if (Types[i]->getType()->isIncompleteType())
1403           D = diag::err_assoc_type_incomplete;
1404         else if (!Types[i]->getType()->isObjectType())
1405           D = diag::err_assoc_type_nonobject;
1406         else if (Types[i]->getType()->isVariablyModifiedType())
1407           D = diag::err_assoc_type_variably_modified;
1408
1409         if (D != 0) {
1410           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1411             << Types[i]->getTypeLoc().getSourceRange()
1412             << Types[i]->getType();
1413           TypeErrorFound = true;
1414         }
1415
1416         // C11 6.5.1.1p2 "No two generic associations in the same generic
1417         // selection shall specify compatible types."
1418         for (unsigned j = i+1; j < NumAssocs; ++j)
1419           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1420               Context.typesAreCompatible(Types[i]->getType(),
1421                                          Types[j]->getType())) {
1422             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1423                  diag::err_assoc_compatible_types)
1424               << Types[j]->getTypeLoc().getSourceRange()
1425               << Types[j]->getType()
1426               << Types[i]->getType();
1427             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1428                  diag::note_compat_assoc)
1429               << Types[i]->getTypeLoc().getSourceRange()
1430               << Types[i]->getType();
1431             TypeErrorFound = true;
1432           }
1433       }
1434     }
1435   }
1436   if (TypeErrorFound)
1437     return ExprError();
1438
1439   // If we determined that the generic selection is result-dependent, don't
1440   // try to compute the result expression.
1441   if (IsResultDependent)
1442     return new (Context) GenericSelectionExpr(
1443         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1444         ContainsUnexpandedParameterPack);
1445
1446   SmallVector<unsigned, 1> CompatIndices;
1447   unsigned DefaultIndex = -1U;
1448   for (unsigned i = 0; i < NumAssocs; ++i) {
1449     if (!Types[i])
1450       DefaultIndex = i;
1451     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1452                                         Types[i]->getType()))
1453       CompatIndices.push_back(i);
1454   }
1455
1456   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1457   // type compatible with at most one of the types named in its generic
1458   // association list."
1459   if (CompatIndices.size() > 1) {
1460     // We strip parens here because the controlling expression is typically
1461     // parenthesized in macro definitions.
1462     ControllingExpr = ControllingExpr->IgnoreParens();
1463     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1464       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1465       << (unsigned) CompatIndices.size();
1466     for (unsigned I : CompatIndices) {
1467       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1468            diag::note_compat_assoc)
1469         << Types[I]->getTypeLoc().getSourceRange()
1470         << Types[I]->getType();
1471     }
1472     return ExprError();
1473   }
1474
1475   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1476   // its controlling expression shall have type compatible with exactly one of
1477   // the types named in its generic association list."
1478   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1479     // We strip parens here because the controlling expression is typically
1480     // parenthesized in macro definitions.
1481     ControllingExpr = ControllingExpr->IgnoreParens();
1482     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1483       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1484     return ExprError();
1485   }
1486
1487   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1488   // type name that is compatible with the type of the controlling expression,
1489   // then the result expression of the generic selection is the expression
1490   // in that generic association. Otherwise, the result expression of the
1491   // generic selection is the expression in the default generic association."
1492   unsigned ResultIndex =
1493     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1494
1495   return new (Context) GenericSelectionExpr(
1496       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1497       ContainsUnexpandedParameterPack, ResultIndex);
1498 }
1499
1500 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1501 /// location of the token and the offset of the ud-suffix within it.
1502 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1503                                      unsigned Offset) {
1504   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1505                                         S.getLangOpts());
1506 }
1507
1508 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1509 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1510 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1511                                                  IdentifierInfo *UDSuffix,
1512                                                  SourceLocation UDSuffixLoc,
1513                                                  ArrayRef<Expr*> Args,
1514                                                  SourceLocation LitEndLoc) {
1515   assert(Args.size() <= 2 && "too many arguments for literal operator");
1516
1517   QualType ArgTy[2];
1518   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1519     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1520     if (ArgTy[ArgIdx]->isArrayType())
1521       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1522   }
1523
1524   DeclarationName OpName =
1525     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1526   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1527   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1528
1529   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1530   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1531                               /*AllowRaw*/false, /*AllowTemplate*/false,
1532                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1533     return ExprError();
1534
1535   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1536 }
1537
1538 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1539 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1540 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1541 /// multiple tokens.  However, the common case is that StringToks points to one
1542 /// string.
1543 ///
1544 ExprResult
1545 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1546   assert(!StringToks.empty() && "Must have at least one string!");
1547
1548   StringLiteralParser Literal(StringToks, PP);
1549   if (Literal.hadError)
1550     return ExprError();
1551
1552   SmallVector<SourceLocation, 4> StringTokLocs;
1553   for (const Token &Tok : StringToks)
1554     StringTokLocs.push_back(Tok.getLocation());
1555
1556   QualType CharTy = Context.CharTy;
1557   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1558   if (Literal.isWide()) {
1559     CharTy = Context.getWideCharType();
1560     Kind = StringLiteral::Wide;
1561   } else if (Literal.isUTF8()) {
1562     Kind = StringLiteral::UTF8;
1563   } else if (Literal.isUTF16()) {
1564     CharTy = Context.Char16Ty;
1565     Kind = StringLiteral::UTF16;
1566   } else if (Literal.isUTF32()) {
1567     CharTy = Context.Char32Ty;
1568     Kind = StringLiteral::UTF32;
1569   } else if (Literal.isPascal()) {
1570     CharTy = Context.UnsignedCharTy;
1571   }
1572
1573   QualType CharTyConst = CharTy;
1574   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1575   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1576     CharTyConst.addConst();
1577
1578   // Get an array type for the string, according to C99 6.4.5.  This includes
1579   // the nul terminator character as well as the string length for pascal
1580   // strings.
1581   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1582                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1583                                  ArrayType::Normal, 0);
1584
1585   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1586   if (getLangOpts().OpenCL) {
1587     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1588   }
1589
1590   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1591   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1592                                              Kind, Literal.Pascal, StrTy,
1593                                              &StringTokLocs[0],
1594                                              StringTokLocs.size());
1595   if (Literal.getUDSuffix().empty())
1596     return Lit;
1597
1598   // We're building a user-defined literal.
1599   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1600   SourceLocation UDSuffixLoc =
1601     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1602                    Literal.getUDSuffixOffset());
1603
1604   // Make sure we're allowed user-defined literals here.
1605   if (!UDLScope)
1606     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1607
1608   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1609   //   operator "" X (str, len)
1610   QualType SizeType = Context.getSizeType();
1611
1612   DeclarationName OpName =
1613     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1614   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1615   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1616
1617   QualType ArgTy[] = {
1618     Context.getArrayDecayedType(StrTy), SizeType
1619   };
1620
1621   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1622   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1623                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1624                                 /*AllowStringTemplate*/true)) {
1625
1626   case LOLR_Cooked: {
1627     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1628     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1629                                                     StringTokLocs[0]);
1630     Expr *Args[] = { Lit, LenArg };
1631
1632     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1633   }
1634
1635   case LOLR_StringTemplate: {
1636     TemplateArgumentListInfo ExplicitArgs;
1637
1638     unsigned CharBits = Context.getIntWidth(CharTy);
1639     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1640     llvm::APSInt Value(CharBits, CharIsUnsigned);
1641
1642     TemplateArgument TypeArg(CharTy);
1643     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1644     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1645
1646     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1647       Value = Lit->getCodeUnit(I);
1648       TemplateArgument Arg(Context, Value, CharTy);
1649       TemplateArgumentLocInfo ArgInfo;
1650       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1651     }
1652     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1653                                     &ExplicitArgs);
1654   }
1655   case LOLR_Raw:
1656   case LOLR_Template:
1657     llvm_unreachable("unexpected literal operator lookup result");
1658   case LOLR_Error:
1659     return ExprError();
1660   }
1661   llvm_unreachable("unexpected literal operator lookup result");
1662 }
1663
1664 ExprResult
1665 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1666                        SourceLocation Loc,
1667                        const CXXScopeSpec *SS) {
1668   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1669   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1670 }
1671
1672 /// BuildDeclRefExpr - Build an expression that references a
1673 /// declaration that does not require a closure capture.
1674 ExprResult
1675 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1676                        const DeclarationNameInfo &NameInfo,
1677                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1678                        const TemplateArgumentListInfo *TemplateArgs) {
1679   if (getLangOpts().CUDA)
1680     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1681       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1682         if (CheckCUDATarget(Caller, Callee)) {
1683           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1684             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1685             << IdentifyCUDATarget(Caller);
1686           Diag(D->getLocation(), diag::note_previous_decl)
1687             << D->getIdentifier();
1688           return ExprError();
1689         }
1690       }
1691
1692   bool RefersToCapturedVariable =
1693       isa<VarDecl>(D) &&
1694       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1695
1696   DeclRefExpr *E;
1697   if (isa<VarTemplateSpecializationDecl>(D)) {
1698     VarTemplateSpecializationDecl *VarSpec =
1699         cast<VarTemplateSpecializationDecl>(D);
1700
1701     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1702                                         : NestedNameSpecifierLoc(),
1703                             VarSpec->getTemplateKeywordLoc(), D,
1704                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1705                             FoundD, TemplateArgs);
1706   } else {
1707     assert(!TemplateArgs && "No template arguments for non-variable"
1708                             " template specialization references");
1709     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1710                                         : NestedNameSpecifierLoc(),
1711                             SourceLocation(), D, RefersToCapturedVariable,
1712                             NameInfo, Ty, VK, FoundD);
1713   }
1714
1715   MarkDeclRefReferenced(E);
1716
1717   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1718       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1719       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1720       recordUseOfEvaluatedWeak(E);
1721
1722   // Just in case we're building an illegal pointer-to-member.
1723   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1724   if (FD && FD->isBitField())
1725     E->setObjectKind(OK_BitField);
1726
1727   return E;
1728 }
1729
1730 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1731 /// possibly a list of template arguments.
1732 ///
1733 /// If this produces template arguments, it is permitted to call
1734 /// DecomposeTemplateName.
1735 ///
1736 /// This actually loses a lot of source location information for
1737 /// non-standard name kinds; we should consider preserving that in
1738 /// some way.
1739 void
1740 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1741                              TemplateArgumentListInfo &Buffer,
1742                              DeclarationNameInfo &NameInfo,
1743                              const TemplateArgumentListInfo *&TemplateArgs) {
1744   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1745     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1746     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1747
1748     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1749                                        Id.TemplateId->NumArgs);
1750     translateTemplateArguments(TemplateArgsPtr, Buffer);
1751
1752     TemplateName TName = Id.TemplateId->Template.get();
1753     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1754     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1755     TemplateArgs = &Buffer;
1756   } else {
1757     NameInfo = GetNameFromUnqualifiedId(Id);
1758     TemplateArgs = nullptr;
1759   }
1760 }
1761
1762 static void emitEmptyLookupTypoDiagnostic(
1763     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1764     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1765     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1766   DeclContext *Ctx =
1767       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1768   if (!TC) {
1769     // Emit a special diagnostic for failed member lookups.
1770     // FIXME: computing the declaration context might fail here (?)
1771     if (Ctx)
1772       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1773                                                  << SS.getRange();
1774     else
1775       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1776     return;
1777   }
1778
1779   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1780   bool DroppedSpecifier =
1781       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1782   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1783                         ? diag::note_implicit_param_decl
1784                         : diag::note_previous_decl;
1785   if (!Ctx)
1786     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1787                          SemaRef.PDiag(NoteID));
1788   else
1789     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1790                                  << Typo << Ctx << DroppedSpecifier
1791                                  << SS.getRange(),
1792                          SemaRef.PDiag(NoteID));
1793 }
1794
1795 /// Diagnose an empty lookup.
1796 ///
1797 /// \return false if new lookup candidates were found
1798 bool
1799 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1800                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1801                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1802                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1803   DeclarationName Name = R.getLookupName();
1804
1805   unsigned diagnostic = diag::err_undeclared_var_use;
1806   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1807   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1808       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1809       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1810     diagnostic = diag::err_undeclared_use;
1811     diagnostic_suggest = diag::err_undeclared_use_suggest;
1812   }
1813
1814   // If the original lookup was an unqualified lookup, fake an
1815   // unqualified lookup.  This is useful when (for example) the
1816   // original lookup would not have found something because it was a
1817   // dependent name.
1818   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1819   while (DC) {
1820     if (isa<CXXRecordDecl>(DC)) {
1821       LookupQualifiedName(R, DC);
1822
1823       if (!R.empty()) {
1824         // Don't give errors about ambiguities in this lookup.
1825         R.suppressDiagnostics();
1826
1827         // During a default argument instantiation the CurContext points
1828         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1829         // function parameter list, hence add an explicit check.
1830         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1831                               ActiveTemplateInstantiations.back().Kind ==
1832             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1833         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1834         bool isInstance = CurMethod &&
1835                           CurMethod->isInstance() &&
1836                           DC == CurMethod->getParent() && !isDefaultArgument;
1837
1838         // Give a code modification hint to insert 'this->'.
1839         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1840         // Actually quite difficult!
1841         if (getLangOpts().MSVCCompat)
1842           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1843         if (isInstance) {
1844           Diag(R.getNameLoc(), diagnostic) << Name
1845             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1846           CheckCXXThisCapture(R.getNameLoc());
1847         } else {
1848           Diag(R.getNameLoc(), diagnostic) << Name;
1849         }
1850
1851         // Do we really want to note all of these?
1852         for (NamedDecl *D : R)
1853           Diag(D->getLocation(), diag::note_dependent_var_use);
1854
1855         // Return true if we are inside a default argument instantiation
1856         // and the found name refers to an instance member function, otherwise
1857         // the function calling DiagnoseEmptyLookup will try to create an
1858         // implicit member call and this is wrong for default argument.
1859         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1860           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1861           return true;
1862         }
1863
1864         // Tell the callee to try to recover.
1865         return false;
1866       }
1867
1868       R.clear();
1869     }
1870
1871     // In Microsoft mode, if we are performing lookup from within a friend
1872     // function definition declared at class scope then we must set
1873     // DC to the lexical parent to be able to search into the parent
1874     // class.
1875     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1876         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1877         DC->getLexicalParent()->isRecord())
1878       DC = DC->getLexicalParent();
1879     else
1880       DC = DC->getParent();
1881   }
1882
1883   // We didn't find anything, so try to correct for a typo.
1884   TypoCorrection Corrected;
1885   if (S && Out) {
1886     SourceLocation TypoLoc = R.getNameLoc();
1887     assert(!ExplicitTemplateArgs &&
1888            "Diagnosing an empty lookup with explicit template args!");
1889     *Out = CorrectTypoDelayed(
1890         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1891         [=](const TypoCorrection &TC) {
1892           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1893                                         diagnostic, diagnostic_suggest);
1894         },
1895         nullptr, CTK_ErrorRecovery);
1896     if (*Out)
1897       return true;
1898   } else if (S && (Corrected =
1899                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1900                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1901     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1902     bool DroppedSpecifier =
1903         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1904     R.setLookupName(Corrected.getCorrection());
1905
1906     bool AcceptableWithRecovery = false;
1907     bool AcceptableWithoutRecovery = false;
1908     NamedDecl *ND = Corrected.getFoundDecl();
1909     if (ND) {
1910       if (Corrected.isOverloaded()) {
1911         OverloadCandidateSet OCS(R.getNameLoc(),
1912                                  OverloadCandidateSet::CSK_Normal);
1913         OverloadCandidateSet::iterator Best;
1914         for (NamedDecl *CD : Corrected) {
1915           if (FunctionTemplateDecl *FTD =
1916                    dyn_cast<FunctionTemplateDecl>(CD))
1917             AddTemplateOverloadCandidate(
1918                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1919                 Args, OCS);
1920           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1921             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1922               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1923                                    Args, OCS);
1924         }
1925         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1926         case OR_Success:
1927           ND = Best->FoundDecl;
1928           Corrected.setCorrectionDecl(ND);
1929           break;
1930         default:
1931           // FIXME: Arbitrarily pick the first declaration for the note.
1932           Corrected.setCorrectionDecl(ND);
1933           break;
1934         }
1935       }
1936       R.addDecl(ND);
1937       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1938         CXXRecordDecl *Record = nullptr;
1939         if (Corrected.getCorrectionSpecifier()) {
1940           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1941           Record = Ty->getAsCXXRecordDecl();
1942         }
1943         if (!Record)
1944           Record = cast<CXXRecordDecl>(
1945               ND->getDeclContext()->getRedeclContext());
1946         R.setNamingClass(Record);
1947       }
1948
1949       auto *UnderlyingND = ND->getUnderlyingDecl();
1950       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1951                                isa<FunctionTemplateDecl>(UnderlyingND);
1952       // FIXME: If we ended up with a typo for a type name or
1953       // Objective-C class name, we're in trouble because the parser
1954       // is in the wrong place to recover. Suggest the typo
1955       // correction, but don't make it a fix-it since we're not going
1956       // to recover well anyway.
1957       AcceptableWithoutRecovery =
1958           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1959     } else {
1960       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1961       // because we aren't able to recover.
1962       AcceptableWithoutRecovery = true;
1963     }
1964
1965     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1966       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1967                             ? diag::note_implicit_param_decl
1968                             : diag::note_previous_decl;
1969       if (SS.isEmpty())
1970         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1971                      PDiag(NoteID), AcceptableWithRecovery);
1972       else
1973         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1974                                   << Name << computeDeclContext(SS, false)
1975                                   << DroppedSpecifier << SS.getRange(),
1976                      PDiag(NoteID), AcceptableWithRecovery);
1977
1978       // Tell the callee whether to try to recover.
1979       return !AcceptableWithRecovery;
1980     }
1981   }
1982   R.clear();
1983
1984   // Emit a special diagnostic for failed member lookups.
1985   // FIXME: computing the declaration context might fail here (?)
1986   if (!SS.isEmpty()) {
1987     Diag(R.getNameLoc(), diag::err_no_member)
1988       << Name << computeDeclContext(SS, false)
1989       << SS.getRange();
1990     return true;
1991   }
1992
1993   // Give up, we can't recover.
1994   Diag(R.getNameLoc(), diagnostic) << Name;
1995   return true;
1996 }
1997
1998 /// In Microsoft mode, if we are inside a template class whose parent class has
1999 /// dependent base classes, and we can't resolve an unqualified identifier, then
2000 /// assume the identifier is a member of a dependent base class.  We can only
2001 /// recover successfully in static methods, instance methods, and other contexts
2002 /// where 'this' is available.  This doesn't precisely match MSVC's
2003 /// instantiation model, but it's close enough.
2004 static Expr *
2005 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2006                                DeclarationNameInfo &NameInfo,
2007                                SourceLocation TemplateKWLoc,
2008                                const TemplateArgumentListInfo *TemplateArgs) {
2009   // Only try to recover from lookup into dependent bases in static methods or
2010   // contexts where 'this' is available.
2011   QualType ThisType = S.getCurrentThisType();
2012   const CXXRecordDecl *RD = nullptr;
2013   if (!ThisType.isNull())
2014     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2015   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2016     RD = MD->getParent();
2017   if (!RD || !RD->hasAnyDependentBases())
2018     return nullptr;
2019
2020   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2021   // is available, suggest inserting 'this->' as a fixit.
2022   SourceLocation Loc = NameInfo.getLoc();
2023   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2024   DB << NameInfo.getName() << RD;
2025
2026   if (!ThisType.isNull()) {
2027     DB << FixItHint::CreateInsertion(Loc, "this->");
2028     return CXXDependentScopeMemberExpr::Create(
2029         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2030         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2031         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2032   }
2033
2034   // Synthesize a fake NNS that points to the derived class.  This will
2035   // perform name lookup during template instantiation.
2036   CXXScopeSpec SS;
2037   auto *NNS =
2038       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2039   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2040   return DependentScopeDeclRefExpr::Create(
2041       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2042       TemplateArgs);
2043 }
2044
2045 ExprResult
2046 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2047                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2048                         bool HasTrailingLParen, bool IsAddressOfOperand,
2049                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2050                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2051   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2052          "cannot be direct & operand and have a trailing lparen");
2053   if (SS.isInvalid())
2054     return ExprError();
2055
2056   TemplateArgumentListInfo TemplateArgsBuffer;
2057
2058   // Decompose the UnqualifiedId into the following data.
2059   DeclarationNameInfo NameInfo;
2060   const TemplateArgumentListInfo *TemplateArgs;
2061   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2062
2063   DeclarationName Name = NameInfo.getName();
2064   IdentifierInfo *II = Name.getAsIdentifierInfo();
2065   SourceLocation NameLoc = NameInfo.getLoc();
2066
2067   // C++ [temp.dep.expr]p3:
2068   //   An id-expression is type-dependent if it contains:
2069   //     -- an identifier that was declared with a dependent type,
2070   //        (note: handled after lookup)
2071   //     -- a template-id that is dependent,
2072   //        (note: handled in BuildTemplateIdExpr)
2073   //     -- a conversion-function-id that specifies a dependent type,
2074   //     -- a nested-name-specifier that contains a class-name that
2075   //        names a dependent type.
2076   // Determine whether this is a member of an unknown specialization;
2077   // we need to handle these differently.
2078   bool DependentID = false;
2079   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2080       Name.getCXXNameType()->isDependentType()) {
2081     DependentID = true;
2082   } else if (SS.isSet()) {
2083     if (DeclContext *DC = computeDeclContext(SS, false)) {
2084       if (RequireCompleteDeclContext(SS, DC))
2085         return ExprError();
2086     } else {
2087       DependentID = true;
2088     }
2089   }
2090
2091   if (DependentID)
2092     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2093                                       IsAddressOfOperand, TemplateArgs);
2094
2095   // Perform the required lookup.
2096   LookupResult R(*this, NameInfo, 
2097                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2098                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2099   if (TemplateArgs) {
2100     // Lookup the template name again to correctly establish the context in
2101     // which it was found. This is really unfortunate as we already did the
2102     // lookup to determine that it was a template name in the first place. If
2103     // this becomes a performance hit, we can work harder to preserve those
2104     // results until we get here but it's likely not worth it.
2105     bool MemberOfUnknownSpecialization;
2106     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2107                        MemberOfUnknownSpecialization);
2108     
2109     if (MemberOfUnknownSpecialization ||
2110         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2111       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2112                                         IsAddressOfOperand, TemplateArgs);
2113   } else {
2114     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2115     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2116
2117     // If the result might be in a dependent base class, this is a dependent 
2118     // id-expression.
2119     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2120       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2121                                         IsAddressOfOperand, TemplateArgs);
2122
2123     // If this reference is in an Objective-C method, then we need to do
2124     // some special Objective-C lookup, too.
2125     if (IvarLookupFollowUp) {
2126       ExprResult E(LookupInObjCMethod(R, S, II, true));
2127       if (E.isInvalid())
2128         return ExprError();
2129
2130       if (Expr *Ex = E.getAs<Expr>())
2131         return Ex;
2132     }
2133   }
2134
2135   if (R.isAmbiguous())
2136     return ExprError();
2137
2138   // This could be an implicitly declared function reference (legal in C90,
2139   // extension in C99, forbidden in C++).
2140   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2141     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2142     if (D) R.addDecl(D);
2143   }
2144
2145   // Determine whether this name might be a candidate for
2146   // argument-dependent lookup.
2147   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2148
2149   if (R.empty() && !ADL) {
2150     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2151       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2152                                                    TemplateKWLoc, TemplateArgs))
2153         return E;
2154     }
2155
2156     // Don't diagnose an empty lookup for inline assembly.
2157     if (IsInlineAsmIdentifier)
2158       return ExprError();
2159
2160     // If this name wasn't predeclared and if this is not a function
2161     // call, diagnose the problem.
2162     TypoExpr *TE = nullptr;
2163     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2164         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2165     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2166     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2167            "Typo correction callback misconfigured");
2168     if (CCC) {
2169       // Make sure the callback knows what the typo being diagnosed is.
2170       CCC->setTypoName(II);
2171       if (SS.isValid())
2172         CCC->setTypoNNS(SS.getScopeRep());
2173     }
2174     if (DiagnoseEmptyLookup(S, SS, R,
2175                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2176                             nullptr, None, &TE)) {
2177       if (TE && KeywordReplacement) {
2178         auto &State = getTypoExprState(TE);
2179         auto BestTC = State.Consumer->getNextCorrection();
2180         if (BestTC.isKeyword()) {
2181           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2182           if (State.DiagHandler)
2183             State.DiagHandler(BestTC);
2184           KeywordReplacement->startToken();
2185           KeywordReplacement->setKind(II->getTokenID());
2186           KeywordReplacement->setIdentifierInfo(II);
2187           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2188           // Clean up the state associated with the TypoExpr, since it has
2189           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2190           clearDelayedTypo(TE);
2191           // Signal that a correction to a keyword was performed by returning a
2192           // valid-but-null ExprResult.
2193           return (Expr*)nullptr;
2194         }
2195         State.Consumer->resetCorrectionStream();
2196       }
2197       return TE ? TE : ExprError();
2198     }
2199
2200     assert(!R.empty() &&
2201            "DiagnoseEmptyLookup returned false but added no results");
2202
2203     // If we found an Objective-C instance variable, let
2204     // LookupInObjCMethod build the appropriate expression to
2205     // reference the ivar.
2206     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2207       R.clear();
2208       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2209       // In a hopelessly buggy code, Objective-C instance variable
2210       // lookup fails and no expression will be built to reference it.
2211       if (!E.isInvalid() && !E.get())
2212         return ExprError();
2213       return E;
2214     }
2215   }
2216
2217   // This is guaranteed from this point on.
2218   assert(!R.empty() || ADL);
2219
2220   // Check whether this might be a C++ implicit instance member access.
2221   // C++ [class.mfct.non-static]p3:
2222   //   When an id-expression that is not part of a class member access
2223   //   syntax and not used to form a pointer to member is used in the
2224   //   body of a non-static member function of class X, if name lookup
2225   //   resolves the name in the id-expression to a non-static non-type
2226   //   member of some class C, the id-expression is transformed into a
2227   //   class member access expression using (*this) as the
2228   //   postfix-expression to the left of the . operator.
2229   //
2230   // But we don't actually need to do this for '&' operands if R
2231   // resolved to a function or overloaded function set, because the
2232   // expression is ill-formed if it actually works out to be a
2233   // non-static member function:
2234   //
2235   // C++ [expr.ref]p4:
2236   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2237   //   [t]he expression can be used only as the left-hand operand of a
2238   //   member function call.
2239   //
2240   // There are other safeguards against such uses, but it's important
2241   // to get this right here so that we don't end up making a
2242   // spuriously dependent expression if we're inside a dependent
2243   // instance method.
2244   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2245     bool MightBeImplicitMember;
2246     if (!IsAddressOfOperand)
2247       MightBeImplicitMember = true;
2248     else if (!SS.isEmpty())
2249       MightBeImplicitMember = false;
2250     else if (R.isOverloadedResult())
2251       MightBeImplicitMember = false;
2252     else if (R.isUnresolvableResult())
2253       MightBeImplicitMember = true;
2254     else
2255       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2256                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2257                               isa<MSPropertyDecl>(R.getFoundDecl());
2258
2259     if (MightBeImplicitMember)
2260       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2261                                              R, TemplateArgs, S);
2262   }
2263
2264   if (TemplateArgs || TemplateKWLoc.isValid()) {
2265
2266     // In C++1y, if this is a variable template id, then check it
2267     // in BuildTemplateIdExpr().
2268     // The single lookup result must be a variable template declaration.
2269     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2270         Id.TemplateId->Kind == TNK_Var_template) {
2271       assert(R.getAsSingle<VarTemplateDecl>() &&
2272              "There should only be one declaration found.");
2273     }
2274
2275     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2276   }
2277
2278   return BuildDeclarationNameExpr(SS, R, ADL);
2279 }
2280
2281 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2282 /// declaration name, generally during template instantiation.
2283 /// There's a large number of things which don't need to be done along
2284 /// this path.
2285 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2286     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2287     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2288   DeclContext *DC = computeDeclContext(SS, false);
2289   if (!DC)
2290     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2291                                      NameInfo, /*TemplateArgs=*/nullptr);
2292
2293   if (RequireCompleteDeclContext(SS, DC))
2294     return ExprError();
2295
2296   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2297   LookupQualifiedName(R, DC);
2298
2299   if (R.isAmbiguous())
2300     return ExprError();
2301
2302   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2303     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2304                                      NameInfo, /*TemplateArgs=*/nullptr);
2305
2306   if (R.empty()) {
2307     Diag(NameInfo.getLoc(), diag::err_no_member)
2308       << NameInfo.getName() << DC << SS.getRange();
2309     return ExprError();
2310   }
2311
2312   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2313     // Diagnose a missing typename if this resolved unambiguously to a type in
2314     // a dependent context.  If we can recover with a type, downgrade this to
2315     // a warning in Microsoft compatibility mode.
2316     unsigned DiagID = diag::err_typename_missing;
2317     if (RecoveryTSI && getLangOpts().MSVCCompat)
2318       DiagID = diag::ext_typename_missing;
2319     SourceLocation Loc = SS.getBeginLoc();
2320     auto D = Diag(Loc, DiagID);
2321     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2322       << SourceRange(Loc, NameInfo.getEndLoc());
2323
2324     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2325     // context.
2326     if (!RecoveryTSI)
2327       return ExprError();
2328
2329     // Only issue the fixit if we're prepared to recover.
2330     D << FixItHint::CreateInsertion(Loc, "typename ");
2331
2332     // Recover by pretending this was an elaborated type.
2333     QualType Ty = Context.getTypeDeclType(TD);
2334     TypeLocBuilder TLB;
2335     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2336
2337     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2338     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2339     QTL.setElaboratedKeywordLoc(SourceLocation());
2340     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2341
2342     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2343
2344     return ExprEmpty();
2345   }
2346
2347   // Defend against this resolving to an implicit member access. We usually
2348   // won't get here if this might be a legitimate a class member (we end up in
2349   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2350   // a pointer-to-member or in an unevaluated context in C++11.
2351   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2352     return BuildPossibleImplicitMemberExpr(SS,
2353                                            /*TemplateKWLoc=*/SourceLocation(),
2354                                            R, /*TemplateArgs=*/nullptr, S);
2355
2356   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2357 }
2358
2359 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2360 /// detected that we're currently inside an ObjC method.  Perform some
2361 /// additional lookup.
2362 ///
2363 /// Ideally, most of this would be done by lookup, but there's
2364 /// actually quite a lot of extra work involved.
2365 ///
2366 /// Returns a null sentinel to indicate trivial success.
2367 ExprResult
2368 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2369                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2370   SourceLocation Loc = Lookup.getNameLoc();
2371   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2372   
2373   // Check for error condition which is already reported.
2374   if (!CurMethod)
2375     return ExprError();
2376
2377   // There are two cases to handle here.  1) scoped lookup could have failed,
2378   // in which case we should look for an ivar.  2) scoped lookup could have
2379   // found a decl, but that decl is outside the current instance method (i.e.
2380   // a global variable).  In these two cases, we do a lookup for an ivar with
2381   // this name, if the lookup sucedes, we replace it our current decl.
2382
2383   // If we're in a class method, we don't normally want to look for
2384   // ivars.  But if we don't find anything else, and there's an
2385   // ivar, that's an error.
2386   bool IsClassMethod = CurMethod->isClassMethod();
2387
2388   bool LookForIvars;
2389   if (Lookup.empty())
2390     LookForIvars = true;
2391   else if (IsClassMethod)
2392     LookForIvars = false;
2393   else
2394     LookForIvars = (Lookup.isSingleResult() &&
2395                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2396   ObjCInterfaceDecl *IFace = nullptr;
2397   if (LookForIvars) {
2398     IFace = CurMethod->getClassInterface();
2399     ObjCInterfaceDecl *ClassDeclared;
2400     ObjCIvarDecl *IV = nullptr;
2401     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2402       // Diagnose using an ivar in a class method.
2403       if (IsClassMethod)
2404         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2405                          << IV->getDeclName());
2406
2407       // If we're referencing an invalid decl, just return this as a silent
2408       // error node.  The error diagnostic was already emitted on the decl.
2409       if (IV->isInvalidDecl())
2410         return ExprError();
2411
2412       // Check if referencing a field with __attribute__((deprecated)).
2413       if (DiagnoseUseOfDecl(IV, Loc))
2414         return ExprError();
2415
2416       // Diagnose the use of an ivar outside of the declaring class.
2417       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2418           !declaresSameEntity(ClassDeclared, IFace) &&
2419           !getLangOpts().DebuggerSupport)
2420         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2421
2422       // FIXME: This should use a new expr for a direct reference, don't
2423       // turn this into Self->ivar, just return a BareIVarExpr or something.
2424       IdentifierInfo &II = Context.Idents.get("self");
2425       UnqualifiedId SelfName;
2426       SelfName.setIdentifier(&II, SourceLocation());
2427       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2428       CXXScopeSpec SelfScopeSpec;
2429       SourceLocation TemplateKWLoc;
2430       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2431                                               SelfName, false, false);
2432       if (SelfExpr.isInvalid())
2433         return ExprError();
2434
2435       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2436       if (SelfExpr.isInvalid())
2437         return ExprError();
2438
2439       MarkAnyDeclReferenced(Loc, IV, true);
2440
2441       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2442       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2443           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2444         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2445
2446       ObjCIvarRefExpr *Result = new (Context)
2447           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2448                           IV->getLocation(), SelfExpr.get(), true, true);
2449
2450       if (getLangOpts().ObjCAutoRefCount) {
2451         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2452           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2453             recordUseOfEvaluatedWeak(Result);
2454         }
2455         if (CurContext->isClosure())
2456           Diag(Loc, diag::warn_implicitly_retains_self)
2457             << FixItHint::CreateInsertion(Loc, "self->");
2458       }
2459       
2460       return Result;
2461     }
2462   } else if (CurMethod->isInstanceMethod()) {
2463     // We should warn if a local variable hides an ivar.
2464     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2465       ObjCInterfaceDecl *ClassDeclared;
2466       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2467         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2468             declaresSameEntity(IFace, ClassDeclared))
2469           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2470       }
2471     }
2472   } else if (Lookup.isSingleResult() &&
2473              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2474     // If accessing a stand-alone ivar in a class method, this is an error.
2475     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2476       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2477                        << IV->getDeclName());
2478   }
2479
2480   if (Lookup.empty() && II && AllowBuiltinCreation) {
2481     // FIXME. Consolidate this with similar code in LookupName.
2482     if (unsigned BuiltinID = II->getBuiltinID()) {
2483       if (!(getLangOpts().CPlusPlus &&
2484             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2485         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2486                                            S, Lookup.isForRedeclaration(),
2487                                            Lookup.getNameLoc());
2488         if (D) Lookup.addDecl(D);
2489       }
2490     }
2491   }
2492   // Sentinel value saying that we didn't do anything special.
2493   return ExprResult((Expr *)nullptr);
2494 }
2495
2496 /// \brief Cast a base object to a member's actual type.
2497 ///
2498 /// Logically this happens in three phases:
2499 ///
2500 /// * First we cast from the base type to the naming class.
2501 ///   The naming class is the class into which we were looking
2502 ///   when we found the member;  it's the qualifier type if a
2503 ///   qualifier was provided, and otherwise it's the base type.
2504 ///
2505 /// * Next we cast from the naming class to the declaring class.
2506 ///   If the member we found was brought into a class's scope by
2507 ///   a using declaration, this is that class;  otherwise it's
2508 ///   the class declaring the member.
2509 ///
2510 /// * Finally we cast from the declaring class to the "true"
2511 ///   declaring class of the member.  This conversion does not
2512 ///   obey access control.
2513 ExprResult
2514 Sema::PerformObjectMemberConversion(Expr *From,
2515                                     NestedNameSpecifier *Qualifier,
2516                                     NamedDecl *FoundDecl,
2517                                     NamedDecl *Member) {
2518   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2519   if (!RD)
2520     return From;
2521
2522   QualType DestRecordType;
2523   QualType DestType;
2524   QualType FromRecordType;
2525   QualType FromType = From->getType();
2526   bool PointerConversions = false;
2527   if (isa<FieldDecl>(Member)) {
2528     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2529
2530     if (FromType->getAs<PointerType>()) {
2531       DestType = Context.getPointerType(DestRecordType);
2532       FromRecordType = FromType->getPointeeType();
2533       PointerConversions = true;
2534     } else {
2535       DestType = DestRecordType;
2536       FromRecordType = FromType;
2537     }
2538   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2539     if (Method->isStatic())
2540       return From;
2541
2542     DestType = Method->getThisType(Context);
2543     DestRecordType = DestType->getPointeeType();
2544
2545     if (FromType->getAs<PointerType>()) {
2546       FromRecordType = FromType->getPointeeType();
2547       PointerConversions = true;
2548     } else {
2549       FromRecordType = FromType;
2550       DestType = DestRecordType;
2551     }
2552   } else {
2553     // No conversion necessary.
2554     return From;
2555   }
2556
2557   if (DestType->isDependentType() || FromType->isDependentType())
2558     return From;
2559
2560   // If the unqualified types are the same, no conversion is necessary.
2561   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2562     return From;
2563
2564   SourceRange FromRange = From->getSourceRange();
2565   SourceLocation FromLoc = FromRange.getBegin();
2566
2567   ExprValueKind VK = From->getValueKind();
2568
2569   // C++ [class.member.lookup]p8:
2570   //   [...] Ambiguities can often be resolved by qualifying a name with its
2571   //   class name.
2572   //
2573   // If the member was a qualified name and the qualified referred to a
2574   // specific base subobject type, we'll cast to that intermediate type
2575   // first and then to the object in which the member is declared. That allows
2576   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2577   //
2578   //   class Base { public: int x; };
2579   //   class Derived1 : public Base { };
2580   //   class Derived2 : public Base { };
2581   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2582   //
2583   //   void VeryDerived::f() {
2584   //     x = 17; // error: ambiguous base subobjects
2585   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2586   //   }
2587   if (Qualifier && Qualifier->getAsType()) {
2588     QualType QType = QualType(Qualifier->getAsType(), 0);
2589     assert(QType->isRecordType() && "lookup done with non-record type");
2590
2591     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2592
2593     // In C++98, the qualifier type doesn't actually have to be a base
2594     // type of the object type, in which case we just ignore it.
2595     // Otherwise build the appropriate casts.
2596     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2597       CXXCastPath BasePath;
2598       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2599                                        FromLoc, FromRange, &BasePath))
2600         return ExprError();
2601
2602       if (PointerConversions)
2603         QType = Context.getPointerType(QType);
2604       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2605                                VK, &BasePath).get();
2606
2607       FromType = QType;
2608       FromRecordType = QRecordType;
2609
2610       // If the qualifier type was the same as the destination type,
2611       // we're done.
2612       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2613         return From;
2614     }
2615   }
2616
2617   bool IgnoreAccess = false;
2618
2619   // If we actually found the member through a using declaration, cast
2620   // down to the using declaration's type.
2621   //
2622   // Pointer equality is fine here because only one declaration of a
2623   // class ever has member declarations.
2624   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2625     assert(isa<UsingShadowDecl>(FoundDecl));
2626     QualType URecordType = Context.getTypeDeclType(
2627                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2628
2629     // We only need to do this if the naming-class to declaring-class
2630     // conversion is non-trivial.
2631     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2632       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2633       CXXCastPath BasePath;
2634       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2635                                        FromLoc, FromRange, &BasePath))
2636         return ExprError();
2637
2638       QualType UType = URecordType;
2639       if (PointerConversions)
2640         UType = Context.getPointerType(UType);
2641       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2642                                VK, &BasePath).get();
2643       FromType = UType;
2644       FromRecordType = URecordType;
2645     }
2646
2647     // We don't do access control for the conversion from the
2648     // declaring class to the true declaring class.
2649     IgnoreAccess = true;
2650   }
2651
2652   CXXCastPath BasePath;
2653   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2654                                    FromLoc, FromRange, &BasePath,
2655                                    IgnoreAccess))
2656     return ExprError();
2657
2658   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2659                            VK, &BasePath);
2660 }
2661
2662 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2663                                       const LookupResult &R,
2664                                       bool HasTrailingLParen) {
2665   // Only when used directly as the postfix-expression of a call.
2666   if (!HasTrailingLParen)
2667     return false;
2668
2669   // Never if a scope specifier was provided.
2670   if (SS.isSet())
2671     return false;
2672
2673   // Only in C++ or ObjC++.
2674   if (!getLangOpts().CPlusPlus)
2675     return false;
2676
2677   // Turn off ADL when we find certain kinds of declarations during
2678   // normal lookup:
2679   for (NamedDecl *D : R) {
2680     // C++0x [basic.lookup.argdep]p3:
2681     //     -- a declaration of a class member
2682     // Since using decls preserve this property, we check this on the
2683     // original decl.
2684     if (D->isCXXClassMember())
2685       return false;
2686
2687     // C++0x [basic.lookup.argdep]p3:
2688     //     -- a block-scope function declaration that is not a
2689     //        using-declaration
2690     // NOTE: we also trigger this for function templates (in fact, we
2691     // don't check the decl type at all, since all other decl types
2692     // turn off ADL anyway).
2693     if (isa<UsingShadowDecl>(D))
2694       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2695     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2696       return false;
2697
2698     // C++0x [basic.lookup.argdep]p3:
2699     //     -- a declaration that is neither a function or a function
2700     //        template
2701     // And also for builtin functions.
2702     if (isa<FunctionDecl>(D)) {
2703       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2704
2705       // But also builtin functions.
2706       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2707         return false;
2708     } else if (!isa<FunctionTemplateDecl>(D))
2709       return false;
2710   }
2711
2712   return true;
2713 }
2714
2715
2716 /// Diagnoses obvious problems with the use of the given declaration
2717 /// as an expression.  This is only actually called for lookups that
2718 /// were not overloaded, and it doesn't promise that the declaration
2719 /// will in fact be used.
2720 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2721   if (isa<TypedefNameDecl>(D)) {
2722     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2723     return true;
2724   }
2725
2726   if (isa<ObjCInterfaceDecl>(D)) {
2727     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2728     return true;
2729   }
2730
2731   if (isa<NamespaceDecl>(D)) {
2732     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2733     return true;
2734   }
2735
2736   return false;
2737 }
2738
2739 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2740                                           LookupResult &R, bool NeedsADL,
2741                                           bool AcceptInvalidDecl) {
2742   // If this is a single, fully-resolved result and we don't need ADL,
2743   // just build an ordinary singleton decl ref.
2744   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2745     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2746                                     R.getRepresentativeDecl(), nullptr,
2747                                     AcceptInvalidDecl);
2748
2749   // We only need to check the declaration if there's exactly one
2750   // result, because in the overloaded case the results can only be
2751   // functions and function templates.
2752   if (R.isSingleResult() &&
2753       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2754     return ExprError();
2755
2756   // Otherwise, just build an unresolved lookup expression.  Suppress
2757   // any lookup-related diagnostics; we'll hash these out later, when
2758   // we've picked a target.
2759   R.suppressDiagnostics();
2760
2761   UnresolvedLookupExpr *ULE
2762     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2763                                    SS.getWithLocInContext(Context),
2764                                    R.getLookupNameInfo(),
2765                                    NeedsADL, R.isOverloadedResult(),
2766                                    R.begin(), R.end());
2767
2768   return ULE;
2769 }
2770
2771 /// \brief Complete semantic analysis for a reference to the given declaration.
2772 ExprResult Sema::BuildDeclarationNameExpr(
2773     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2774     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2775     bool AcceptInvalidDecl) {
2776   assert(D && "Cannot refer to a NULL declaration");
2777   assert(!isa<FunctionTemplateDecl>(D) &&
2778          "Cannot refer unambiguously to a function template");
2779
2780   SourceLocation Loc = NameInfo.getLoc();
2781   if (CheckDeclInExpr(*this, Loc, D))
2782     return ExprError();
2783
2784   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2785     // Specifically diagnose references to class templates that are missing
2786     // a template argument list.
2787     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2788                                            << Template << SS.getRange();
2789     Diag(Template->getLocation(), diag::note_template_decl_here);
2790     return ExprError();
2791   }
2792
2793   // Make sure that we're referring to a value.
2794   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2795   if (!VD) {
2796     Diag(Loc, diag::err_ref_non_value)
2797       << D << SS.getRange();
2798     Diag(D->getLocation(), diag::note_declared_at);
2799     return ExprError();
2800   }
2801
2802   // Check whether this declaration can be used. Note that we suppress
2803   // this check when we're going to perform argument-dependent lookup
2804   // on this function name, because this might not be the function
2805   // that overload resolution actually selects.
2806   if (DiagnoseUseOfDecl(VD, Loc))
2807     return ExprError();
2808
2809   // Only create DeclRefExpr's for valid Decl's.
2810   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2811     return ExprError();
2812
2813   // Handle members of anonymous structs and unions.  If we got here,
2814   // and the reference is to a class member indirect field, then this
2815   // must be the subject of a pointer-to-member expression.
2816   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2817     if (!indirectField->isCXXClassMember())
2818       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2819                                                       indirectField);
2820
2821   {
2822     QualType type = VD->getType();
2823     ExprValueKind valueKind = VK_RValue;
2824
2825     switch (D->getKind()) {
2826     // Ignore all the non-ValueDecl kinds.
2827 #define ABSTRACT_DECL(kind)
2828 #define VALUE(type, base)
2829 #define DECL(type, base) \
2830     case Decl::type:
2831 #include "clang/AST/DeclNodes.inc"
2832       llvm_unreachable("invalid value decl kind");
2833
2834     // These shouldn't make it here.
2835     case Decl::ObjCAtDefsField:
2836     case Decl::ObjCIvar:
2837       llvm_unreachable("forming non-member reference to ivar?");
2838
2839     // Enum constants are always r-values and never references.
2840     // Unresolved using declarations are dependent.
2841     case Decl::EnumConstant:
2842     case Decl::UnresolvedUsingValue:
2843       valueKind = VK_RValue;
2844       break;
2845
2846     // Fields and indirect fields that got here must be for
2847     // pointer-to-member expressions; we just call them l-values for
2848     // internal consistency, because this subexpression doesn't really
2849     // exist in the high-level semantics.
2850     case Decl::Field:
2851     case Decl::IndirectField:
2852       assert(getLangOpts().CPlusPlus &&
2853              "building reference to field in C?");
2854
2855       // These can't have reference type in well-formed programs, but
2856       // for internal consistency we do this anyway.
2857       type = type.getNonReferenceType();
2858       valueKind = VK_LValue;
2859       break;
2860
2861     // Non-type template parameters are either l-values or r-values
2862     // depending on the type.
2863     case Decl::NonTypeTemplateParm: {
2864       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2865         type = reftype->getPointeeType();
2866         valueKind = VK_LValue; // even if the parameter is an r-value reference
2867         break;
2868       }
2869
2870       // For non-references, we need to strip qualifiers just in case
2871       // the template parameter was declared as 'const int' or whatever.
2872       valueKind = VK_RValue;
2873       type = type.getUnqualifiedType();
2874       break;
2875     }
2876
2877     case Decl::Var:
2878     case Decl::VarTemplateSpecialization:
2879     case Decl::VarTemplatePartialSpecialization:
2880       // In C, "extern void blah;" is valid and is an r-value.
2881       if (!getLangOpts().CPlusPlus &&
2882           !type.hasQualifiers() &&
2883           type->isVoidType()) {
2884         valueKind = VK_RValue;
2885         break;
2886       }
2887       // fallthrough
2888
2889     case Decl::ImplicitParam:
2890     case Decl::ParmVar: {
2891       // These are always l-values.
2892       valueKind = VK_LValue;
2893       type = type.getNonReferenceType();
2894
2895       // FIXME: Does the addition of const really only apply in
2896       // potentially-evaluated contexts? Since the variable isn't actually
2897       // captured in an unevaluated context, it seems that the answer is no.
2898       if (!isUnevaluatedContext()) {
2899         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2900         if (!CapturedType.isNull())
2901           type = CapturedType;
2902       }
2903       
2904       break;
2905     }
2906         
2907     case Decl::Function: {
2908       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2909         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2910           type = Context.BuiltinFnTy;
2911           valueKind = VK_RValue;
2912           break;
2913         }
2914       }
2915
2916       const FunctionType *fty = type->castAs<FunctionType>();
2917
2918       // If we're referring to a function with an __unknown_anytype
2919       // result type, make the entire expression __unknown_anytype.
2920       if (fty->getReturnType() == Context.UnknownAnyTy) {
2921         type = Context.UnknownAnyTy;
2922         valueKind = VK_RValue;
2923         break;
2924       }
2925
2926       // Functions are l-values in C++.
2927       if (getLangOpts().CPlusPlus) {
2928         valueKind = VK_LValue;
2929         break;
2930       }
2931       
2932       // C99 DR 316 says that, if a function type comes from a
2933       // function definition (without a prototype), that type is only
2934       // used for checking compatibility. Therefore, when referencing
2935       // the function, we pretend that we don't have the full function
2936       // type.
2937       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2938           isa<FunctionProtoType>(fty))
2939         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2940                                               fty->getExtInfo());
2941
2942       // Functions are r-values in C.
2943       valueKind = VK_RValue;
2944       break;
2945     }
2946
2947     case Decl::MSProperty:
2948       valueKind = VK_LValue;
2949       break;
2950
2951     case Decl::CXXMethod:
2952       // If we're referring to a method with an __unknown_anytype
2953       // result type, make the entire expression __unknown_anytype.
2954       // This should only be possible with a type written directly.
2955       if (const FunctionProtoType *proto
2956             = dyn_cast<FunctionProtoType>(VD->getType()))
2957         if (proto->getReturnType() == Context.UnknownAnyTy) {
2958           type = Context.UnknownAnyTy;
2959           valueKind = VK_RValue;
2960           break;
2961         }
2962
2963       // C++ methods are l-values if static, r-values if non-static.
2964       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2965         valueKind = VK_LValue;
2966         break;
2967       }
2968       // fallthrough
2969
2970     case Decl::CXXConversion:
2971     case Decl::CXXDestructor:
2972     case Decl::CXXConstructor:
2973       valueKind = VK_RValue;
2974       break;
2975     }
2976
2977     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2978                             TemplateArgs);
2979   }
2980 }
2981
2982 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2983                                     SmallString<32> &Target) {
2984   Target.resize(CharByteWidth * (Source.size() + 1));
2985   char *ResultPtr = &Target[0];
2986   const UTF8 *ErrorPtr;
2987   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2988   (void)success;
2989   assert(success);
2990   Target.resize(ResultPtr - &Target[0]);
2991 }
2992
2993 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2994                                      PredefinedExpr::IdentType IT) {
2995   // Pick the current block, lambda, captured statement or function.
2996   Decl *currentDecl = nullptr;
2997   if (const BlockScopeInfo *BSI = getCurBlock())
2998     currentDecl = BSI->TheDecl;
2999   else if (const LambdaScopeInfo *LSI = getCurLambda())
3000     currentDecl = LSI->CallOperator;
3001   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3002     currentDecl = CSI->TheCapturedDecl;
3003   else
3004     currentDecl = getCurFunctionOrMethodDecl();
3005
3006   if (!currentDecl) {
3007     Diag(Loc, diag::ext_predef_outside_function);
3008     currentDecl = Context.getTranslationUnitDecl();
3009   }
3010
3011   QualType ResTy;
3012   StringLiteral *SL = nullptr;
3013   if (cast<DeclContext>(currentDecl)->isDependentContext())
3014     ResTy = Context.DependentTy;
3015   else {
3016     // Pre-defined identifiers are of type char[x], where x is the length of
3017     // the string.
3018     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3019     unsigned Length = Str.length();
3020
3021     llvm::APInt LengthI(32, Length + 1);
3022     if (IT == PredefinedExpr::LFunction) {
3023       ResTy = Context.WideCharTy.withConst();
3024       SmallString<32> RawChars;
3025       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3026                               Str, RawChars);
3027       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3028                                            /*IndexTypeQuals*/ 0);
3029       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3030                                  /*Pascal*/ false, ResTy, Loc);
3031     } else {
3032       ResTy = Context.CharTy.withConst();
3033       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3034                                            /*IndexTypeQuals*/ 0);
3035       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3036                                  /*Pascal*/ false, ResTy, Loc);
3037     }
3038   }
3039
3040   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3041 }
3042
3043 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3044   PredefinedExpr::IdentType IT;
3045
3046   switch (Kind) {
3047   default: llvm_unreachable("Unknown simple primary expr!");
3048   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3049   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3050   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3051   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3052   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3053   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3054   }
3055
3056   return BuildPredefinedExpr(Loc, IT);
3057 }
3058
3059 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3060   SmallString<16> CharBuffer;
3061   bool Invalid = false;
3062   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3063   if (Invalid)
3064     return ExprError();
3065
3066   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3067                             PP, Tok.getKind());
3068   if (Literal.hadError())
3069     return ExprError();
3070
3071   QualType Ty;
3072   if (Literal.isWide())
3073     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3074   else if (Literal.isUTF16())
3075     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3076   else if (Literal.isUTF32())
3077     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3078   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3079     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3080   else
3081     Ty = Context.CharTy;  // 'x' -> char in C++
3082
3083   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3084   if (Literal.isWide())
3085     Kind = CharacterLiteral::Wide;
3086   else if (Literal.isUTF16())
3087     Kind = CharacterLiteral::UTF16;
3088   else if (Literal.isUTF32())
3089     Kind = CharacterLiteral::UTF32;
3090   else if (Literal.isUTF8())
3091     Kind = CharacterLiteral::UTF8;
3092
3093   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3094                                              Tok.getLocation());
3095
3096   if (Literal.getUDSuffix().empty())
3097     return Lit;
3098
3099   // We're building a user-defined literal.
3100   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3101   SourceLocation UDSuffixLoc =
3102     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3103
3104   // Make sure we're allowed user-defined literals here.
3105   if (!UDLScope)
3106     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3107
3108   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3109   //   operator "" X (ch)
3110   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3111                                         Lit, Tok.getLocation());
3112 }
3113
3114 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3115   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3116   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3117                                 Context.IntTy, Loc);
3118 }
3119
3120 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3121                                   QualType Ty, SourceLocation Loc) {
3122   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3123
3124   using llvm::APFloat;
3125   APFloat Val(Format);
3126
3127   APFloat::opStatus result = Literal.GetFloatValue(Val);
3128
3129   // Overflow is always an error, but underflow is only an error if
3130   // we underflowed to zero (APFloat reports denormals as underflow).
3131   if ((result & APFloat::opOverflow) ||
3132       ((result & APFloat::opUnderflow) && Val.isZero())) {
3133     unsigned diagnostic;
3134     SmallString<20> buffer;
3135     if (result & APFloat::opOverflow) {
3136       diagnostic = diag::warn_float_overflow;
3137       APFloat::getLargest(Format).toString(buffer);
3138     } else {
3139       diagnostic = diag::warn_float_underflow;
3140       APFloat::getSmallest(Format).toString(buffer);
3141     }
3142
3143     S.Diag(Loc, diagnostic)
3144       << Ty
3145       << StringRef(buffer.data(), buffer.size());
3146   }
3147
3148   bool isExact = (result == APFloat::opOK);
3149   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3150 }
3151
3152 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3153   assert(E && "Invalid expression");
3154
3155   if (E->isValueDependent())
3156     return false;
3157
3158   QualType QT = E->getType();
3159   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3160     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3161     return true;
3162   }
3163
3164   llvm::APSInt ValueAPS;
3165   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3166
3167   if (R.isInvalid())
3168     return true;
3169
3170   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3171   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3172     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3173         << ValueAPS.toString(10) << ValueIsPositive;
3174     return true;
3175   }
3176
3177   return false;
3178 }
3179
3180 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3181   // Fast path for a single digit (which is quite common).  A single digit
3182   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3183   if (Tok.getLength() == 1) {
3184     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3185     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3186   }
3187
3188   SmallString<128> SpellingBuffer;
3189   // NumericLiteralParser wants to overread by one character.  Add padding to
3190   // the buffer in case the token is copied to the buffer.  If getSpelling()
3191   // returns a StringRef to the memory buffer, it should have a null char at
3192   // the EOF, so it is also safe.
3193   SpellingBuffer.resize(Tok.getLength() + 1);
3194
3195   // Get the spelling of the token, which eliminates trigraphs, etc.
3196   bool Invalid = false;
3197   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3198   if (Invalid)
3199     return ExprError();
3200
3201   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3202   if (Literal.hadError)
3203     return ExprError();
3204
3205   if (Literal.hasUDSuffix()) {
3206     // We're building a user-defined literal.
3207     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3208     SourceLocation UDSuffixLoc =
3209       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3210
3211     // Make sure we're allowed user-defined literals here.
3212     if (!UDLScope)
3213       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3214
3215     QualType CookedTy;
3216     if (Literal.isFloatingLiteral()) {
3217       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3218       // long double, the literal is treated as a call of the form
3219       //   operator "" X (f L)
3220       CookedTy = Context.LongDoubleTy;
3221     } else {
3222       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3223       // unsigned long long, the literal is treated as a call of the form
3224       //   operator "" X (n ULL)
3225       CookedTy = Context.UnsignedLongLongTy;
3226     }
3227
3228     DeclarationName OpName =
3229       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3230     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3231     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3232
3233     SourceLocation TokLoc = Tok.getLocation();
3234
3235     // Perform literal operator lookup to determine if we're building a raw
3236     // literal or a cooked one.
3237     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3238     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3239                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3240                                   /*AllowStringTemplate*/false)) {
3241     case LOLR_Error:
3242       return ExprError();
3243
3244     case LOLR_Cooked: {
3245       Expr *Lit;
3246       if (Literal.isFloatingLiteral()) {
3247         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3248       } else {
3249         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3250         if (Literal.GetIntegerValue(ResultVal))
3251           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3252               << /* Unsigned */ 1;
3253         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3254                                      Tok.getLocation());
3255       }
3256       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3257     }
3258
3259     case LOLR_Raw: {
3260       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3261       // literal is treated as a call of the form
3262       //   operator "" X ("n")
3263       unsigned Length = Literal.getUDSuffixOffset();
3264       QualType StrTy = Context.getConstantArrayType(
3265           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3266           ArrayType::Normal, 0);
3267       Expr *Lit = StringLiteral::Create(
3268           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3269           /*Pascal*/false, StrTy, &TokLoc, 1);
3270       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3271     }
3272
3273     case LOLR_Template: {
3274       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3275       // template), L is treated as a call fo the form
3276       //   operator "" X <'c1', 'c2', ... 'ck'>()
3277       // where n is the source character sequence c1 c2 ... ck.
3278       TemplateArgumentListInfo ExplicitArgs;
3279       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3280       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3281       llvm::APSInt Value(CharBits, CharIsUnsigned);
3282       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3283         Value = TokSpelling[I];
3284         TemplateArgument Arg(Context, Value, Context.CharTy);
3285         TemplateArgumentLocInfo ArgInfo;
3286         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3287       }
3288       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3289                                       &ExplicitArgs);
3290     }
3291     case LOLR_StringTemplate:
3292       llvm_unreachable("unexpected literal operator lookup result");
3293     }
3294   }
3295
3296   Expr *Res;
3297
3298   if (Literal.isFloatingLiteral()) {
3299     QualType Ty;
3300     if (Literal.isFloat)
3301       Ty = Context.FloatTy;
3302     else if (!Literal.isLong)
3303       Ty = Context.DoubleTy;
3304     else
3305       Ty = Context.LongDoubleTy;
3306
3307     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3308
3309     if (Ty == Context.DoubleTy) {
3310       if (getLangOpts().SinglePrecisionConstants) {
3311         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3312       } else if (getLangOpts().OpenCL &&
3313                  !((getLangOpts().OpenCLVersion >= 120) ||
3314                    getOpenCLOptions().cl_khr_fp64)) {
3315         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3316         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3317       }
3318     }
3319   } else if (!Literal.isIntegerLiteral()) {
3320     return ExprError();
3321   } else {
3322     QualType Ty;
3323
3324     // 'long long' is a C99 or C++11 feature.
3325     if (!getLangOpts().C99 && Literal.isLongLong) {
3326       if (getLangOpts().CPlusPlus)
3327         Diag(Tok.getLocation(),
3328              getLangOpts().CPlusPlus11 ?
3329              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3330       else
3331         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3332     }
3333
3334     // Get the value in the widest-possible width.
3335     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3336     llvm::APInt ResultVal(MaxWidth, 0);
3337
3338     if (Literal.GetIntegerValue(ResultVal)) {
3339       // If this value didn't fit into uintmax_t, error and force to ull.
3340       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3341           << /* Unsigned */ 1;
3342       Ty = Context.UnsignedLongLongTy;
3343       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3344              "long long is not intmax_t?");
3345     } else {
3346       // If this value fits into a ULL, try to figure out what else it fits into
3347       // according to the rules of C99 6.4.4.1p5.
3348
3349       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3350       // be an unsigned int.
3351       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3352
3353       // Check from smallest to largest, picking the smallest type we can.
3354       unsigned Width = 0;
3355
3356       // Microsoft specific integer suffixes are explicitly sized.
3357       if (Literal.MicrosoftInteger) {
3358         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3359           Width = 8;
3360           Ty = Context.CharTy;
3361         } else {
3362           Width = Literal.MicrosoftInteger;
3363           Ty = Context.getIntTypeForBitwidth(Width,
3364                                              /*Signed=*/!Literal.isUnsigned);
3365         }
3366       }
3367
3368       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3369         // Are int/unsigned possibilities?
3370         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3371
3372         // Does it fit in a unsigned int?
3373         if (ResultVal.isIntN(IntSize)) {
3374           // Does it fit in a signed int?
3375           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3376             Ty = Context.IntTy;
3377           else if (AllowUnsigned)
3378             Ty = Context.UnsignedIntTy;
3379           Width = IntSize;
3380         }
3381       }
3382
3383       // Are long/unsigned long possibilities?
3384       if (Ty.isNull() && !Literal.isLongLong) {
3385         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3386
3387         // Does it fit in a unsigned long?
3388         if (ResultVal.isIntN(LongSize)) {
3389           // Does it fit in a signed long?
3390           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3391             Ty = Context.LongTy;
3392           else if (AllowUnsigned)
3393             Ty = Context.UnsignedLongTy;
3394           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3395           // is compatible.
3396           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3397             const unsigned LongLongSize =
3398                 Context.getTargetInfo().getLongLongWidth();
3399             Diag(Tok.getLocation(),
3400                  getLangOpts().CPlusPlus
3401                      ? Literal.isLong
3402                            ? diag::warn_old_implicitly_unsigned_long_cxx
3403                            : /*C++98 UB*/ diag::
3404                                  ext_old_implicitly_unsigned_long_cxx
3405                      : diag::warn_old_implicitly_unsigned_long)
3406                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3407                                             : /*will be ill-formed*/ 1);
3408             Ty = Context.UnsignedLongTy;
3409           }
3410           Width = LongSize;
3411         }
3412       }
3413
3414       // Check long long if needed.
3415       if (Ty.isNull()) {
3416         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3417
3418         // Does it fit in a unsigned long long?
3419         if (ResultVal.isIntN(LongLongSize)) {
3420           // Does it fit in a signed long long?
3421           // To be compatible with MSVC, hex integer literals ending with the
3422           // LL or i64 suffix are always signed in Microsoft mode.
3423           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3424               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3425             Ty = Context.LongLongTy;
3426           else if (AllowUnsigned)
3427             Ty = Context.UnsignedLongLongTy;
3428           Width = LongLongSize;
3429         }
3430       }
3431
3432       // If we still couldn't decide a type, we probably have something that
3433       // does not fit in a signed long long, but has no U suffix.
3434       if (Ty.isNull()) {
3435         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3436         Ty = Context.UnsignedLongLongTy;
3437         Width = Context.getTargetInfo().getLongLongWidth();
3438       }
3439
3440       if (ResultVal.getBitWidth() != Width)
3441         ResultVal = ResultVal.trunc(Width);
3442     }
3443     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3444   }
3445
3446   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3447   if (Literal.isImaginary)
3448     Res = new (Context) ImaginaryLiteral(Res,
3449                                         Context.getComplexType(Res->getType()));
3450
3451   return Res;
3452 }
3453
3454 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3455   assert(E && "ActOnParenExpr() missing expr");
3456   return new (Context) ParenExpr(L, R, E);
3457 }
3458
3459 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3460                                          SourceLocation Loc,
3461                                          SourceRange ArgRange) {
3462   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3463   // scalar or vector data type argument..."
3464   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3465   // type (C99 6.2.5p18) or void.
3466   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3467     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3468       << T << ArgRange;
3469     return true;
3470   }
3471
3472   assert((T->isVoidType() || !T->isIncompleteType()) &&
3473          "Scalar types should always be complete");
3474   return false;
3475 }
3476
3477 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3478                                            SourceLocation Loc,
3479                                            SourceRange ArgRange,
3480                                            UnaryExprOrTypeTrait TraitKind) {
3481   // Invalid types must be hard errors for SFINAE in C++.
3482   if (S.LangOpts.CPlusPlus)
3483     return true;
3484
3485   // C99 6.5.3.4p1:
3486   if (T->isFunctionType() &&
3487       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3488     // sizeof(function)/alignof(function) is allowed as an extension.
3489     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3490       << TraitKind << ArgRange;
3491     return false;
3492   }
3493
3494   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3495   // this is an error (OpenCL v1.1 s6.3.k)
3496   if (T->isVoidType()) {
3497     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3498                                         : diag::ext_sizeof_alignof_void_type;
3499     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3500     return false;
3501   }
3502
3503   return true;
3504 }
3505
3506 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3507                                              SourceLocation Loc,
3508                                              SourceRange ArgRange,
3509                                              UnaryExprOrTypeTrait TraitKind) {
3510   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3511   // runtime doesn't allow it.
3512   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3513     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3514       << T << (TraitKind == UETT_SizeOf)
3515       << ArgRange;
3516     return true;
3517   }
3518
3519   return false;
3520 }
3521
3522 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3523 /// pointer type is equal to T) and emit a warning if it is.
3524 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3525                                      Expr *E) {
3526   // Don't warn if the operation changed the type.
3527   if (T != E->getType())
3528     return;
3529
3530   // Now look for array decays.
3531   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3532   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3533     return;
3534
3535   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3536                                              << ICE->getType()
3537                                              << ICE->getSubExpr()->getType();
3538 }
3539
3540 /// \brief Check the constraints on expression operands to unary type expression
3541 /// and type traits.
3542 ///
3543 /// Completes any types necessary and validates the constraints on the operand
3544 /// expression. The logic mostly mirrors the type-based overload, but may modify
3545 /// the expression as it completes the type for that expression through template
3546 /// instantiation, etc.
3547 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3548                                             UnaryExprOrTypeTrait ExprKind) {
3549   QualType ExprTy = E->getType();
3550   assert(!ExprTy->isReferenceType());
3551
3552   if (ExprKind == UETT_VecStep)
3553     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3554                                         E->getSourceRange());
3555
3556   // Whitelist some types as extensions
3557   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3558                                       E->getSourceRange(), ExprKind))
3559     return false;
3560
3561   // 'alignof' applied to an expression only requires the base element type of
3562   // the expression to be complete. 'sizeof' requires the expression's type to
3563   // be complete (and will attempt to complete it if it's an array of unknown
3564   // bound).
3565   if (ExprKind == UETT_AlignOf) {
3566     if (RequireCompleteType(E->getExprLoc(),
3567                             Context.getBaseElementType(E->getType()),
3568                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3569                             E->getSourceRange()))
3570       return true;
3571   } else {
3572     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3573                                 ExprKind, E->getSourceRange()))
3574       return true;
3575   }
3576
3577   // Completing the expression's type may have changed it.
3578   ExprTy = E->getType();
3579   assert(!ExprTy->isReferenceType());
3580
3581   if (ExprTy->isFunctionType()) {
3582     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3583       << ExprKind << E->getSourceRange();
3584     return true;
3585   }
3586
3587   // The operand for sizeof and alignof is in an unevaluated expression context,
3588   // so side effects could result in unintended consequences.
3589   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3590       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3591     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3592
3593   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3594                                        E->getSourceRange(), ExprKind))
3595     return true;
3596
3597   if (ExprKind == UETT_SizeOf) {
3598     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3599       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3600         QualType OType = PVD->getOriginalType();
3601         QualType Type = PVD->getType();
3602         if (Type->isPointerType() && OType->isArrayType()) {
3603           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3604             << Type << OType;
3605           Diag(PVD->getLocation(), diag::note_declared_at);
3606         }
3607       }
3608     }
3609
3610     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3611     // decays into a pointer and returns an unintended result. This is most
3612     // likely a typo for "sizeof(array) op x".
3613     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3614       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3615                                BO->getLHS());
3616       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3617                                BO->getRHS());
3618     }
3619   }
3620
3621   return false;
3622 }
3623
3624 /// \brief Check the constraints on operands to unary expression and type
3625 /// traits.
3626 ///
3627 /// This will complete any types necessary, and validate the various constraints
3628 /// on those operands.
3629 ///
3630 /// The UsualUnaryConversions() function is *not* called by this routine.
3631 /// C99 6.3.2.1p[2-4] all state:
3632 ///   Except when it is the operand of the sizeof operator ...
3633 ///
3634 /// C++ [expr.sizeof]p4
3635 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3636 ///   standard conversions are not applied to the operand of sizeof.
3637 ///
3638 /// This policy is followed for all of the unary trait expressions.
3639 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3640                                             SourceLocation OpLoc,
3641                                             SourceRange ExprRange,
3642                                             UnaryExprOrTypeTrait ExprKind) {
3643   if (ExprType->isDependentType())
3644     return false;
3645
3646   // C++ [expr.sizeof]p2:
3647   //     When applied to a reference or a reference type, the result
3648   //     is the size of the referenced type.
3649   // C++11 [expr.alignof]p3:
3650   //     When alignof is applied to a reference type, the result
3651   //     shall be the alignment of the referenced type.
3652   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3653     ExprType = Ref->getPointeeType();
3654
3655   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3656   //   When alignof or _Alignof is applied to an array type, the result
3657   //   is the alignment of the element type.
3658   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3659     ExprType = Context.getBaseElementType(ExprType);
3660
3661   if (ExprKind == UETT_VecStep)
3662     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3663
3664   // Whitelist some types as extensions
3665   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3666                                       ExprKind))
3667     return false;
3668
3669   if (RequireCompleteType(OpLoc, ExprType,
3670                           diag::err_sizeof_alignof_incomplete_type,
3671                           ExprKind, ExprRange))
3672     return true;
3673
3674   if (ExprType->isFunctionType()) {
3675     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3676       << ExprKind << ExprRange;
3677     return true;
3678   }
3679
3680   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3681                                        ExprKind))
3682     return true;
3683
3684   return false;
3685 }
3686
3687 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3688   E = E->IgnoreParens();
3689
3690   // Cannot know anything else if the expression is dependent.
3691   if (E->isTypeDependent())
3692     return false;
3693
3694   if (E->getObjectKind() == OK_BitField) {
3695     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3696        << 1 << E->getSourceRange();
3697     return true;
3698   }
3699
3700   ValueDecl *D = nullptr;
3701   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3702     D = DRE->getDecl();
3703   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3704     D = ME->getMemberDecl();
3705   }
3706
3707   // If it's a field, require the containing struct to have a
3708   // complete definition so that we can compute the layout.
3709   //
3710   // This can happen in C++11 onwards, either by naming the member
3711   // in a way that is not transformed into a member access expression
3712   // (in an unevaluated operand, for instance), or by naming the member
3713   // in a trailing-return-type.
3714   //
3715   // For the record, since __alignof__ on expressions is a GCC
3716   // extension, GCC seems to permit this but always gives the
3717   // nonsensical answer 0.
3718   //
3719   // We don't really need the layout here --- we could instead just
3720   // directly check for all the appropriate alignment-lowing
3721   // attributes --- but that would require duplicating a lot of
3722   // logic that just isn't worth duplicating for such a marginal
3723   // use-case.
3724   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3725     // Fast path this check, since we at least know the record has a
3726     // definition if we can find a member of it.
3727     if (!FD->getParent()->isCompleteDefinition()) {
3728       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3729         << E->getSourceRange();
3730       return true;
3731     }
3732
3733     // Otherwise, if it's a field, and the field doesn't have
3734     // reference type, then it must have a complete type (or be a
3735     // flexible array member, which we explicitly want to
3736     // white-list anyway), which makes the following checks trivial.
3737     if (!FD->getType()->isReferenceType())
3738       return false;
3739   }
3740
3741   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3742 }
3743
3744 bool Sema::CheckVecStepExpr(Expr *E) {
3745   E = E->IgnoreParens();
3746
3747   // Cannot know anything else if the expression is dependent.
3748   if (E->isTypeDependent())
3749     return false;
3750
3751   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3752 }
3753
3754 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3755                                         CapturingScopeInfo *CSI) {
3756   assert(T->isVariablyModifiedType());
3757   assert(CSI != nullptr);
3758
3759   // We're going to walk down into the type and look for VLA expressions.
3760   do {
3761     const Type *Ty = T.getTypePtr();
3762     switch (Ty->getTypeClass()) {
3763 #define TYPE(Class, Base)
3764 #define ABSTRACT_TYPE(Class, Base)
3765 #define NON_CANONICAL_TYPE(Class, Base)
3766 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3767 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3768 #include "clang/AST/TypeNodes.def"
3769       T = QualType();
3770       break;
3771     // These types are never variably-modified.
3772     case Type::Builtin:
3773     case Type::Complex:
3774     case Type::Vector:
3775     case Type::ExtVector:
3776     case Type::Record:
3777     case Type::Enum:
3778     case Type::Elaborated:
3779     case Type::TemplateSpecialization:
3780     case Type::ObjCObject:
3781     case Type::ObjCInterface:
3782     case Type::ObjCObjectPointer:
3783     case Type::Pipe:
3784       llvm_unreachable("type class is never variably-modified!");
3785     case Type::Adjusted:
3786       T = cast<AdjustedType>(Ty)->getOriginalType();
3787       break;
3788     case Type::Decayed:
3789       T = cast<DecayedType>(Ty)->getPointeeType();
3790       break;
3791     case Type::Pointer:
3792       T = cast<PointerType>(Ty)->getPointeeType();
3793       break;
3794     case Type::BlockPointer:
3795       T = cast<BlockPointerType>(Ty)->getPointeeType();
3796       break;
3797     case Type::LValueReference:
3798     case Type::RValueReference:
3799       T = cast<ReferenceType>(Ty)->getPointeeType();
3800       break;
3801     case Type::MemberPointer:
3802       T = cast<MemberPointerType>(Ty)->getPointeeType();
3803       break;
3804     case Type::ConstantArray:
3805     case Type::IncompleteArray:
3806       // Losing element qualification here is fine.
3807       T = cast<ArrayType>(Ty)->getElementType();
3808       break;
3809     case Type::VariableArray: {
3810       // Losing element qualification here is fine.
3811       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3812
3813       // Unknown size indication requires no size computation.
3814       // Otherwise, evaluate and record it.
3815       if (auto Size = VAT->getSizeExpr()) {
3816         if (!CSI->isVLATypeCaptured(VAT)) {
3817           RecordDecl *CapRecord = nullptr;
3818           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3819             CapRecord = LSI->Lambda;
3820           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3821             CapRecord = CRSI->TheRecordDecl;
3822           }
3823           if (CapRecord) {
3824             auto ExprLoc = Size->getExprLoc();
3825             auto SizeType = Context.getSizeType();
3826             // Build the non-static data member.
3827             auto Field =
3828                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3829                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3830                                   /*BW*/ nullptr, /*Mutable*/ false,
3831                                   /*InitStyle*/ ICIS_NoInit);
3832             Field->setImplicit(true);
3833             Field->setAccess(AS_private);
3834             Field->setCapturedVLAType(VAT);
3835             CapRecord->addDecl(Field);
3836
3837             CSI->addVLATypeCapture(ExprLoc, SizeType);
3838           }
3839         }
3840       }
3841       T = VAT->getElementType();
3842       break;
3843     }
3844     case Type::FunctionProto:
3845     case Type::FunctionNoProto:
3846       T = cast<FunctionType>(Ty)->getReturnType();
3847       break;
3848     case Type::Paren:
3849     case Type::TypeOf:
3850     case Type::UnaryTransform:
3851     case Type::Attributed:
3852     case Type::SubstTemplateTypeParm:
3853     case Type::PackExpansion:
3854       // Keep walking after single level desugaring.
3855       T = T.getSingleStepDesugaredType(Context);
3856       break;
3857     case Type::Typedef:
3858       T = cast<TypedefType>(Ty)->desugar();
3859       break;
3860     case Type::Decltype:
3861       T = cast<DecltypeType>(Ty)->desugar();
3862       break;
3863     case Type::Auto:
3864       T = cast<AutoType>(Ty)->getDeducedType();
3865       break;
3866     case Type::TypeOfExpr:
3867       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3868       break;
3869     case Type::Atomic:
3870       T = cast<AtomicType>(Ty)->getValueType();
3871       break;
3872     }
3873   } while (!T.isNull() && T->isVariablyModifiedType());
3874 }
3875
3876 /// \brief Build a sizeof or alignof expression given a type operand.
3877 ExprResult
3878 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3879                                      SourceLocation OpLoc,
3880                                      UnaryExprOrTypeTrait ExprKind,
3881                                      SourceRange R) {
3882   if (!TInfo)
3883     return ExprError();
3884
3885   QualType T = TInfo->getType();
3886
3887   if (!T->isDependentType() &&
3888       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3889     return ExprError();
3890
3891   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3892     if (auto *TT = T->getAs<TypedefType>()) {
3893       if (auto *CSI = dyn_cast<CapturingScopeInfo>(FunctionScopes.back())) {
3894         DeclContext *DC = nullptr;
3895         if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI))
3896           DC = LSI->CallOperator;
3897         else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3898           DC = CRSI->TheCapturedDecl;
3899         if (DC && TT->getDecl()->getDeclContext() != DC)
3900           captureVariablyModifiedType(Context, T, CSI);
3901       }
3902     }
3903   }
3904
3905   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3906   return new (Context) UnaryExprOrTypeTraitExpr(
3907       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3908 }
3909
3910 /// \brief Build a sizeof or alignof expression given an expression
3911 /// operand.
3912 ExprResult
3913 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3914                                      UnaryExprOrTypeTrait ExprKind) {
3915   ExprResult PE = CheckPlaceholderExpr(E);
3916   if (PE.isInvalid()) 
3917     return ExprError();
3918
3919   E = PE.get();
3920   
3921   // Verify that the operand is valid.
3922   bool isInvalid = false;
3923   if (E->isTypeDependent()) {
3924     // Delay type-checking for type-dependent expressions.
3925   } else if (ExprKind == UETT_AlignOf) {
3926     isInvalid = CheckAlignOfExpr(*this, E);
3927   } else if (ExprKind == UETT_VecStep) {
3928     isInvalid = CheckVecStepExpr(E);
3929   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3930       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3931       isInvalid = true;
3932   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3933     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3934     isInvalid = true;
3935   } else {
3936     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3937   }
3938
3939   if (isInvalid)
3940     return ExprError();
3941
3942   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3943     PE = TransformToPotentiallyEvaluated(E);
3944     if (PE.isInvalid()) return ExprError();
3945     E = PE.get();
3946   }
3947
3948   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3949   return new (Context) UnaryExprOrTypeTraitExpr(
3950       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3951 }
3952
3953 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3954 /// expr and the same for @c alignof and @c __alignof
3955 /// Note that the ArgRange is invalid if isType is false.
3956 ExprResult
3957 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3958                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3959                                     void *TyOrEx, SourceRange ArgRange) {
3960   // If error parsing type, ignore.
3961   if (!TyOrEx) return ExprError();
3962
3963   if (IsType) {
3964     TypeSourceInfo *TInfo;
3965     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3966     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3967   }
3968
3969   Expr *ArgEx = (Expr *)TyOrEx;
3970   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3971   return Result;
3972 }
3973
3974 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3975                                      bool IsReal) {
3976   if (V.get()->isTypeDependent())
3977     return S.Context.DependentTy;
3978
3979   // _Real and _Imag are only l-values for normal l-values.
3980   if (V.get()->getObjectKind() != OK_Ordinary) {
3981     V = S.DefaultLvalueConversion(V.get());
3982     if (V.isInvalid())
3983       return QualType();
3984   }
3985
3986   // These operators return the element type of a complex type.
3987   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3988     return CT->getElementType();
3989
3990   // Otherwise they pass through real integer and floating point types here.
3991   if (V.get()->getType()->isArithmeticType())
3992     return V.get()->getType();
3993
3994   // Test for placeholders.
3995   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3996   if (PR.isInvalid()) return QualType();
3997   if (PR.get() != V.get()) {
3998     V = PR;
3999     return CheckRealImagOperand(S, V, Loc, IsReal);
4000   }
4001
4002   // Reject anything else.
4003   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4004     << (IsReal ? "__real" : "__imag");
4005   return QualType();
4006 }
4007
4008
4009
4010 ExprResult
4011 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4012                           tok::TokenKind Kind, Expr *Input) {
4013   UnaryOperatorKind Opc;
4014   switch (Kind) {
4015   default: llvm_unreachable("Unknown unary op!");
4016   case tok::plusplus:   Opc = UO_PostInc; break;
4017   case tok::minusminus: Opc = UO_PostDec; break;
4018   }
4019
4020   // Since this might is a postfix expression, get rid of ParenListExprs.
4021   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4022   if (Result.isInvalid()) return ExprError();
4023   Input = Result.get();
4024
4025   return BuildUnaryOp(S, OpLoc, Opc, Input);
4026 }
4027
4028 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4029 ///
4030 /// \return true on error
4031 static bool checkArithmeticOnObjCPointer(Sema &S,
4032                                          SourceLocation opLoc,
4033                                          Expr *op) {
4034   assert(op->getType()->isObjCObjectPointerType());
4035   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4036       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4037     return false;
4038
4039   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4040     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4041     << op->getSourceRange();
4042   return true;
4043 }
4044
4045 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4046   auto *BaseNoParens = Base->IgnoreParens();
4047   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4048     return MSProp->getPropertyDecl()->getType()->isArrayType();
4049   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4050 }
4051
4052 ExprResult
4053 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4054                               Expr *idx, SourceLocation rbLoc) {
4055   if (base && !base->getType().isNull() &&
4056       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4057     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4058                                     /*Length=*/nullptr, rbLoc);
4059
4060   // Since this might be a postfix expression, get rid of ParenListExprs.
4061   if (isa<ParenListExpr>(base)) {
4062     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4063     if (result.isInvalid()) return ExprError();
4064     base = result.get();
4065   }
4066
4067   // Handle any non-overload placeholder types in the base and index
4068   // expressions.  We can't handle overloads here because the other
4069   // operand might be an overloadable type, in which case the overload
4070   // resolution for the operator overload should get the first crack
4071   // at the overload.
4072   bool IsMSPropertySubscript = false;
4073   if (base->getType()->isNonOverloadPlaceholderType()) {
4074     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4075     if (!IsMSPropertySubscript) {
4076       ExprResult result = CheckPlaceholderExpr(base);
4077       if (result.isInvalid())
4078         return ExprError();
4079       base = result.get();
4080     }
4081   }
4082   if (idx->getType()->isNonOverloadPlaceholderType()) {
4083     ExprResult result = CheckPlaceholderExpr(idx);
4084     if (result.isInvalid()) return ExprError();
4085     idx = result.get();
4086   }
4087
4088   // Build an unanalyzed expression if either operand is type-dependent.
4089   if (getLangOpts().CPlusPlus &&
4090       (base->isTypeDependent() || idx->isTypeDependent())) {
4091     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4092                                             VK_LValue, OK_Ordinary, rbLoc);
4093   }
4094
4095   // MSDN, property (C++)
4096   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4097   // This attribute can also be used in the declaration of an empty array in a
4098   // class or structure definition. For example:
4099   // __declspec(property(get=GetX, put=PutX)) int x[];
4100   // The above statement indicates that x[] can be used with one or more array
4101   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4102   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4103   if (IsMSPropertySubscript) {
4104     // Build MS property subscript expression if base is MS property reference
4105     // or MS property subscript.
4106     return new (Context) MSPropertySubscriptExpr(
4107         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4108   }
4109
4110   // Use C++ overloaded-operator rules if either operand has record
4111   // type.  The spec says to do this if either type is *overloadable*,
4112   // but enum types can't declare subscript operators or conversion
4113   // operators, so there's nothing interesting for overload resolution
4114   // to do if there aren't any record types involved.
4115   //
4116   // ObjC pointers have their own subscripting logic that is not tied
4117   // to overload resolution and so should not take this path.
4118   if (getLangOpts().CPlusPlus &&
4119       (base->getType()->isRecordType() ||
4120        (!base->getType()->isObjCObjectPointerType() &&
4121         idx->getType()->isRecordType()))) {
4122     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4123   }
4124
4125   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4126 }
4127
4128 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4129                                           Expr *LowerBound,
4130                                           SourceLocation ColonLoc, Expr *Length,
4131                                           SourceLocation RBLoc) {
4132   if (Base->getType()->isPlaceholderType() &&
4133       !Base->getType()->isSpecificPlaceholderType(
4134           BuiltinType::OMPArraySection)) {
4135     ExprResult Result = CheckPlaceholderExpr(Base);
4136     if (Result.isInvalid())
4137       return ExprError();
4138     Base = Result.get();
4139   }
4140   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4141     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4142     if (Result.isInvalid())
4143       return ExprError();
4144     LowerBound = Result.get();
4145   }
4146   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4147     ExprResult Result = CheckPlaceholderExpr(Length);
4148     if (Result.isInvalid())
4149       return ExprError();
4150     Length = Result.get();
4151   }
4152
4153   // Build an unanalyzed expression if either operand is type-dependent.
4154   if (Base->isTypeDependent() ||
4155       (LowerBound &&
4156        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4157       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4158     return new (Context)
4159         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4160                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4161   }
4162
4163   // Perform default conversions.
4164   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4165   QualType ResultTy;
4166   if (OriginalTy->isAnyPointerType()) {
4167     ResultTy = OriginalTy->getPointeeType();
4168   } else if (OriginalTy->isArrayType()) {
4169     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4170   } else {
4171     return ExprError(
4172         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4173         << Base->getSourceRange());
4174   }
4175   // C99 6.5.2.1p1
4176   if (LowerBound) {
4177     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4178                                                       LowerBound);
4179     if (Res.isInvalid())
4180       return ExprError(Diag(LowerBound->getExprLoc(),
4181                             diag::err_omp_typecheck_section_not_integer)
4182                        << 0 << LowerBound->getSourceRange());
4183     LowerBound = Res.get();
4184
4185     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4186         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4187       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4188           << 0 << LowerBound->getSourceRange();
4189   }
4190   if (Length) {
4191     auto Res =
4192         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4193     if (Res.isInvalid())
4194       return ExprError(Diag(Length->getExprLoc(),
4195                             diag::err_omp_typecheck_section_not_integer)
4196                        << 1 << Length->getSourceRange());
4197     Length = Res.get();
4198
4199     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4200         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4201       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4202           << 1 << Length->getSourceRange();
4203   }
4204
4205   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4206   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4207   // type. Note that functions are not objects, and that (in C99 parlance)
4208   // incomplete types are not object types.
4209   if (ResultTy->isFunctionType()) {
4210     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4211         << ResultTy << Base->getSourceRange();
4212     return ExprError();
4213   }
4214
4215   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4216                           diag::err_omp_section_incomplete_type, Base))
4217     return ExprError();
4218
4219   if (LowerBound) {
4220     llvm::APSInt LowerBoundValue;
4221     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4222       // OpenMP 4.0, [2.4 Array Sections]
4223       // The lower-bound and length must evaluate to non-negative integers.
4224       if (LowerBoundValue.isNegative()) {
4225         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4226             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4227             << LowerBound->getSourceRange();
4228         return ExprError();
4229       }
4230     }
4231   }
4232
4233   if (Length) {
4234     llvm::APSInt LengthValue;
4235     if (Length->EvaluateAsInt(LengthValue, Context)) {
4236       // OpenMP 4.0, [2.4 Array Sections]
4237       // The lower-bound and length must evaluate to non-negative integers.
4238       if (LengthValue.isNegative()) {
4239         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4240             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4241             << Length->getSourceRange();
4242         return ExprError();
4243       }
4244     }
4245   } else if (ColonLoc.isValid() &&
4246              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4247                                       !OriginalTy->isVariableArrayType()))) {
4248     // OpenMP 4.0, [2.4 Array Sections]
4249     // When the size of the array dimension is not known, the length must be
4250     // specified explicitly.
4251     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4252         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4253     return ExprError();
4254   }
4255
4256   return new (Context)
4257       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4258                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4259 }
4260
4261 ExprResult
4262 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4263                                       Expr *Idx, SourceLocation RLoc) {
4264   Expr *LHSExp = Base;
4265   Expr *RHSExp = Idx;
4266
4267   // Perform default conversions.
4268   if (!LHSExp->getType()->getAs<VectorType>()) {
4269     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4270     if (Result.isInvalid())
4271       return ExprError();
4272     LHSExp = Result.get();
4273   }
4274   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4275   if (Result.isInvalid())
4276     return ExprError();
4277   RHSExp = Result.get();
4278
4279   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4280   ExprValueKind VK = VK_LValue;
4281   ExprObjectKind OK = OK_Ordinary;
4282
4283   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4284   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4285   // in the subscript position. As a result, we need to derive the array base
4286   // and index from the expression types.
4287   Expr *BaseExpr, *IndexExpr;
4288   QualType ResultType;
4289   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4290     BaseExpr = LHSExp;
4291     IndexExpr = RHSExp;
4292     ResultType = Context.DependentTy;
4293   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4294     BaseExpr = LHSExp;
4295     IndexExpr = RHSExp;
4296     ResultType = PTy->getPointeeType();
4297   } else if (const ObjCObjectPointerType *PTy =
4298                LHSTy->getAs<ObjCObjectPointerType>()) {
4299     BaseExpr = LHSExp;
4300     IndexExpr = RHSExp;
4301
4302     // Use custom logic if this should be the pseudo-object subscript
4303     // expression.
4304     if (!LangOpts.isSubscriptPointerArithmetic())
4305       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4306                                           nullptr);
4307
4308     ResultType = PTy->getPointeeType();
4309   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4310      // Handle the uncommon case of "123[Ptr]".
4311     BaseExpr = RHSExp;
4312     IndexExpr = LHSExp;
4313     ResultType = PTy->getPointeeType();
4314   } else if (const ObjCObjectPointerType *PTy =
4315                RHSTy->getAs<ObjCObjectPointerType>()) {
4316      // Handle the uncommon case of "123[Ptr]".
4317     BaseExpr = RHSExp;
4318     IndexExpr = LHSExp;
4319     ResultType = PTy->getPointeeType();
4320     if (!LangOpts.isSubscriptPointerArithmetic()) {
4321       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4322         << ResultType << BaseExpr->getSourceRange();
4323       return ExprError();
4324     }
4325   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4326     BaseExpr = LHSExp;    // vectors: V[123]
4327     IndexExpr = RHSExp;
4328     VK = LHSExp->getValueKind();
4329     if (VK != VK_RValue)
4330       OK = OK_VectorComponent;
4331
4332     // FIXME: need to deal with const...
4333     ResultType = VTy->getElementType();
4334   } else if (LHSTy->isArrayType()) {
4335     // If we see an array that wasn't promoted by
4336     // DefaultFunctionArrayLvalueConversion, it must be an array that
4337     // wasn't promoted because of the C90 rule that doesn't
4338     // allow promoting non-lvalue arrays.  Warn, then
4339     // force the promotion here.
4340     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4341         LHSExp->getSourceRange();
4342     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4343                                CK_ArrayToPointerDecay).get();
4344     LHSTy = LHSExp->getType();
4345
4346     BaseExpr = LHSExp;
4347     IndexExpr = RHSExp;
4348     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4349   } else if (RHSTy->isArrayType()) {
4350     // Same as previous, except for 123[f().a] case
4351     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4352         RHSExp->getSourceRange();
4353     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4354                                CK_ArrayToPointerDecay).get();
4355     RHSTy = RHSExp->getType();
4356
4357     BaseExpr = RHSExp;
4358     IndexExpr = LHSExp;
4359     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4360   } else {
4361     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4362        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4363   }
4364   // C99 6.5.2.1p1
4365   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4366     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4367                      << IndexExpr->getSourceRange());
4368
4369   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4370        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4371          && !IndexExpr->isTypeDependent())
4372     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4373
4374   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4375   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4376   // type. Note that Functions are not objects, and that (in C99 parlance)
4377   // incomplete types are not object types.
4378   if (ResultType->isFunctionType()) {
4379     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4380       << ResultType << BaseExpr->getSourceRange();
4381     return ExprError();
4382   }
4383
4384   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4385     // GNU extension: subscripting on pointer to void
4386     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4387       << BaseExpr->getSourceRange();
4388
4389     // C forbids expressions of unqualified void type from being l-values.
4390     // See IsCForbiddenLValueType.
4391     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4392   } else if (!ResultType->isDependentType() &&
4393       RequireCompleteType(LLoc, ResultType,
4394                           diag::err_subscript_incomplete_type, BaseExpr))
4395     return ExprError();
4396
4397   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4398          !ResultType.isCForbiddenLValueType());
4399
4400   return new (Context)
4401       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4402 }
4403
4404 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4405                                         FunctionDecl *FD,
4406                                         ParmVarDecl *Param) {
4407   if (Param->hasUnparsedDefaultArg()) {
4408     Diag(CallLoc,
4409          diag::err_use_of_default_argument_to_function_declared_later) <<
4410       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4411     Diag(UnparsedDefaultArgLocs[Param],
4412          diag::note_default_argument_declared_here);
4413     return ExprError();
4414   }
4415   
4416   if (Param->hasUninstantiatedDefaultArg()) {
4417     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4418
4419     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4420                                                  Param);
4421
4422     // Instantiate the expression.
4423     MultiLevelTemplateArgumentList MutiLevelArgList
4424       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4425
4426     InstantiatingTemplate Inst(*this, CallLoc, Param,
4427                                MutiLevelArgList.getInnermost());
4428     if (Inst.isInvalid())
4429       return ExprError();
4430
4431     ExprResult Result;
4432     {
4433       // C++ [dcl.fct.default]p5:
4434       //   The names in the [default argument] expression are bound, and
4435       //   the semantic constraints are checked, at the point where the
4436       //   default argument expression appears.
4437       ContextRAII SavedContext(*this, FD);
4438       LocalInstantiationScope Local(*this);
4439       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4440     }
4441     if (Result.isInvalid())
4442       return ExprError();
4443
4444     // Check the expression as an initializer for the parameter.
4445     InitializedEntity Entity
4446       = InitializedEntity::InitializeParameter(Context, Param);
4447     InitializationKind Kind
4448       = InitializationKind::CreateCopy(Param->getLocation(),
4449              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4450     Expr *ResultE = Result.getAs<Expr>();
4451
4452     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4453     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4454     if (Result.isInvalid())
4455       return ExprError();
4456
4457     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4458                                  Param->getOuterLocStart());
4459     if (Result.isInvalid())
4460       return ExprError();
4461
4462     // Remember the instantiated default argument.
4463     Param->setDefaultArg(Result.getAs<Expr>());
4464     if (ASTMutationListener *L = getASTMutationListener()) {
4465       L->DefaultArgumentInstantiated(Param);
4466     }
4467   }
4468
4469   // If the default expression creates temporaries, we need to
4470   // push them to the current stack of expression temporaries so they'll
4471   // be properly destroyed.
4472   // FIXME: We should really be rebuilding the default argument with new
4473   // bound temporaries; see the comment in PR5810.
4474   // We don't need to do that with block decls, though, because
4475   // blocks in default argument expression can never capture anything.
4476   if (isa<ExprWithCleanups>(Param->getInit())) {
4477     // Set the "needs cleanups" bit regardless of whether there are
4478     // any explicit objects.
4479     ExprNeedsCleanups = true;
4480
4481     // Append all the objects to the cleanup list.  Right now, this
4482     // should always be a no-op, because blocks in default argument
4483     // expressions should never be able to capture anything.
4484     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4485            "default argument expression has capturing blocks?");
4486   }
4487
4488   // We already type-checked the argument, so we know it works. 
4489   // Just mark all of the declarations in this potentially-evaluated expression
4490   // as being "referenced".
4491   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4492                                    /*SkipLocalVariables=*/true);
4493   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4494 }
4495
4496
4497 Sema::VariadicCallType
4498 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4499                           Expr *Fn) {
4500   if (Proto && Proto->isVariadic()) {
4501     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4502       return VariadicConstructor;
4503     else if (Fn && Fn->getType()->isBlockPointerType())
4504       return VariadicBlock;
4505     else if (FDecl) {
4506       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4507         if (Method->isInstance())
4508           return VariadicMethod;
4509     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4510       return VariadicMethod;
4511     return VariadicFunction;
4512   }
4513   return VariadicDoesNotApply;
4514 }
4515
4516 namespace {
4517 class FunctionCallCCC : public FunctionCallFilterCCC {
4518 public:
4519   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4520                   unsigned NumArgs, MemberExpr *ME)
4521       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4522         FunctionName(FuncName) {}
4523
4524   bool ValidateCandidate(const TypoCorrection &candidate) override {
4525     if (!candidate.getCorrectionSpecifier() ||
4526         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4527       return false;
4528     }
4529
4530     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4531   }
4532
4533 private:
4534   const IdentifierInfo *const FunctionName;
4535 };
4536 }
4537
4538 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4539                                                FunctionDecl *FDecl,
4540                                                ArrayRef<Expr *> Args) {
4541   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4542   DeclarationName FuncName = FDecl->getDeclName();
4543   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4544
4545   if (TypoCorrection Corrected = S.CorrectTypo(
4546           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4547           S.getScopeForContext(S.CurContext), nullptr,
4548           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4549                                              Args.size(), ME),
4550           Sema::CTK_ErrorRecovery)) {
4551     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4552       if (Corrected.isOverloaded()) {
4553         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4554         OverloadCandidateSet::iterator Best;
4555         for (NamedDecl *CD : Corrected) {
4556           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4557             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4558                                    OCS);
4559         }
4560         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4561         case OR_Success:
4562           ND = Best->FoundDecl;
4563           Corrected.setCorrectionDecl(ND);
4564           break;
4565         default:
4566           break;
4567         }
4568       }
4569       ND = ND->getUnderlyingDecl();
4570       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4571         return Corrected;
4572     }
4573   }
4574   return TypoCorrection();
4575 }
4576
4577 /// ConvertArgumentsForCall - Converts the arguments specified in
4578 /// Args/NumArgs to the parameter types of the function FDecl with
4579 /// function prototype Proto. Call is the call expression itself, and
4580 /// Fn is the function expression. For a C++ member function, this
4581 /// routine does not attempt to convert the object argument. Returns
4582 /// true if the call is ill-formed.
4583 bool
4584 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4585                               FunctionDecl *FDecl,
4586                               const FunctionProtoType *Proto,
4587                               ArrayRef<Expr *> Args,
4588                               SourceLocation RParenLoc,
4589                               bool IsExecConfig) {
4590   // Bail out early if calling a builtin with custom typechecking.
4591   if (FDecl)
4592     if (unsigned ID = FDecl->getBuiltinID())
4593       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4594         return false;
4595
4596   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4597   // assignment, to the types of the corresponding parameter, ...
4598   unsigned NumParams = Proto->getNumParams();
4599   bool Invalid = false;
4600   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4601   unsigned FnKind = Fn->getType()->isBlockPointerType()
4602                        ? 1 /* block */
4603                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4604                                        : 0 /* function */);
4605
4606   // If too few arguments are available (and we don't have default
4607   // arguments for the remaining parameters), don't make the call.
4608   if (Args.size() < NumParams) {
4609     if (Args.size() < MinArgs) {
4610       TypoCorrection TC;
4611       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4612         unsigned diag_id =
4613             MinArgs == NumParams && !Proto->isVariadic()
4614                 ? diag::err_typecheck_call_too_few_args_suggest
4615                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4616         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4617                                         << static_cast<unsigned>(Args.size())
4618                                         << TC.getCorrectionRange());
4619       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4620         Diag(RParenLoc,
4621              MinArgs == NumParams && !Proto->isVariadic()
4622                  ? diag::err_typecheck_call_too_few_args_one
4623                  : diag::err_typecheck_call_too_few_args_at_least_one)
4624             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4625       else
4626         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4627                             ? diag::err_typecheck_call_too_few_args
4628                             : diag::err_typecheck_call_too_few_args_at_least)
4629             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4630             << Fn->getSourceRange();
4631
4632       // Emit the location of the prototype.
4633       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4634         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4635           << FDecl;
4636
4637       return true;
4638     }
4639     Call->setNumArgs(Context, NumParams);
4640   }
4641
4642   // If too many are passed and not variadic, error on the extras and drop
4643   // them.
4644   if (Args.size() > NumParams) {
4645     if (!Proto->isVariadic()) {
4646       TypoCorrection TC;
4647       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4648         unsigned diag_id =
4649             MinArgs == NumParams && !Proto->isVariadic()
4650                 ? diag::err_typecheck_call_too_many_args_suggest
4651                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4652         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4653                                         << static_cast<unsigned>(Args.size())
4654                                         << TC.getCorrectionRange());
4655       } else if (NumParams == 1 && FDecl &&
4656                  FDecl->getParamDecl(0)->getDeclName())
4657         Diag(Args[NumParams]->getLocStart(),
4658              MinArgs == NumParams
4659                  ? diag::err_typecheck_call_too_many_args_one
4660                  : diag::err_typecheck_call_too_many_args_at_most_one)
4661             << FnKind << FDecl->getParamDecl(0)
4662             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4663             << SourceRange(Args[NumParams]->getLocStart(),
4664                            Args.back()->getLocEnd());
4665       else
4666         Diag(Args[NumParams]->getLocStart(),
4667              MinArgs == NumParams
4668                  ? diag::err_typecheck_call_too_many_args
4669                  : diag::err_typecheck_call_too_many_args_at_most)
4670             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4671             << Fn->getSourceRange()
4672             << SourceRange(Args[NumParams]->getLocStart(),
4673                            Args.back()->getLocEnd());
4674
4675       // Emit the location of the prototype.
4676       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4677         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4678           << FDecl;
4679       
4680       // This deletes the extra arguments.
4681       Call->setNumArgs(Context, NumParams);
4682       return true;
4683     }
4684   }
4685   SmallVector<Expr *, 8> AllArgs;
4686   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4687   
4688   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4689                                    Proto, 0, Args, AllArgs, CallType);
4690   if (Invalid)
4691     return true;
4692   unsigned TotalNumArgs = AllArgs.size();
4693   for (unsigned i = 0; i < TotalNumArgs; ++i)
4694     Call->setArg(i, AllArgs[i]);
4695
4696   return false;
4697 }
4698
4699 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4700                                   const FunctionProtoType *Proto,
4701                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4702                                   SmallVectorImpl<Expr *> &AllArgs,
4703                                   VariadicCallType CallType, bool AllowExplicit,
4704                                   bool IsListInitialization) {
4705   unsigned NumParams = Proto->getNumParams();
4706   bool Invalid = false;
4707   size_t ArgIx = 0;
4708   // Continue to check argument types (even if we have too few/many args).
4709   for (unsigned i = FirstParam; i < NumParams; i++) {
4710     QualType ProtoArgType = Proto->getParamType(i);
4711
4712     Expr *Arg;
4713     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4714     if (ArgIx < Args.size()) {
4715       Arg = Args[ArgIx++];
4716
4717       if (RequireCompleteType(Arg->getLocStart(),
4718                               ProtoArgType,
4719                               diag::err_call_incomplete_argument, Arg))
4720         return true;
4721
4722       // Strip the unbridged-cast placeholder expression off, if applicable.
4723       bool CFAudited = false;
4724       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4725           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4726           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4727         Arg = stripARCUnbridgedCast(Arg);
4728       else if (getLangOpts().ObjCAutoRefCount &&
4729                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4730                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4731         CFAudited = true;
4732
4733       InitializedEntity Entity =
4734           Param ? InitializedEntity::InitializeParameter(Context, Param,
4735                                                          ProtoArgType)
4736                 : InitializedEntity::InitializeParameter(
4737                       Context, ProtoArgType, Proto->isParamConsumed(i));
4738
4739       // Remember that parameter belongs to a CF audited API.
4740       if (CFAudited)
4741         Entity.setParameterCFAudited();
4742
4743       ExprResult ArgE = PerformCopyInitialization(
4744           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4745       if (ArgE.isInvalid())
4746         return true;
4747
4748       Arg = ArgE.getAs<Expr>();
4749     } else {
4750       assert(Param && "can't use default arguments without a known callee");
4751
4752       ExprResult ArgExpr =
4753         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4754       if (ArgExpr.isInvalid())
4755         return true;
4756
4757       Arg = ArgExpr.getAs<Expr>();
4758     }
4759
4760     // Check for array bounds violations for each argument to the call. This
4761     // check only triggers warnings when the argument isn't a more complex Expr
4762     // with its own checking, such as a BinaryOperator.
4763     CheckArrayAccess(Arg);
4764
4765     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4766     CheckStaticArrayArgument(CallLoc, Param, Arg);
4767
4768     AllArgs.push_back(Arg);
4769   }
4770
4771   // If this is a variadic call, handle args passed through "...".
4772   if (CallType != VariadicDoesNotApply) {
4773     // Assume that extern "C" functions with variadic arguments that
4774     // return __unknown_anytype aren't *really* variadic.
4775     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4776         FDecl->isExternC()) {
4777       for (Expr *A : Args.slice(ArgIx)) {
4778         QualType paramType; // ignored
4779         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4780         Invalid |= arg.isInvalid();
4781         AllArgs.push_back(arg.get());
4782       }
4783
4784     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4785     } else {
4786       for (Expr *A : Args.slice(ArgIx)) {
4787         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4788         Invalid |= Arg.isInvalid();
4789         AllArgs.push_back(Arg.get());
4790       }
4791     }
4792
4793     // Check for array bounds violations.
4794     for (Expr *A : Args.slice(ArgIx))
4795       CheckArrayAccess(A);
4796   }
4797   return Invalid;
4798 }
4799
4800 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4801   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4802   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4803     TL = DTL.getOriginalLoc();
4804   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4805     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4806       << ATL.getLocalSourceRange();
4807 }
4808
4809 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4810 /// array parameter, check that it is non-null, and that if it is formed by
4811 /// array-to-pointer decay, the underlying array is sufficiently large.
4812 ///
4813 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4814 /// array type derivation, then for each call to the function, the value of the
4815 /// corresponding actual argument shall provide access to the first element of
4816 /// an array with at least as many elements as specified by the size expression.
4817 void
4818 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4819                                ParmVarDecl *Param,
4820                                const Expr *ArgExpr) {
4821   // Static array parameters are not supported in C++.
4822   if (!Param || getLangOpts().CPlusPlus)
4823     return;
4824
4825   QualType OrigTy = Param->getOriginalType();
4826
4827   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4828   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4829     return;
4830
4831   if (ArgExpr->isNullPointerConstant(Context,
4832                                      Expr::NPC_NeverValueDependent)) {
4833     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4834     DiagnoseCalleeStaticArrayParam(*this, Param);
4835     return;
4836   }
4837
4838   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4839   if (!CAT)
4840     return;
4841
4842   const ConstantArrayType *ArgCAT =
4843     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4844   if (!ArgCAT)
4845     return;
4846
4847   if (ArgCAT->getSize().ult(CAT->getSize())) {
4848     Diag(CallLoc, diag::warn_static_array_too_small)
4849       << ArgExpr->getSourceRange()
4850       << (unsigned) ArgCAT->getSize().getZExtValue()
4851       << (unsigned) CAT->getSize().getZExtValue();
4852     DiagnoseCalleeStaticArrayParam(*this, Param);
4853   }
4854 }
4855
4856 /// Given a function expression of unknown-any type, try to rebuild it
4857 /// to have a function type.
4858 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4859
4860 /// Is the given type a placeholder that we need to lower out
4861 /// immediately during argument processing?
4862 static bool isPlaceholderToRemoveAsArg(QualType type) {
4863   // Placeholders are never sugared.
4864   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4865   if (!placeholder) return false;
4866
4867   switch (placeholder->getKind()) {
4868   // Ignore all the non-placeholder types.
4869 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4870 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4871 #include "clang/AST/BuiltinTypes.def"
4872     return false;
4873
4874   // We cannot lower out overload sets; they might validly be resolved
4875   // by the call machinery.
4876   case BuiltinType::Overload:
4877     return false;
4878
4879   // Unbridged casts in ARC can be handled in some call positions and
4880   // should be left in place.
4881   case BuiltinType::ARCUnbridgedCast:
4882     return false;
4883
4884   // Pseudo-objects should be converted as soon as possible.
4885   case BuiltinType::PseudoObject:
4886     return true;
4887
4888   // The debugger mode could theoretically but currently does not try
4889   // to resolve unknown-typed arguments based on known parameter types.
4890   case BuiltinType::UnknownAny:
4891     return true;
4892
4893   // These are always invalid as call arguments and should be reported.
4894   case BuiltinType::BoundMember:
4895   case BuiltinType::BuiltinFn:
4896   case BuiltinType::OMPArraySection:
4897     return true;
4898
4899   }
4900   llvm_unreachable("bad builtin type kind");
4901 }
4902
4903 /// Check an argument list for placeholders that we won't try to
4904 /// handle later.
4905 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4906   // Apply this processing to all the arguments at once instead of
4907   // dying at the first failure.
4908   bool hasInvalid = false;
4909   for (size_t i = 0, e = args.size(); i != e; i++) {
4910     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4911       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4912       if (result.isInvalid()) hasInvalid = true;
4913       else args[i] = result.get();
4914     } else if (hasInvalid) {
4915       (void)S.CorrectDelayedTyposInExpr(args[i]);
4916     }
4917   }
4918   return hasInvalid;
4919 }
4920
4921 /// If a builtin function has a pointer argument with no explicit address
4922 /// space, then it should be able to accept a pointer to any address
4923 /// space as input.  In order to do this, we need to replace the
4924 /// standard builtin declaration with one that uses the same address space
4925 /// as the call.
4926 ///
4927 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4928 ///                  it does not contain any pointer arguments without
4929 ///                  an address space qualifer.  Otherwise the rewritten
4930 ///                  FunctionDecl is returned.
4931 /// TODO: Handle pointer return types.
4932 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4933                                                 const FunctionDecl *FDecl,
4934                                                 MultiExprArg ArgExprs) {
4935
4936   QualType DeclType = FDecl->getType();
4937   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4938
4939   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4940       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4941     return nullptr;
4942
4943   bool NeedsNewDecl = false;
4944   unsigned i = 0;
4945   SmallVector<QualType, 8> OverloadParams;
4946
4947   for (QualType ParamType : FT->param_types()) {
4948
4949     // Convert array arguments to pointer to simplify type lookup.
4950     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4951     QualType ArgType = Arg->getType();
4952     if (!ParamType->isPointerType() ||
4953         ParamType.getQualifiers().hasAddressSpace() ||
4954         !ArgType->isPointerType() ||
4955         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4956       OverloadParams.push_back(ParamType);
4957       continue;
4958     }
4959
4960     NeedsNewDecl = true;
4961     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4962
4963     QualType PointeeType = ParamType->getPointeeType();
4964     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4965     OverloadParams.push_back(Context.getPointerType(PointeeType));
4966   }
4967
4968   if (!NeedsNewDecl)
4969     return nullptr;
4970
4971   FunctionProtoType::ExtProtoInfo EPI;
4972   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4973                                                 OverloadParams, EPI);
4974   DeclContext *Parent = Context.getTranslationUnitDecl();
4975   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4976                                                     FDecl->getLocation(),
4977                                                     FDecl->getLocation(),
4978                                                     FDecl->getIdentifier(),
4979                                                     OverloadTy,
4980                                                     /*TInfo=*/nullptr,
4981                                                     SC_Extern, false,
4982                                                     /*hasPrototype=*/true);
4983   SmallVector<ParmVarDecl*, 16> Params;
4984   FT = cast<FunctionProtoType>(OverloadTy);
4985   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4986     QualType ParamType = FT->getParamType(i);
4987     ParmVarDecl *Parm =
4988         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4989                                 SourceLocation(), nullptr, ParamType,
4990                                 /*TInfo=*/nullptr, SC_None, nullptr);
4991     Parm->setScopeInfo(0, i);
4992     Params.push_back(Parm);
4993   }
4994   OverloadDecl->setParams(Params);
4995   return OverloadDecl;
4996 }
4997
4998 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4999 /// This provides the location of the left/right parens and a list of comma
5000 /// locations.
5001 ExprResult
5002 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5003                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
5004                     Expr *ExecConfig, bool IsExecConfig) {
5005   // Since this might be a postfix expression, get rid of ParenListExprs.
5006   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
5007   if (Result.isInvalid()) return ExprError();
5008   Fn = Result.get();
5009
5010   if (checkArgsForPlaceholders(*this, ArgExprs))
5011     return ExprError();
5012
5013   if (getLangOpts().CPlusPlus) {
5014     // If this is a pseudo-destructor expression, build the call immediately.
5015     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5016       if (!ArgExprs.empty()) {
5017         // Pseudo-destructor calls should not have any arguments.
5018         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5019           << FixItHint::CreateRemoval(
5020                                     SourceRange(ArgExprs.front()->getLocStart(),
5021                                                 ArgExprs.back()->getLocEnd()));
5022       }
5023
5024       return new (Context)
5025           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5026     }
5027     if (Fn->getType() == Context.PseudoObjectTy) {
5028       ExprResult result = CheckPlaceholderExpr(Fn);
5029       if (result.isInvalid()) return ExprError();
5030       Fn = result.get();
5031     }
5032
5033     // Determine whether this is a dependent call inside a C++ template,
5034     // in which case we won't do any semantic analysis now.
5035     // FIXME: Will need to cache the results of name lookup (including ADL) in
5036     // Fn.
5037     bool Dependent = false;
5038     if (Fn->isTypeDependent())
5039       Dependent = true;
5040     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5041       Dependent = true;
5042
5043     if (Dependent) {
5044       if (ExecConfig) {
5045         return new (Context) CUDAKernelCallExpr(
5046             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5047             Context.DependentTy, VK_RValue, RParenLoc);
5048       } else {
5049         return new (Context) CallExpr(
5050             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5051       }
5052     }
5053
5054     // Determine whether this is a call to an object (C++ [over.call.object]).
5055     if (Fn->getType()->isRecordType())
5056       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5057                                           RParenLoc);
5058
5059     if (Fn->getType() == Context.UnknownAnyTy) {
5060       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5061       if (result.isInvalid()) return ExprError();
5062       Fn = result.get();
5063     }
5064
5065     if (Fn->getType() == Context.BoundMemberTy) {
5066       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5067     }
5068   }
5069
5070   // Check for overloaded calls.  This can happen even in C due to extensions.
5071   if (Fn->getType() == Context.OverloadTy) {
5072     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5073
5074     // We aren't supposed to apply this logic for if there's an '&' involved.
5075     if (!find.HasFormOfMemberPointer) {
5076       OverloadExpr *ovl = find.Expression;
5077       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5078         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
5079                                        RParenLoc, ExecConfig,
5080                                        /*AllowTypoCorrection=*/true,
5081                                        find.IsAddressOfOperand);
5082       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5083     }
5084   }
5085
5086   // If we're directly calling a function, get the appropriate declaration.
5087   if (Fn->getType() == Context.UnknownAnyTy) {
5088     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5089     if (result.isInvalid()) return ExprError();
5090     Fn = result.get();
5091   }
5092
5093   Expr *NakedFn = Fn->IgnoreParens();
5094
5095   bool CallingNDeclIndirectly = false;
5096   NamedDecl *NDecl = nullptr;
5097   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5098     if (UnOp->getOpcode() == UO_AddrOf) {
5099       CallingNDeclIndirectly = true;
5100       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5101     }
5102   }
5103
5104   if (isa<DeclRefExpr>(NakedFn)) {
5105     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5106
5107     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5108     if (FDecl && FDecl->getBuiltinID()) {
5109       // Rewrite the function decl for this builtin by replacing parameters
5110       // with no explicit address space with the address space of the arguments
5111       // in ArgExprs.
5112       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5113         NDecl = FDecl;
5114         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5115                            SourceLocation(), FDecl, false,
5116                            SourceLocation(), FDecl->getType(),
5117                            Fn->getValueKind(), FDecl);
5118       }
5119     }
5120   } else if (isa<MemberExpr>(NakedFn))
5121     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5122
5123   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5124     if (CallingNDeclIndirectly &&
5125         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5126                                            Fn->getLocStart()))
5127       return ExprError();
5128
5129     if (FD->hasAttr<EnableIfAttr>()) {
5130       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5131         Diag(Fn->getLocStart(),
5132              isa<CXXMethodDecl>(FD) ?
5133                  diag::err_ovl_no_viable_member_function_in_call :
5134                  diag::err_ovl_no_viable_function_in_call)
5135           << FD << FD->getSourceRange();
5136         Diag(FD->getLocation(),
5137              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5138             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5139       }
5140     }
5141   }
5142
5143   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5144                                ExecConfig, IsExecConfig);
5145 }
5146
5147 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5148 ///
5149 /// __builtin_astype( value, dst type )
5150 ///
5151 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5152                                  SourceLocation BuiltinLoc,
5153                                  SourceLocation RParenLoc) {
5154   ExprValueKind VK = VK_RValue;
5155   ExprObjectKind OK = OK_Ordinary;
5156   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5157   QualType SrcTy = E->getType();
5158   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5159     return ExprError(Diag(BuiltinLoc,
5160                           diag::err_invalid_astype_of_different_size)
5161                      << DstTy
5162                      << SrcTy
5163                      << E->getSourceRange());
5164   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5165 }
5166
5167 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5168 /// provided arguments.
5169 ///
5170 /// __builtin_convertvector( value, dst type )
5171 ///
5172 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5173                                         SourceLocation BuiltinLoc,
5174                                         SourceLocation RParenLoc) {
5175   TypeSourceInfo *TInfo;
5176   GetTypeFromParser(ParsedDestTy, &TInfo);
5177   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5178 }
5179
5180 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5181 /// i.e. an expression not of \p OverloadTy.  The expression should
5182 /// unary-convert to an expression of function-pointer or
5183 /// block-pointer type.
5184 ///
5185 /// \param NDecl the declaration being called, if available
5186 ExprResult
5187 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5188                             SourceLocation LParenLoc,
5189                             ArrayRef<Expr *> Args,
5190                             SourceLocation RParenLoc,
5191                             Expr *Config, bool IsExecConfig) {
5192   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5193   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5194
5195   // Promote the function operand.
5196   // We special-case function promotion here because we only allow promoting
5197   // builtin functions to function pointers in the callee of a call.
5198   ExprResult Result;
5199   if (BuiltinID &&
5200       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5201     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5202                                CK_BuiltinFnToFnPtr).get();
5203   } else {
5204     Result = CallExprUnaryConversions(Fn);
5205   }
5206   if (Result.isInvalid())
5207     return ExprError();
5208   Fn = Result.get();
5209
5210   // Make the call expr early, before semantic checks.  This guarantees cleanup
5211   // of arguments and function on error.
5212   CallExpr *TheCall;
5213   if (Config)
5214     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5215                                                cast<CallExpr>(Config), Args,
5216                                                Context.BoolTy, VK_RValue,
5217                                                RParenLoc);
5218   else
5219     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5220                                      VK_RValue, RParenLoc);
5221
5222   if (!getLangOpts().CPlusPlus) {
5223     // C cannot always handle TypoExpr nodes in builtin calls and direct
5224     // function calls as their argument checking don't necessarily handle
5225     // dependent types properly, so make sure any TypoExprs have been
5226     // dealt with.
5227     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5228     if (!Result.isUsable()) return ExprError();
5229     TheCall = dyn_cast<CallExpr>(Result.get());
5230     if (!TheCall) return Result;
5231     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5232   }
5233
5234   // Bail out early if calling a builtin with custom typechecking.
5235   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5236     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5237
5238  retry:
5239   const FunctionType *FuncT;
5240   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5241     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5242     // have type pointer to function".
5243     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5244     if (!FuncT)
5245       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5246                          << Fn->getType() << Fn->getSourceRange());
5247   } else if (const BlockPointerType *BPT =
5248                Fn->getType()->getAs<BlockPointerType>()) {
5249     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5250   } else {
5251     // Handle calls to expressions of unknown-any type.
5252     if (Fn->getType() == Context.UnknownAnyTy) {
5253       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5254       if (rewrite.isInvalid()) return ExprError();
5255       Fn = rewrite.get();
5256       TheCall->setCallee(Fn);
5257       goto retry;
5258     }
5259
5260     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5261       << Fn->getType() << Fn->getSourceRange());
5262   }
5263
5264   if (getLangOpts().CUDA) {
5265     if (Config) {
5266       // CUDA: Kernel calls must be to global functions
5267       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5268         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5269             << FDecl->getName() << Fn->getSourceRange());
5270
5271       // CUDA: Kernel function must have 'void' return type
5272       if (!FuncT->getReturnType()->isVoidType())
5273         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5274             << Fn->getType() << Fn->getSourceRange());
5275     } else {
5276       // CUDA: Calls to global functions must be configured
5277       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5278         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5279             << FDecl->getName() << Fn->getSourceRange());
5280     }
5281   }
5282
5283   // Check for a valid return type
5284   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5285                           FDecl))
5286     return ExprError();
5287
5288   // We know the result type of the call, set it.
5289   TheCall->setType(FuncT->getCallResultType(Context));
5290   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5291
5292   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5293   if (Proto) {
5294     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5295                                 IsExecConfig))
5296       return ExprError();
5297   } else {
5298     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5299
5300     if (FDecl) {
5301       // Check if we have too few/too many template arguments, based
5302       // on our knowledge of the function definition.
5303       const FunctionDecl *Def = nullptr;
5304       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5305         Proto = Def->getType()->getAs<FunctionProtoType>();
5306        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5307           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5308           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5309       }
5310       
5311       // If the function we're calling isn't a function prototype, but we have
5312       // a function prototype from a prior declaratiom, use that prototype.
5313       if (!FDecl->hasPrototype())
5314         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5315     }
5316
5317     // Promote the arguments (C99 6.5.2.2p6).
5318     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5319       Expr *Arg = Args[i];
5320
5321       if (Proto && i < Proto->getNumParams()) {
5322         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5323             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5324         ExprResult ArgE =
5325             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5326         if (ArgE.isInvalid())
5327           return true;
5328         
5329         Arg = ArgE.getAs<Expr>();
5330
5331       } else {
5332         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5333
5334         if (ArgE.isInvalid())
5335           return true;
5336
5337         Arg = ArgE.getAs<Expr>();
5338       }
5339       
5340       if (RequireCompleteType(Arg->getLocStart(),
5341                               Arg->getType(),
5342                               diag::err_call_incomplete_argument, Arg))
5343         return ExprError();
5344
5345       TheCall->setArg(i, Arg);
5346     }
5347   }
5348
5349   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5350     if (!Method->isStatic())
5351       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5352         << Fn->getSourceRange());
5353
5354   // Check for sentinels
5355   if (NDecl)
5356     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5357
5358   // Do special checking on direct calls to functions.
5359   if (FDecl) {
5360     if (CheckFunctionCall(FDecl, TheCall, Proto))
5361       return ExprError();
5362
5363     if (BuiltinID)
5364       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5365   } else if (NDecl) {
5366     if (CheckPointerCall(NDecl, TheCall, Proto))
5367       return ExprError();
5368   } else {
5369     if (CheckOtherCall(TheCall, Proto))
5370       return ExprError();
5371   }
5372
5373   return MaybeBindToTemporary(TheCall);
5374 }
5375
5376 ExprResult
5377 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5378                            SourceLocation RParenLoc, Expr *InitExpr) {
5379   assert(Ty && "ActOnCompoundLiteral(): missing type");
5380   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5381
5382   TypeSourceInfo *TInfo;
5383   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5384   if (!TInfo)
5385     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5386
5387   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5388 }
5389
5390 ExprResult
5391 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5392                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5393   QualType literalType = TInfo->getType();
5394
5395   if (literalType->isArrayType()) {
5396     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5397           diag::err_illegal_decl_array_incomplete_type,
5398           SourceRange(LParenLoc,
5399                       LiteralExpr->getSourceRange().getEnd())))
5400       return ExprError();
5401     if (literalType->isVariableArrayType())
5402       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5403         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5404   } else if (!literalType->isDependentType() &&
5405              RequireCompleteType(LParenLoc, literalType,
5406                diag::err_typecheck_decl_incomplete_type,
5407                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5408     return ExprError();
5409
5410   InitializedEntity Entity
5411     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5412   InitializationKind Kind
5413     = InitializationKind::CreateCStyleCast(LParenLoc, 
5414                                            SourceRange(LParenLoc, RParenLoc),
5415                                            /*InitList=*/true);
5416   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5417   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5418                                       &literalType);
5419   if (Result.isInvalid())
5420     return ExprError();
5421   LiteralExpr = Result.get();
5422
5423   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5424   if (isFileScope &&
5425       !LiteralExpr->isTypeDependent() &&
5426       !LiteralExpr->isValueDependent() &&
5427       !literalType->isDependentType()) { // 6.5.2.5p3
5428     if (CheckForConstantInitializer(LiteralExpr, literalType))
5429       return ExprError();
5430   }
5431
5432   // In C, compound literals are l-values for some reason.
5433   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5434
5435   return MaybeBindToTemporary(
5436            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5437                                              VK, LiteralExpr, isFileScope));
5438 }
5439
5440 ExprResult
5441 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5442                     SourceLocation RBraceLoc) {
5443   // Immediately handle non-overload placeholders.  Overloads can be
5444   // resolved contextually, but everything else here can't.
5445   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5446     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5447       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5448
5449       // Ignore failures; dropping the entire initializer list because
5450       // of one failure would be terrible for indexing/etc.
5451       if (result.isInvalid()) continue;
5452
5453       InitArgList[I] = result.get();
5454     }
5455   }
5456
5457   // Semantic analysis for initializers is done by ActOnDeclarator() and
5458   // CheckInitializer() - it requires knowledge of the object being intialized.
5459
5460   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5461                                                RBraceLoc);
5462   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5463   return E;
5464 }
5465
5466 /// Do an explicit extend of the given block pointer if we're in ARC.
5467 void Sema::maybeExtendBlockObject(ExprResult &E) {
5468   assert(E.get()->getType()->isBlockPointerType());
5469   assert(E.get()->isRValue());
5470
5471   // Only do this in an r-value context.
5472   if (!getLangOpts().ObjCAutoRefCount) return;
5473
5474   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5475                                CK_ARCExtendBlockObject, E.get(),
5476                                /*base path*/ nullptr, VK_RValue);
5477   ExprNeedsCleanups = true;
5478 }
5479
5480 /// Prepare a conversion of the given expression to an ObjC object
5481 /// pointer type.
5482 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5483   QualType type = E.get()->getType();
5484   if (type->isObjCObjectPointerType()) {
5485     return CK_BitCast;
5486   } else if (type->isBlockPointerType()) {
5487     maybeExtendBlockObject(E);
5488     return CK_BlockPointerToObjCPointerCast;
5489   } else {
5490     assert(type->isPointerType());
5491     return CK_CPointerToObjCPointerCast;
5492   }
5493 }
5494
5495 /// Prepares for a scalar cast, performing all the necessary stages
5496 /// except the final cast and returning the kind required.
5497 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5498   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5499   // Also, callers should have filtered out the invalid cases with
5500   // pointers.  Everything else should be possible.
5501
5502   QualType SrcTy = Src.get()->getType();
5503   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5504     return CK_NoOp;
5505
5506   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5507   case Type::STK_MemberPointer:
5508     llvm_unreachable("member pointer type in C");
5509
5510   case Type::STK_CPointer:
5511   case Type::STK_BlockPointer:
5512   case Type::STK_ObjCObjectPointer:
5513     switch (DestTy->getScalarTypeKind()) {
5514     case Type::STK_CPointer: {
5515       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5516       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5517       if (SrcAS != DestAS)
5518         return CK_AddressSpaceConversion;
5519       return CK_BitCast;
5520     }
5521     case Type::STK_BlockPointer:
5522       return (SrcKind == Type::STK_BlockPointer
5523                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5524     case Type::STK_ObjCObjectPointer:
5525       if (SrcKind == Type::STK_ObjCObjectPointer)
5526         return CK_BitCast;
5527       if (SrcKind == Type::STK_CPointer)
5528         return CK_CPointerToObjCPointerCast;
5529       maybeExtendBlockObject(Src);
5530       return CK_BlockPointerToObjCPointerCast;
5531     case Type::STK_Bool:
5532       return CK_PointerToBoolean;
5533     case Type::STK_Integral:
5534       return CK_PointerToIntegral;
5535     case Type::STK_Floating:
5536     case Type::STK_FloatingComplex:
5537     case Type::STK_IntegralComplex:
5538     case Type::STK_MemberPointer:
5539       llvm_unreachable("illegal cast from pointer");
5540     }
5541     llvm_unreachable("Should have returned before this");
5542
5543   case Type::STK_Bool: // casting from bool is like casting from an integer
5544   case Type::STK_Integral:
5545     switch (DestTy->getScalarTypeKind()) {
5546     case Type::STK_CPointer:
5547     case Type::STK_ObjCObjectPointer:
5548     case Type::STK_BlockPointer:
5549       if (Src.get()->isNullPointerConstant(Context,
5550                                            Expr::NPC_ValueDependentIsNull))
5551         return CK_NullToPointer;
5552       return CK_IntegralToPointer;
5553     case Type::STK_Bool:
5554       return CK_IntegralToBoolean;
5555     case Type::STK_Integral:
5556       return CK_IntegralCast;
5557     case Type::STK_Floating:
5558       return CK_IntegralToFloating;
5559     case Type::STK_IntegralComplex:
5560       Src = ImpCastExprToType(Src.get(),
5561                       DestTy->castAs<ComplexType>()->getElementType(),
5562                       CK_IntegralCast);
5563       return CK_IntegralRealToComplex;
5564     case Type::STK_FloatingComplex:
5565       Src = ImpCastExprToType(Src.get(),
5566                       DestTy->castAs<ComplexType>()->getElementType(),
5567                       CK_IntegralToFloating);
5568       return CK_FloatingRealToComplex;
5569     case Type::STK_MemberPointer:
5570       llvm_unreachable("member pointer type in C");
5571     }
5572     llvm_unreachable("Should have returned before this");
5573
5574   case Type::STK_Floating:
5575     switch (DestTy->getScalarTypeKind()) {
5576     case Type::STK_Floating:
5577       return CK_FloatingCast;
5578     case Type::STK_Bool:
5579       return CK_FloatingToBoolean;
5580     case Type::STK_Integral:
5581       return CK_FloatingToIntegral;
5582     case Type::STK_FloatingComplex:
5583       Src = ImpCastExprToType(Src.get(),
5584                               DestTy->castAs<ComplexType>()->getElementType(),
5585                               CK_FloatingCast);
5586       return CK_FloatingRealToComplex;
5587     case Type::STK_IntegralComplex:
5588       Src = ImpCastExprToType(Src.get(),
5589                               DestTy->castAs<ComplexType>()->getElementType(),
5590                               CK_FloatingToIntegral);
5591       return CK_IntegralRealToComplex;
5592     case Type::STK_CPointer:
5593     case Type::STK_ObjCObjectPointer:
5594     case Type::STK_BlockPointer:
5595       llvm_unreachable("valid float->pointer cast?");
5596     case Type::STK_MemberPointer:
5597       llvm_unreachable("member pointer type in C");
5598     }
5599     llvm_unreachable("Should have returned before this");
5600
5601   case Type::STK_FloatingComplex:
5602     switch (DestTy->getScalarTypeKind()) {
5603     case Type::STK_FloatingComplex:
5604       return CK_FloatingComplexCast;
5605     case Type::STK_IntegralComplex:
5606       return CK_FloatingComplexToIntegralComplex;
5607     case Type::STK_Floating: {
5608       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5609       if (Context.hasSameType(ET, DestTy))
5610         return CK_FloatingComplexToReal;
5611       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5612       return CK_FloatingCast;
5613     }
5614     case Type::STK_Bool:
5615       return CK_FloatingComplexToBoolean;
5616     case Type::STK_Integral:
5617       Src = ImpCastExprToType(Src.get(),
5618                               SrcTy->castAs<ComplexType>()->getElementType(),
5619                               CK_FloatingComplexToReal);
5620       return CK_FloatingToIntegral;
5621     case Type::STK_CPointer:
5622     case Type::STK_ObjCObjectPointer:
5623     case Type::STK_BlockPointer:
5624       llvm_unreachable("valid complex float->pointer cast?");
5625     case Type::STK_MemberPointer:
5626       llvm_unreachable("member pointer type in C");
5627     }
5628     llvm_unreachable("Should have returned before this");
5629
5630   case Type::STK_IntegralComplex:
5631     switch (DestTy->getScalarTypeKind()) {
5632     case Type::STK_FloatingComplex:
5633       return CK_IntegralComplexToFloatingComplex;
5634     case Type::STK_IntegralComplex:
5635       return CK_IntegralComplexCast;
5636     case Type::STK_Integral: {
5637       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5638       if (Context.hasSameType(ET, DestTy))
5639         return CK_IntegralComplexToReal;
5640       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5641       return CK_IntegralCast;
5642     }
5643     case Type::STK_Bool:
5644       return CK_IntegralComplexToBoolean;
5645     case Type::STK_Floating:
5646       Src = ImpCastExprToType(Src.get(),
5647                               SrcTy->castAs<ComplexType>()->getElementType(),
5648                               CK_IntegralComplexToReal);
5649       return CK_IntegralToFloating;
5650     case Type::STK_CPointer:
5651     case Type::STK_ObjCObjectPointer:
5652     case Type::STK_BlockPointer:
5653       llvm_unreachable("valid complex int->pointer cast?");
5654     case Type::STK_MemberPointer:
5655       llvm_unreachable("member pointer type in C");
5656     }
5657     llvm_unreachable("Should have returned before this");
5658   }
5659
5660   llvm_unreachable("Unhandled scalar cast");
5661 }
5662
5663 static bool breakDownVectorType(QualType type, uint64_t &len,
5664                                 QualType &eltType) {
5665   // Vectors are simple.
5666   if (const VectorType *vecType = type->getAs<VectorType>()) {
5667     len = vecType->getNumElements();
5668     eltType = vecType->getElementType();
5669     assert(eltType->isScalarType());
5670     return true;
5671   }
5672   
5673   // We allow lax conversion to and from non-vector types, but only if
5674   // they're real types (i.e. non-complex, non-pointer scalar types).
5675   if (!type->isRealType()) return false;
5676   
5677   len = 1;
5678   eltType = type;
5679   return true;
5680 }
5681
5682 /// Are the two types lax-compatible vector types?  That is, given
5683 /// that one of them is a vector, do they have equal storage sizes,
5684 /// where the storage size is the number of elements times the element
5685 /// size?
5686 ///
5687 /// This will also return false if either of the types is neither a
5688 /// vector nor a real type.
5689 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5690   assert(destTy->isVectorType() || srcTy->isVectorType());
5691   
5692   // Disallow lax conversions between scalars and ExtVectors (these
5693   // conversions are allowed for other vector types because common headers
5694   // depend on them).  Most scalar OP ExtVector cases are handled by the
5695   // splat path anyway, which does what we want (convert, not bitcast).
5696   // What this rules out for ExtVectors is crazy things like char4*float.
5697   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5698   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5699
5700   uint64_t srcLen, destLen;
5701   QualType srcEltTy, destEltTy;
5702   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5703   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5704   
5705   // ASTContext::getTypeSize will return the size rounded up to a
5706   // power of 2, so instead of using that, we need to use the raw
5707   // element size multiplied by the element count.
5708   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5709   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5710   
5711   return (srcLen * srcEltSize == destLen * destEltSize);
5712 }
5713
5714 /// Is this a legal conversion between two types, one of which is
5715 /// known to be a vector type?
5716 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5717   assert(destTy->isVectorType() || srcTy->isVectorType());
5718   
5719   if (!Context.getLangOpts().LaxVectorConversions)
5720     return false;
5721   return areLaxCompatibleVectorTypes(srcTy, destTy);
5722 }
5723
5724 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5725                            CastKind &Kind) {
5726   assert(VectorTy->isVectorType() && "Not a vector type!");
5727
5728   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5729     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5730       return Diag(R.getBegin(),
5731                   Ty->isVectorType() ?
5732                   diag::err_invalid_conversion_between_vectors :
5733                   diag::err_invalid_conversion_between_vector_and_integer)
5734         << VectorTy << Ty << R;
5735   } else
5736     return Diag(R.getBegin(),
5737                 diag::err_invalid_conversion_between_vector_and_scalar)
5738       << VectorTy << Ty << R;
5739
5740   Kind = CK_BitCast;
5741   return false;
5742 }
5743
5744 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5745   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5746
5747   if (DestElemTy == SplattedExpr->getType())
5748     return SplattedExpr;
5749
5750   assert(DestElemTy->isFloatingType() ||
5751          DestElemTy->isIntegralOrEnumerationType());
5752
5753   CastKind CK;
5754   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5755     // OpenCL requires that we convert `true` boolean expressions to -1, but
5756     // only when splatting vectors.
5757     if (DestElemTy->isFloatingType()) {
5758       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5759       // in two steps: boolean to signed integral, then to floating.
5760       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5761                                                  CK_BooleanToSignedIntegral);
5762       SplattedExpr = CastExprRes.get();
5763       CK = CK_IntegralToFloating;
5764     } else {
5765       CK = CK_BooleanToSignedIntegral;
5766     }
5767   } else {
5768     ExprResult CastExprRes = SplattedExpr;
5769     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5770     if (CastExprRes.isInvalid())
5771       return ExprError();
5772     SplattedExpr = CastExprRes.get();
5773   }
5774   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5775 }
5776
5777 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5778                                     Expr *CastExpr, CastKind &Kind) {
5779   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5780
5781   QualType SrcTy = CastExpr->getType();
5782
5783   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5784   // an ExtVectorType.
5785   // In OpenCL, casts between vectors of different types are not allowed.
5786   // (See OpenCL 6.2).
5787   if (SrcTy->isVectorType()) {
5788     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5789         || (getLangOpts().OpenCL &&
5790             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5791       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5792         << DestTy << SrcTy << R;
5793       return ExprError();
5794     }
5795     Kind = CK_BitCast;
5796     return CastExpr;
5797   }
5798
5799   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5800   // conversion will take place first from scalar to elt type, and then
5801   // splat from elt type to vector.
5802   if (SrcTy->isPointerType())
5803     return Diag(R.getBegin(),
5804                 diag::err_invalid_conversion_between_vector_and_scalar)
5805       << DestTy << SrcTy << R;
5806
5807   Kind = CK_VectorSplat;
5808   return prepareVectorSplat(DestTy, CastExpr);
5809 }
5810
5811 ExprResult
5812 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5813                     Declarator &D, ParsedType &Ty,
5814                     SourceLocation RParenLoc, Expr *CastExpr) {
5815   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5816          "ActOnCastExpr(): missing type or expr");
5817
5818   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5819   if (D.isInvalidType())
5820     return ExprError();
5821
5822   if (getLangOpts().CPlusPlus) {
5823     // Check that there are no default arguments (C++ only).
5824     CheckExtraCXXDefaultArguments(D);
5825   } else {
5826     // Make sure any TypoExprs have been dealt with.
5827     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5828     if (!Res.isUsable())
5829       return ExprError();
5830     CastExpr = Res.get();
5831   }
5832
5833   checkUnusedDeclAttributes(D);
5834
5835   QualType castType = castTInfo->getType();
5836   Ty = CreateParsedType(castType, castTInfo);
5837
5838   bool isVectorLiteral = false;
5839
5840   // Check for an altivec or OpenCL literal,
5841   // i.e. all the elements are integer constants.
5842   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5843   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5844   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5845        && castType->isVectorType() && (PE || PLE)) {
5846     if (PLE && PLE->getNumExprs() == 0) {
5847       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5848       return ExprError();
5849     }
5850     if (PE || PLE->getNumExprs() == 1) {
5851       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5852       if (!E->getType()->isVectorType())
5853         isVectorLiteral = true;
5854     }
5855     else
5856       isVectorLiteral = true;
5857   }
5858
5859   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5860   // then handle it as such.
5861   if (isVectorLiteral)
5862     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5863
5864   // If the Expr being casted is a ParenListExpr, handle it specially.
5865   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5866   // sequence of BinOp comma operators.
5867   if (isa<ParenListExpr>(CastExpr)) {
5868     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5869     if (Result.isInvalid()) return ExprError();
5870     CastExpr = Result.get();
5871   }
5872
5873   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5874       !getSourceManager().isInSystemMacro(LParenLoc))
5875     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5876   
5877   CheckTollFreeBridgeCast(castType, CastExpr);
5878   
5879   CheckObjCBridgeRelatedCast(castType, CastExpr);
5880   
5881   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5882 }
5883
5884 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5885                                     SourceLocation RParenLoc, Expr *E,
5886                                     TypeSourceInfo *TInfo) {
5887   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5888          "Expected paren or paren list expression");
5889
5890   Expr **exprs;
5891   unsigned numExprs;
5892   Expr *subExpr;
5893   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5894   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5895     LiteralLParenLoc = PE->getLParenLoc();
5896     LiteralRParenLoc = PE->getRParenLoc();
5897     exprs = PE->getExprs();
5898     numExprs = PE->getNumExprs();
5899   } else { // isa<ParenExpr> by assertion at function entrance
5900     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5901     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5902     subExpr = cast<ParenExpr>(E)->getSubExpr();
5903     exprs = &subExpr;
5904     numExprs = 1;
5905   }
5906
5907   QualType Ty = TInfo->getType();
5908   assert(Ty->isVectorType() && "Expected vector type");
5909
5910   SmallVector<Expr *, 8> initExprs;
5911   const VectorType *VTy = Ty->getAs<VectorType>();
5912   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5913   
5914   // '(...)' form of vector initialization in AltiVec: the number of
5915   // initializers must be one or must match the size of the vector.
5916   // If a single value is specified in the initializer then it will be
5917   // replicated to all the components of the vector
5918   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5919     // The number of initializers must be one or must match the size of the
5920     // vector. If a single value is specified in the initializer then it will
5921     // be replicated to all the components of the vector
5922     if (numExprs == 1) {
5923       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5924       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5925       if (Literal.isInvalid())
5926         return ExprError();
5927       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5928                                   PrepareScalarCast(Literal, ElemTy));
5929       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5930     }
5931     else if (numExprs < numElems) {
5932       Diag(E->getExprLoc(),
5933            diag::err_incorrect_number_of_vector_initializers);
5934       return ExprError();
5935     }
5936     else
5937       initExprs.append(exprs, exprs + numExprs);
5938   }
5939   else {
5940     // For OpenCL, when the number of initializers is a single value,
5941     // it will be replicated to all components of the vector.
5942     if (getLangOpts().OpenCL &&
5943         VTy->getVectorKind() == VectorType::GenericVector &&
5944         numExprs == 1) {
5945         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5946         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5947         if (Literal.isInvalid())
5948           return ExprError();
5949         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5950                                     PrepareScalarCast(Literal, ElemTy));
5951         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5952     }
5953     
5954     initExprs.append(exprs, exprs + numExprs);
5955   }
5956   // FIXME: This means that pretty-printing the final AST will produce curly
5957   // braces instead of the original commas.
5958   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5959                                                    initExprs, LiteralRParenLoc);
5960   initE->setType(Ty);
5961   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5962 }
5963
5964 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5965 /// the ParenListExpr into a sequence of comma binary operators.
5966 ExprResult
5967 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5968   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5969   if (!E)
5970     return OrigExpr;
5971
5972   ExprResult Result(E->getExpr(0));
5973
5974   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5975     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5976                         E->getExpr(i));
5977
5978   if (Result.isInvalid()) return ExprError();
5979
5980   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5981 }
5982
5983 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5984                                     SourceLocation R,
5985                                     MultiExprArg Val) {
5986   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5987   return expr;
5988 }
5989
5990 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5991 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5992 /// emitted.
5993 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5994                                       SourceLocation QuestionLoc) {
5995   Expr *NullExpr = LHSExpr;
5996   Expr *NonPointerExpr = RHSExpr;
5997   Expr::NullPointerConstantKind NullKind =
5998       NullExpr->isNullPointerConstant(Context,
5999                                       Expr::NPC_ValueDependentIsNotNull);
6000
6001   if (NullKind == Expr::NPCK_NotNull) {
6002     NullExpr = RHSExpr;
6003     NonPointerExpr = LHSExpr;
6004     NullKind =
6005         NullExpr->isNullPointerConstant(Context,
6006                                         Expr::NPC_ValueDependentIsNotNull);
6007   }
6008
6009   if (NullKind == Expr::NPCK_NotNull)
6010     return false;
6011
6012   if (NullKind == Expr::NPCK_ZeroExpression)
6013     return false;
6014
6015   if (NullKind == Expr::NPCK_ZeroLiteral) {
6016     // In this case, check to make sure that we got here from a "NULL"
6017     // string in the source code.
6018     NullExpr = NullExpr->IgnoreParenImpCasts();
6019     SourceLocation loc = NullExpr->getExprLoc();
6020     if (!findMacroSpelling(loc, "NULL"))
6021       return false;
6022   }
6023
6024   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6025   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6026       << NonPointerExpr->getType() << DiagType
6027       << NonPointerExpr->getSourceRange();
6028   return true;
6029 }
6030
6031 /// \brief Return false if the condition expression is valid, true otherwise.
6032 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6033   QualType CondTy = Cond->getType();
6034
6035   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6036   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6037     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6038       << CondTy << Cond->getSourceRange();
6039     return true;
6040   }
6041
6042   // C99 6.5.15p2
6043   if (CondTy->isScalarType()) return false;
6044
6045   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6046     << CondTy << Cond->getSourceRange();
6047   return true;
6048 }
6049
6050 /// \brief Handle when one or both operands are void type.
6051 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6052                                          ExprResult &RHS) {
6053     Expr *LHSExpr = LHS.get();
6054     Expr *RHSExpr = RHS.get();
6055
6056     if (!LHSExpr->getType()->isVoidType())
6057       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6058         << RHSExpr->getSourceRange();
6059     if (!RHSExpr->getType()->isVoidType())
6060       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6061         << LHSExpr->getSourceRange();
6062     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6063     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6064     return S.Context.VoidTy;
6065 }
6066
6067 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6068 /// true otherwise.
6069 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6070                                         QualType PointerTy) {
6071   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6072       !NullExpr.get()->isNullPointerConstant(S.Context,
6073                                             Expr::NPC_ValueDependentIsNull))
6074     return true;
6075
6076   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6077   return false;
6078 }
6079
6080 /// \brief Checks compatibility between two pointers and return the resulting
6081 /// type.
6082 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6083                                                      ExprResult &RHS,
6084                                                      SourceLocation Loc) {
6085   QualType LHSTy = LHS.get()->getType();
6086   QualType RHSTy = RHS.get()->getType();
6087
6088   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6089     // Two identical pointers types are always compatible.
6090     return LHSTy;
6091   }
6092
6093   QualType lhptee, rhptee;
6094
6095   // Get the pointee types.
6096   bool IsBlockPointer = false;
6097   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6098     lhptee = LHSBTy->getPointeeType();
6099     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6100     IsBlockPointer = true;
6101   } else {
6102     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6103     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6104   }
6105
6106   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6107   // differently qualified versions of compatible types, the result type is
6108   // a pointer to an appropriately qualified version of the composite
6109   // type.
6110
6111   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6112   // clause doesn't make sense for our extensions. E.g. address space 2 should
6113   // be incompatible with address space 3: they may live on different devices or
6114   // anything.
6115   Qualifiers lhQual = lhptee.getQualifiers();
6116   Qualifiers rhQual = rhptee.getQualifiers();
6117
6118   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6119   lhQual.removeCVRQualifiers();
6120   rhQual.removeCVRQualifiers();
6121
6122   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6123   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6124
6125   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6126
6127   if (CompositeTy.isNull()) {
6128     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6129       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6130       << RHS.get()->getSourceRange();
6131     // In this situation, we assume void* type. No especially good
6132     // reason, but this is what gcc does, and we do have to pick
6133     // to get a consistent AST.
6134     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6135     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6136     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6137     return incompatTy;
6138   }
6139
6140   // The pointer types are compatible.
6141   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6142   if (IsBlockPointer)
6143     ResultTy = S.Context.getBlockPointerType(ResultTy);
6144   else
6145     ResultTy = S.Context.getPointerType(ResultTy);
6146
6147   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
6148   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
6149   return ResultTy;
6150 }
6151
6152 /// \brief Return the resulting type when the operands are both block pointers.
6153 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6154                                                           ExprResult &LHS,
6155                                                           ExprResult &RHS,
6156                                                           SourceLocation Loc) {
6157   QualType LHSTy = LHS.get()->getType();
6158   QualType RHSTy = RHS.get()->getType();
6159
6160   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6161     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6162       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6163       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6164       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6165       return destType;
6166     }
6167     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6168       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6169       << RHS.get()->getSourceRange();
6170     return QualType();
6171   }
6172
6173   // We have 2 block pointer types.
6174   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6175 }
6176
6177 /// \brief Return the resulting type when the operands are both pointers.
6178 static QualType
6179 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6180                                             ExprResult &RHS,
6181                                             SourceLocation Loc) {
6182   // get the pointer types
6183   QualType LHSTy = LHS.get()->getType();
6184   QualType RHSTy = RHS.get()->getType();
6185
6186   // get the "pointed to" types
6187   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6188   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6189
6190   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6191   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6192     // Figure out necessary qualifiers (C99 6.5.15p6)
6193     QualType destPointee
6194       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6195     QualType destType = S.Context.getPointerType(destPointee);
6196     // Add qualifiers if necessary.
6197     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6198     // Promote to void*.
6199     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6200     return destType;
6201   }
6202   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6203     QualType destPointee
6204       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6205     QualType destType = S.Context.getPointerType(destPointee);
6206     // Add qualifiers if necessary.
6207     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6208     // Promote to void*.
6209     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6210     return destType;
6211   }
6212
6213   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6214 }
6215
6216 /// \brief Return false if the first expression is not an integer and the second
6217 /// expression is not a pointer, true otherwise.
6218 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6219                                         Expr* PointerExpr, SourceLocation Loc,
6220                                         bool IsIntFirstExpr) {
6221   if (!PointerExpr->getType()->isPointerType() ||
6222       !Int.get()->getType()->isIntegerType())
6223     return false;
6224
6225   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6226   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6227
6228   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6229     << Expr1->getType() << Expr2->getType()
6230     << Expr1->getSourceRange() << Expr2->getSourceRange();
6231   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6232                             CK_IntegralToPointer);
6233   return true;
6234 }
6235
6236 /// \brief Simple conversion between integer and floating point types.
6237 ///
6238 /// Used when handling the OpenCL conditional operator where the
6239 /// condition is a vector while the other operands are scalar.
6240 ///
6241 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6242 /// types are either integer or floating type. Between the two
6243 /// operands, the type with the higher rank is defined as the "result
6244 /// type". The other operand needs to be promoted to the same type. No
6245 /// other type promotion is allowed. We cannot use
6246 /// UsualArithmeticConversions() for this purpose, since it always
6247 /// promotes promotable types.
6248 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6249                                             ExprResult &RHS,
6250                                             SourceLocation QuestionLoc) {
6251   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6252   if (LHS.isInvalid())
6253     return QualType();
6254   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6255   if (RHS.isInvalid())
6256     return QualType();
6257
6258   // For conversion purposes, we ignore any qualifiers.
6259   // For example, "const float" and "float" are equivalent.
6260   QualType LHSType =
6261     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6262   QualType RHSType =
6263     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6264
6265   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6266     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6267       << LHSType << LHS.get()->getSourceRange();
6268     return QualType();
6269   }
6270
6271   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6272     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6273       << RHSType << RHS.get()->getSourceRange();
6274     return QualType();
6275   }
6276
6277   // If both types are identical, no conversion is needed.
6278   if (LHSType == RHSType)
6279     return LHSType;
6280
6281   // Now handle "real" floating types (i.e. float, double, long double).
6282   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6283     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6284                                  /*IsCompAssign = */ false);
6285
6286   // Finally, we have two differing integer types.
6287   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6288   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6289 }
6290
6291 /// \brief Convert scalar operands to a vector that matches the
6292 ///        condition in length.
6293 ///
6294 /// Used when handling the OpenCL conditional operator where the
6295 /// condition is a vector while the other operands are scalar.
6296 ///
6297 /// We first compute the "result type" for the scalar operands
6298 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6299 /// into a vector of that type where the length matches the condition
6300 /// vector type. s6.11.6 requires that the element types of the result
6301 /// and the condition must have the same number of bits.
6302 static QualType
6303 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6304                               QualType CondTy, SourceLocation QuestionLoc) {
6305   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6306   if (ResTy.isNull()) return QualType();
6307
6308   const VectorType *CV = CondTy->getAs<VectorType>();
6309   assert(CV);
6310
6311   // Determine the vector result type
6312   unsigned NumElements = CV->getNumElements();
6313   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6314
6315   // Ensure that all types have the same number of bits
6316   if (S.Context.getTypeSize(CV->getElementType())
6317       != S.Context.getTypeSize(ResTy)) {
6318     // Since VectorTy is created internally, it does not pretty print
6319     // with an OpenCL name. Instead, we just print a description.
6320     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6321     SmallString<64> Str;
6322     llvm::raw_svector_ostream OS(Str);
6323     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6324     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6325       << CondTy << OS.str();
6326     return QualType();
6327   }
6328
6329   // Convert operands to the vector result type
6330   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6331   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6332
6333   return VectorTy;
6334 }
6335
6336 /// \brief Return false if this is a valid OpenCL condition vector
6337 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6338                                        SourceLocation QuestionLoc) {
6339   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6340   // integral type.
6341   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6342   assert(CondTy);
6343   QualType EleTy = CondTy->getElementType();
6344   if (EleTy->isIntegerType()) return false;
6345
6346   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6347     << Cond->getType() << Cond->getSourceRange();
6348   return true;
6349 }
6350
6351 /// \brief Return false if the vector condition type and the vector
6352 ///        result type are compatible.
6353 ///
6354 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6355 /// number of elements, and their element types have the same number
6356 /// of bits.
6357 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6358                               SourceLocation QuestionLoc) {
6359   const VectorType *CV = CondTy->getAs<VectorType>();
6360   const VectorType *RV = VecResTy->getAs<VectorType>();
6361   assert(CV && RV);
6362
6363   if (CV->getNumElements() != RV->getNumElements()) {
6364     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6365       << CondTy << VecResTy;
6366     return true;
6367   }
6368
6369   QualType CVE = CV->getElementType();
6370   QualType RVE = RV->getElementType();
6371
6372   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6373     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6374       << CondTy << VecResTy;
6375     return true;
6376   }
6377
6378   return false;
6379 }
6380
6381 /// \brief Return the resulting type for the conditional operator in
6382 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6383 ///        s6.3.i) when the condition is a vector type.
6384 static QualType
6385 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6386                              ExprResult &LHS, ExprResult &RHS,
6387                              SourceLocation QuestionLoc) {
6388   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6389   if (Cond.isInvalid())
6390     return QualType();
6391   QualType CondTy = Cond.get()->getType();
6392
6393   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6394     return QualType();
6395
6396   // If either operand is a vector then find the vector type of the
6397   // result as specified in OpenCL v1.1 s6.3.i.
6398   if (LHS.get()->getType()->isVectorType() ||
6399       RHS.get()->getType()->isVectorType()) {
6400     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6401                                               /*isCompAssign*/false,
6402                                               /*AllowBothBool*/true,
6403                                               /*AllowBoolConversions*/false);
6404     if (VecResTy.isNull()) return QualType();
6405     // The result type must match the condition type as specified in
6406     // OpenCL v1.1 s6.11.6.
6407     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6408       return QualType();
6409     return VecResTy;
6410   }
6411
6412   // Both operands are scalar.
6413   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6414 }
6415
6416 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6417 /// In that case, LHS = cond.
6418 /// C99 6.5.15
6419 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6420                                         ExprResult &RHS, ExprValueKind &VK,
6421                                         ExprObjectKind &OK,
6422                                         SourceLocation QuestionLoc) {
6423
6424   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6425   if (!LHSResult.isUsable()) return QualType();
6426   LHS = LHSResult;
6427
6428   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6429   if (!RHSResult.isUsable()) return QualType();
6430   RHS = RHSResult;
6431
6432   // C++ is sufficiently different to merit its own checker.
6433   if (getLangOpts().CPlusPlus)
6434     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6435
6436   VK = VK_RValue;
6437   OK = OK_Ordinary;
6438
6439   // The OpenCL operator with a vector condition is sufficiently
6440   // different to merit its own checker.
6441   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6442     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6443
6444   // First, check the condition.
6445   Cond = UsualUnaryConversions(Cond.get());
6446   if (Cond.isInvalid())
6447     return QualType();
6448   if (checkCondition(*this, Cond.get(), QuestionLoc))
6449     return QualType();
6450
6451   // Now check the two expressions.
6452   if (LHS.get()->getType()->isVectorType() ||
6453       RHS.get()->getType()->isVectorType())
6454     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6455                                /*AllowBothBool*/true,
6456                                /*AllowBoolConversions*/false);
6457
6458   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6459   if (LHS.isInvalid() || RHS.isInvalid())
6460     return QualType();
6461
6462   QualType LHSTy = LHS.get()->getType();
6463   QualType RHSTy = RHS.get()->getType();
6464
6465   // If both operands have arithmetic type, do the usual arithmetic conversions
6466   // to find a common type: C99 6.5.15p3,5.
6467   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6468     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6469     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6470
6471     return ResTy;
6472   }
6473
6474   // If both operands are the same structure or union type, the result is that
6475   // type.
6476   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6477     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6478       if (LHSRT->getDecl() == RHSRT->getDecl())
6479         // "If both the operands have structure or union type, the result has
6480         // that type."  This implies that CV qualifiers are dropped.
6481         return LHSTy.getUnqualifiedType();
6482     // FIXME: Type of conditional expression must be complete in C mode.
6483   }
6484
6485   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6486   // The following || allows only one side to be void (a GCC-ism).
6487   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6488     return checkConditionalVoidType(*this, LHS, RHS);
6489   }
6490
6491   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6492   // the type of the other operand."
6493   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6494   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6495
6496   // All objective-c pointer type analysis is done here.
6497   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6498                                                         QuestionLoc);
6499   if (LHS.isInvalid() || RHS.isInvalid())
6500     return QualType();
6501   if (!compositeType.isNull())
6502     return compositeType;
6503
6504
6505   // Handle block pointer types.
6506   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6507     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6508                                                      QuestionLoc);
6509
6510   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6511   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6512     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6513                                                        QuestionLoc);
6514
6515   // GCC compatibility: soften pointer/integer mismatch.  Note that
6516   // null pointers have been filtered out by this point.
6517   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6518       /*isIntFirstExpr=*/true))
6519     return RHSTy;
6520   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6521       /*isIntFirstExpr=*/false))
6522     return LHSTy;
6523
6524   // Emit a better diagnostic if one of the expressions is a null pointer
6525   // constant and the other is not a pointer type. In this case, the user most
6526   // likely forgot to take the address of the other expression.
6527   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6528     return QualType();
6529
6530   // Otherwise, the operands are not compatible.
6531   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6532     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6533     << RHS.get()->getSourceRange();
6534   return QualType();
6535 }
6536
6537 /// FindCompositeObjCPointerType - Helper method to find composite type of
6538 /// two objective-c pointer types of the two input expressions.
6539 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6540                                             SourceLocation QuestionLoc) {
6541   QualType LHSTy = LHS.get()->getType();
6542   QualType RHSTy = RHS.get()->getType();
6543
6544   // Handle things like Class and struct objc_class*.  Here we case the result
6545   // to the pseudo-builtin, because that will be implicitly cast back to the
6546   // redefinition type if an attempt is made to access its fields.
6547   if (LHSTy->isObjCClassType() &&
6548       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6549     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6550     return LHSTy;
6551   }
6552   if (RHSTy->isObjCClassType() &&
6553       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6554     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6555     return RHSTy;
6556   }
6557   // And the same for struct objc_object* / id
6558   if (LHSTy->isObjCIdType() &&
6559       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6560     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6561     return LHSTy;
6562   }
6563   if (RHSTy->isObjCIdType() &&
6564       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6565     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6566     return RHSTy;
6567   }
6568   // And the same for struct objc_selector* / SEL
6569   if (Context.isObjCSelType(LHSTy) &&
6570       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6571     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6572     return LHSTy;
6573   }
6574   if (Context.isObjCSelType(RHSTy) &&
6575       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6576     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6577     return RHSTy;
6578   }
6579   // Check constraints for Objective-C object pointers types.
6580   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6581
6582     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6583       // Two identical object pointer types are always compatible.
6584       return LHSTy;
6585     }
6586     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6587     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6588     QualType compositeType = LHSTy;
6589
6590     // If both operands are interfaces and either operand can be
6591     // assigned to the other, use that type as the composite
6592     // type. This allows
6593     //   xxx ? (A*) a : (B*) b
6594     // where B is a subclass of A.
6595     //
6596     // Additionally, as for assignment, if either type is 'id'
6597     // allow silent coercion. Finally, if the types are
6598     // incompatible then make sure to use 'id' as the composite
6599     // type so the result is acceptable for sending messages to.
6600
6601     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6602     // It could return the composite type.
6603     if (!(compositeType =
6604           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6605       // Nothing more to do.
6606     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6607       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6608     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6609       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6610     } else if ((LHSTy->isObjCQualifiedIdType() ||
6611                 RHSTy->isObjCQualifiedIdType()) &&
6612                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6613       // Need to handle "id<xx>" explicitly.
6614       // GCC allows qualified id and any Objective-C type to devolve to
6615       // id. Currently localizing to here until clear this should be
6616       // part of ObjCQualifiedIdTypesAreCompatible.
6617       compositeType = Context.getObjCIdType();
6618     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6619       compositeType = Context.getObjCIdType();
6620     } else {
6621       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6622       << LHSTy << RHSTy
6623       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6624       QualType incompatTy = Context.getObjCIdType();
6625       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6626       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6627       return incompatTy;
6628     }
6629     // The object pointer types are compatible.
6630     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6631     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6632     return compositeType;
6633   }
6634   // Check Objective-C object pointer types and 'void *'
6635   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6636     if (getLangOpts().ObjCAutoRefCount) {
6637       // ARC forbids the implicit conversion of object pointers to 'void *',
6638       // so these types are not compatible.
6639       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6640           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6641       LHS = RHS = true;
6642       return QualType();
6643     }
6644     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6645     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6646     QualType destPointee
6647     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6648     QualType destType = Context.getPointerType(destPointee);
6649     // Add qualifiers if necessary.
6650     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6651     // Promote to void*.
6652     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6653     return destType;
6654   }
6655   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6656     if (getLangOpts().ObjCAutoRefCount) {
6657       // ARC forbids the implicit conversion of object pointers to 'void *',
6658       // so these types are not compatible.
6659       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6660           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6661       LHS = RHS = true;
6662       return QualType();
6663     }
6664     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6665     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6666     QualType destPointee
6667     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6668     QualType destType = Context.getPointerType(destPointee);
6669     // Add qualifiers if necessary.
6670     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6671     // Promote to void*.
6672     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6673     return destType;
6674   }
6675   return QualType();
6676 }
6677
6678 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6679 /// ParenRange in parentheses.
6680 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6681                                const PartialDiagnostic &Note,
6682                                SourceRange ParenRange) {
6683   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6684   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6685       EndLoc.isValid()) {
6686     Self.Diag(Loc, Note)
6687       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6688       << FixItHint::CreateInsertion(EndLoc, ")");
6689   } else {
6690     // We can't display the parentheses, so just show the bare note.
6691     Self.Diag(Loc, Note) << ParenRange;
6692   }
6693 }
6694
6695 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6696   return BinaryOperator::isAdditiveOp(Opc) ||
6697          BinaryOperator::isMultiplicativeOp(Opc) ||
6698          BinaryOperator::isShiftOp(Opc);
6699 }
6700
6701 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6702 /// expression, either using a built-in or overloaded operator,
6703 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6704 /// expression.
6705 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6706                                    Expr **RHSExprs) {
6707   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6708   E = E->IgnoreImpCasts();
6709   E = E->IgnoreConversionOperator();
6710   E = E->IgnoreImpCasts();
6711
6712   // Built-in binary operator.
6713   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6714     if (IsArithmeticOp(OP->getOpcode())) {
6715       *Opcode = OP->getOpcode();
6716       *RHSExprs = OP->getRHS();
6717       return true;
6718     }
6719   }
6720
6721   // Overloaded operator.
6722   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6723     if (Call->getNumArgs() != 2)
6724       return false;
6725
6726     // Make sure this is really a binary operator that is safe to pass into
6727     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6728     OverloadedOperatorKind OO = Call->getOperator();
6729     if (OO < OO_Plus || OO > OO_Arrow ||
6730         OO == OO_PlusPlus || OO == OO_MinusMinus)
6731       return false;
6732
6733     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6734     if (IsArithmeticOp(OpKind)) {
6735       *Opcode = OpKind;
6736       *RHSExprs = Call->getArg(1);
6737       return true;
6738     }
6739   }
6740
6741   return false;
6742 }
6743
6744 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6745 /// or is a logical expression such as (x==y) which has int type, but is
6746 /// commonly interpreted as boolean.
6747 static bool ExprLooksBoolean(Expr *E) {
6748   E = E->IgnoreParenImpCasts();
6749
6750   if (E->getType()->isBooleanType())
6751     return true;
6752   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6753     return OP->isComparisonOp() || OP->isLogicalOp();
6754   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6755     return OP->getOpcode() == UO_LNot;
6756   if (E->getType()->isPointerType())
6757     return true;
6758
6759   return false;
6760 }
6761
6762 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6763 /// and binary operator are mixed in a way that suggests the programmer assumed
6764 /// the conditional operator has higher precedence, for example:
6765 /// "int x = a + someBinaryCondition ? 1 : 2".
6766 static void DiagnoseConditionalPrecedence(Sema &Self,
6767                                           SourceLocation OpLoc,
6768                                           Expr *Condition,
6769                                           Expr *LHSExpr,
6770                                           Expr *RHSExpr) {
6771   BinaryOperatorKind CondOpcode;
6772   Expr *CondRHS;
6773
6774   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6775     return;
6776   if (!ExprLooksBoolean(CondRHS))
6777     return;
6778
6779   // The condition is an arithmetic binary expression, with a right-
6780   // hand side that looks boolean, so warn.
6781
6782   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6783       << Condition->getSourceRange()
6784       << BinaryOperator::getOpcodeStr(CondOpcode);
6785
6786   SuggestParentheses(Self, OpLoc,
6787     Self.PDiag(diag::note_precedence_silence)
6788       << BinaryOperator::getOpcodeStr(CondOpcode),
6789     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6790
6791   SuggestParentheses(Self, OpLoc,
6792     Self.PDiag(diag::note_precedence_conditional_first),
6793     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6794 }
6795
6796 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6797 /// in the case of a the GNU conditional expr extension.
6798 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6799                                     SourceLocation ColonLoc,
6800                                     Expr *CondExpr, Expr *LHSExpr,
6801                                     Expr *RHSExpr) {
6802   if (!getLangOpts().CPlusPlus) {
6803     // C cannot handle TypoExpr nodes in the condition because it
6804     // doesn't handle dependent types properly, so make sure any TypoExprs have
6805     // been dealt with before checking the operands.
6806     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6807     if (!CondResult.isUsable()) return ExprError();
6808     CondExpr = CondResult.get();
6809   }
6810
6811   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6812   // was the condition.
6813   OpaqueValueExpr *opaqueValue = nullptr;
6814   Expr *commonExpr = nullptr;
6815   if (!LHSExpr) {
6816     commonExpr = CondExpr;
6817     // Lower out placeholder types first.  This is important so that we don't
6818     // try to capture a placeholder. This happens in few cases in C++; such
6819     // as Objective-C++'s dictionary subscripting syntax.
6820     if (commonExpr->hasPlaceholderType()) {
6821       ExprResult result = CheckPlaceholderExpr(commonExpr);
6822       if (!result.isUsable()) return ExprError();
6823       commonExpr = result.get();
6824     }
6825     // We usually want to apply unary conversions *before* saving, except
6826     // in the special case of a C++ l-value conditional.
6827     if (!(getLangOpts().CPlusPlus
6828           && !commonExpr->isTypeDependent()
6829           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6830           && commonExpr->isGLValue()
6831           && commonExpr->isOrdinaryOrBitFieldObject()
6832           && RHSExpr->isOrdinaryOrBitFieldObject()
6833           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6834       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6835       if (commonRes.isInvalid())
6836         return ExprError();
6837       commonExpr = commonRes.get();
6838     }
6839
6840     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6841                                                 commonExpr->getType(),
6842                                                 commonExpr->getValueKind(),
6843                                                 commonExpr->getObjectKind(),
6844                                                 commonExpr);
6845     LHSExpr = CondExpr = opaqueValue;
6846   }
6847
6848   ExprValueKind VK = VK_RValue;
6849   ExprObjectKind OK = OK_Ordinary;
6850   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6851   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
6852                                              VK, OK, QuestionLoc);
6853   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6854       RHS.isInvalid())
6855     return ExprError();
6856
6857   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6858                                 RHS.get());
6859
6860   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
6861
6862   if (!commonExpr)
6863     return new (Context)
6864         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6865                             RHS.get(), result, VK, OK);
6866
6867   return new (Context) BinaryConditionalOperator(
6868       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6869       ColonLoc, result, VK, OK);
6870 }
6871
6872 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6873 // being closely modeled after the C99 spec:-). The odd characteristic of this
6874 // routine is it effectively iqnores the qualifiers on the top level pointee.
6875 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6876 // FIXME: add a couple examples in this comment.
6877 static Sema::AssignConvertType
6878 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6879   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6880   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6881
6882   // get the "pointed to" type (ignoring qualifiers at the top level)
6883   const Type *lhptee, *rhptee;
6884   Qualifiers lhq, rhq;
6885   std::tie(lhptee, lhq) =
6886       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6887   std::tie(rhptee, rhq) =
6888       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6889
6890   Sema::AssignConvertType ConvTy = Sema::Compatible;
6891
6892   // C99 6.5.16.1p1: This following citation is common to constraints
6893   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6894   // qualifiers of the type *pointed to* by the right;
6895
6896   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6897   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6898       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6899     // Ignore lifetime for further calculation.
6900     lhq.removeObjCLifetime();
6901     rhq.removeObjCLifetime();
6902   }
6903
6904   if (!lhq.compatiblyIncludes(rhq)) {
6905     // Treat address-space mismatches as fatal.  TODO: address subspaces
6906     if (!lhq.isAddressSpaceSupersetOf(rhq))
6907       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6908
6909     // It's okay to add or remove GC or lifetime qualifiers when converting to
6910     // and from void*.
6911     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6912                         .compatiblyIncludes(
6913                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6914              && (lhptee->isVoidType() || rhptee->isVoidType()))
6915       ; // keep old
6916
6917     // Treat lifetime mismatches as fatal.
6918     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6919       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6920     
6921     // For GCC compatibility, other qualifier mismatches are treated
6922     // as still compatible in C.
6923     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6924   }
6925
6926   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6927   // incomplete type and the other is a pointer to a qualified or unqualified
6928   // version of void...
6929   if (lhptee->isVoidType()) {
6930     if (rhptee->isIncompleteOrObjectType())
6931       return ConvTy;
6932
6933     // As an extension, we allow cast to/from void* to function pointer.
6934     assert(rhptee->isFunctionType());
6935     return Sema::FunctionVoidPointer;
6936   }
6937
6938   if (rhptee->isVoidType()) {
6939     if (lhptee->isIncompleteOrObjectType())
6940       return ConvTy;
6941
6942     // As an extension, we allow cast to/from void* to function pointer.
6943     assert(lhptee->isFunctionType());
6944     return Sema::FunctionVoidPointer;
6945   }
6946
6947   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6948   // unqualified versions of compatible types, ...
6949   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6950   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6951     // Check if the pointee types are compatible ignoring the sign.
6952     // We explicitly check for char so that we catch "char" vs
6953     // "unsigned char" on systems where "char" is unsigned.
6954     if (lhptee->isCharType())
6955       ltrans = S.Context.UnsignedCharTy;
6956     else if (lhptee->hasSignedIntegerRepresentation())
6957       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6958
6959     if (rhptee->isCharType())
6960       rtrans = S.Context.UnsignedCharTy;
6961     else if (rhptee->hasSignedIntegerRepresentation())
6962       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6963
6964     if (ltrans == rtrans) {
6965       // Types are compatible ignoring the sign. Qualifier incompatibility
6966       // takes priority over sign incompatibility because the sign
6967       // warning can be disabled.
6968       if (ConvTy != Sema::Compatible)
6969         return ConvTy;
6970
6971       return Sema::IncompatiblePointerSign;
6972     }
6973
6974     // If we are a multi-level pointer, it's possible that our issue is simply
6975     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6976     // the eventual target type is the same and the pointers have the same
6977     // level of indirection, this must be the issue.
6978     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6979       do {
6980         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6981         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6982       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6983
6984       if (lhptee == rhptee)
6985         return Sema::IncompatibleNestedPointerQualifiers;
6986     }
6987
6988     // General pointer incompatibility takes priority over qualifiers.
6989     return Sema::IncompatiblePointer;
6990   }
6991   if (!S.getLangOpts().CPlusPlus &&
6992       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6993     return Sema::IncompatiblePointer;
6994   return ConvTy;
6995 }
6996
6997 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6998 /// block pointer types are compatible or whether a block and normal pointer
6999 /// are compatible. It is more restrict than comparing two function pointer
7000 // types.
7001 static Sema::AssignConvertType
7002 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7003                                     QualType RHSType) {
7004   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7005   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7006
7007   QualType lhptee, rhptee;
7008
7009   // get the "pointed to" type (ignoring qualifiers at the top level)
7010   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7011   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7012
7013   // In C++, the types have to match exactly.
7014   if (S.getLangOpts().CPlusPlus)
7015     return Sema::IncompatibleBlockPointer;
7016
7017   Sema::AssignConvertType ConvTy = Sema::Compatible;
7018
7019   // For blocks we enforce that qualifiers are identical.
7020   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7021     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7022
7023   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7024     return Sema::IncompatibleBlockPointer;
7025
7026   return ConvTy;
7027 }
7028
7029 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7030 /// for assignment compatibility.
7031 static Sema::AssignConvertType
7032 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7033                                    QualType RHSType) {
7034   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7035   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7036
7037   if (LHSType->isObjCBuiltinType()) {
7038     // Class is not compatible with ObjC object pointers.
7039     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7040         !RHSType->isObjCQualifiedClassType())
7041       return Sema::IncompatiblePointer;
7042     return Sema::Compatible;
7043   }
7044   if (RHSType->isObjCBuiltinType()) {
7045     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7046         !LHSType->isObjCQualifiedClassType())
7047       return Sema::IncompatiblePointer;
7048     return Sema::Compatible;
7049   }
7050   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7051   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7052
7053   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7054       // make an exception for id<P>
7055       !LHSType->isObjCQualifiedIdType())
7056     return Sema::CompatiblePointerDiscardsQualifiers;
7057
7058   if (S.Context.typesAreCompatible(LHSType, RHSType))
7059     return Sema::Compatible;
7060   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7061     return Sema::IncompatibleObjCQualifiedId;
7062   return Sema::IncompatiblePointer;
7063 }
7064
7065 Sema::AssignConvertType
7066 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7067                                  QualType LHSType, QualType RHSType) {
7068   // Fake up an opaque expression.  We don't actually care about what
7069   // cast operations are required, so if CheckAssignmentConstraints
7070   // adds casts to this they'll be wasted, but fortunately that doesn't
7071   // usually happen on valid code.
7072   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7073   ExprResult RHSPtr = &RHSExpr;
7074   CastKind K = CK_Invalid;
7075
7076   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7077 }
7078
7079 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7080 /// has code to accommodate several GCC extensions when type checking
7081 /// pointers. Here are some objectionable examples that GCC considers warnings:
7082 ///
7083 ///  int a, *pint;
7084 ///  short *pshort;
7085 ///  struct foo *pfoo;
7086 ///
7087 ///  pint = pshort; // warning: assignment from incompatible pointer type
7088 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7089 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7090 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7091 ///
7092 /// As a result, the code for dealing with pointers is more complex than the
7093 /// C99 spec dictates.
7094 ///
7095 /// Sets 'Kind' for any result kind except Incompatible.
7096 Sema::AssignConvertType
7097 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7098                                  CastKind &Kind, bool ConvertRHS) {
7099   QualType RHSType = RHS.get()->getType();
7100   QualType OrigLHSType = LHSType;
7101
7102   // Get canonical types.  We're not formatting these types, just comparing
7103   // them.
7104   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7105   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7106
7107   // Common case: no conversion required.
7108   if (LHSType == RHSType) {
7109     Kind = CK_NoOp;
7110     return Compatible;
7111   }
7112
7113   // If we have an atomic type, try a non-atomic assignment, then just add an
7114   // atomic qualification step.
7115   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7116     Sema::AssignConvertType result =
7117       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7118     if (result != Compatible)
7119       return result;
7120     if (Kind != CK_NoOp && ConvertRHS)
7121       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7122     Kind = CK_NonAtomicToAtomic;
7123     return Compatible;
7124   }
7125
7126   // If the left-hand side is a reference type, then we are in a
7127   // (rare!) case where we've allowed the use of references in C,
7128   // e.g., as a parameter type in a built-in function. In this case,
7129   // just make sure that the type referenced is compatible with the
7130   // right-hand side type. The caller is responsible for adjusting
7131   // LHSType so that the resulting expression does not have reference
7132   // type.
7133   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7134     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7135       Kind = CK_LValueBitCast;
7136       return Compatible;
7137     }
7138     return Incompatible;
7139   }
7140
7141   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7142   // to the same ExtVector type.
7143   if (LHSType->isExtVectorType()) {
7144     if (RHSType->isExtVectorType())
7145       return Incompatible;
7146     if (RHSType->isArithmeticType()) {
7147       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7148       if (ConvertRHS)
7149         RHS = prepareVectorSplat(LHSType, RHS.get());
7150       Kind = CK_VectorSplat;
7151       return Compatible;
7152     }
7153   }
7154
7155   // Conversions to or from vector type.
7156   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7157     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7158       // Allow assignments of an AltiVec vector type to an equivalent GCC
7159       // vector type and vice versa
7160       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7161         Kind = CK_BitCast;
7162         return Compatible;
7163       }
7164
7165       // If we are allowing lax vector conversions, and LHS and RHS are both
7166       // vectors, the total size only needs to be the same. This is a bitcast;
7167       // no bits are changed but the result type is different.
7168       if (isLaxVectorConversion(RHSType, LHSType)) {
7169         Kind = CK_BitCast;
7170         return IncompatibleVectors;
7171       }
7172     }
7173     return Incompatible;
7174   }
7175
7176   // Arithmetic conversions.
7177   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7178       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7179     if (ConvertRHS)
7180       Kind = PrepareScalarCast(RHS, LHSType);
7181     return Compatible;
7182   }
7183
7184   // Conversions to normal pointers.
7185   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7186     // U* -> T*
7187     if (isa<PointerType>(RHSType)) {
7188       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7189       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7190       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7191       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7192     }
7193
7194     // int -> T*
7195     if (RHSType->isIntegerType()) {
7196       Kind = CK_IntegralToPointer; // FIXME: null?
7197       return IntToPointer;
7198     }
7199
7200     // C pointers are not compatible with ObjC object pointers,
7201     // with two exceptions:
7202     if (isa<ObjCObjectPointerType>(RHSType)) {
7203       //  - conversions to void*
7204       if (LHSPointer->getPointeeType()->isVoidType()) {
7205         Kind = CK_BitCast;
7206         return Compatible;
7207       }
7208
7209       //  - conversions from 'Class' to the redefinition type
7210       if (RHSType->isObjCClassType() &&
7211           Context.hasSameType(LHSType, 
7212                               Context.getObjCClassRedefinitionType())) {
7213         Kind = CK_BitCast;
7214         return Compatible;
7215       }
7216
7217       Kind = CK_BitCast;
7218       return IncompatiblePointer;
7219     }
7220
7221     // U^ -> void*
7222     if (RHSType->getAs<BlockPointerType>()) {
7223       if (LHSPointer->getPointeeType()->isVoidType()) {
7224         Kind = CK_BitCast;
7225         return Compatible;
7226       }
7227     }
7228
7229     return Incompatible;
7230   }
7231
7232   // Conversions to block pointers.
7233   if (isa<BlockPointerType>(LHSType)) {
7234     // U^ -> T^
7235     if (RHSType->isBlockPointerType()) {
7236       Kind = CK_BitCast;
7237       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7238     }
7239
7240     // int or null -> T^
7241     if (RHSType->isIntegerType()) {
7242       Kind = CK_IntegralToPointer; // FIXME: null
7243       return IntToBlockPointer;
7244     }
7245
7246     // id -> T^
7247     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7248       Kind = CK_AnyPointerToBlockPointerCast;
7249       return Compatible;
7250     }
7251
7252     // void* -> T^
7253     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7254       if (RHSPT->getPointeeType()->isVoidType()) {
7255         Kind = CK_AnyPointerToBlockPointerCast;
7256         return Compatible;
7257       }
7258
7259     return Incompatible;
7260   }
7261
7262   // Conversions to Objective-C pointers.
7263   if (isa<ObjCObjectPointerType>(LHSType)) {
7264     // A* -> B*
7265     if (RHSType->isObjCObjectPointerType()) {
7266       Kind = CK_BitCast;
7267       Sema::AssignConvertType result = 
7268         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7269       if (getLangOpts().ObjCAutoRefCount &&
7270           result == Compatible && 
7271           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7272         result = IncompatibleObjCWeakRef;
7273       return result;
7274     }
7275
7276     // int or null -> A*
7277     if (RHSType->isIntegerType()) {
7278       Kind = CK_IntegralToPointer; // FIXME: null
7279       return IntToPointer;
7280     }
7281
7282     // In general, C pointers are not compatible with ObjC object pointers,
7283     // with two exceptions:
7284     if (isa<PointerType>(RHSType)) {
7285       Kind = CK_CPointerToObjCPointerCast;
7286
7287       //  - conversions from 'void*'
7288       if (RHSType->isVoidPointerType()) {
7289         return Compatible;
7290       }
7291
7292       //  - conversions to 'Class' from its redefinition type
7293       if (LHSType->isObjCClassType() &&
7294           Context.hasSameType(RHSType, 
7295                               Context.getObjCClassRedefinitionType())) {
7296         return Compatible;
7297       }
7298
7299       return IncompatiblePointer;
7300     }
7301
7302     // Only under strict condition T^ is compatible with an Objective-C pointer.
7303     if (RHSType->isBlockPointerType() && 
7304         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7305       if (ConvertRHS)
7306         maybeExtendBlockObject(RHS);
7307       Kind = CK_BlockPointerToObjCPointerCast;
7308       return Compatible;
7309     }
7310
7311     return Incompatible;
7312   }
7313
7314   // Conversions from pointers that are not covered by the above.
7315   if (isa<PointerType>(RHSType)) {
7316     // T* -> _Bool
7317     if (LHSType == Context.BoolTy) {
7318       Kind = CK_PointerToBoolean;
7319       return Compatible;
7320     }
7321
7322     // T* -> int
7323     if (LHSType->isIntegerType()) {
7324       Kind = CK_PointerToIntegral;
7325       return PointerToInt;
7326     }
7327
7328     return Incompatible;
7329   }
7330
7331   // Conversions from Objective-C pointers that are not covered by the above.
7332   if (isa<ObjCObjectPointerType>(RHSType)) {
7333     // T* -> _Bool
7334     if (LHSType == Context.BoolTy) {
7335       Kind = CK_PointerToBoolean;
7336       return Compatible;
7337     }
7338
7339     // T* -> int
7340     if (LHSType->isIntegerType()) {
7341       Kind = CK_PointerToIntegral;
7342       return PointerToInt;
7343     }
7344
7345     return Incompatible;
7346   }
7347
7348   // struct A -> struct B
7349   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7350     if (Context.typesAreCompatible(LHSType, RHSType)) {
7351       Kind = CK_NoOp;
7352       return Compatible;
7353     }
7354   }
7355
7356   return Incompatible;
7357 }
7358
7359 /// \brief Constructs a transparent union from an expression that is
7360 /// used to initialize the transparent union.
7361 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7362                                       ExprResult &EResult, QualType UnionType,
7363                                       FieldDecl *Field) {
7364   // Build an initializer list that designates the appropriate member
7365   // of the transparent union.
7366   Expr *E = EResult.get();
7367   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7368                                                    E, SourceLocation());
7369   Initializer->setType(UnionType);
7370   Initializer->setInitializedFieldInUnion(Field);
7371
7372   // Build a compound literal constructing a value of the transparent
7373   // union type from this initializer list.
7374   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7375   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7376                                         VK_RValue, Initializer, false);
7377 }
7378
7379 Sema::AssignConvertType
7380 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7381                                                ExprResult &RHS) {
7382   QualType RHSType = RHS.get()->getType();
7383
7384   // If the ArgType is a Union type, we want to handle a potential
7385   // transparent_union GCC extension.
7386   const RecordType *UT = ArgType->getAsUnionType();
7387   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7388     return Incompatible;
7389
7390   // The field to initialize within the transparent union.
7391   RecordDecl *UD = UT->getDecl();
7392   FieldDecl *InitField = nullptr;
7393   // It's compatible if the expression matches any of the fields.
7394   for (auto *it : UD->fields()) {
7395     if (it->getType()->isPointerType()) {
7396       // If the transparent union contains a pointer type, we allow:
7397       // 1) void pointer
7398       // 2) null pointer constant
7399       if (RHSType->isPointerType())
7400         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7401           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7402           InitField = it;
7403           break;
7404         }
7405
7406       if (RHS.get()->isNullPointerConstant(Context,
7407                                            Expr::NPC_ValueDependentIsNull)) {
7408         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7409                                 CK_NullToPointer);
7410         InitField = it;
7411         break;
7412       }
7413     }
7414
7415     CastKind Kind = CK_Invalid;
7416     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7417           == Compatible) {
7418       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7419       InitField = it;
7420       break;
7421     }
7422   }
7423
7424   if (!InitField)
7425     return Incompatible;
7426
7427   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7428   return Compatible;
7429 }
7430
7431 Sema::AssignConvertType
7432 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7433                                        bool Diagnose,
7434                                        bool DiagnoseCFAudited,
7435                                        bool ConvertRHS) {
7436   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7437   // we can't avoid *all* modifications at the moment, so we need some somewhere
7438   // to put the updated value.
7439   ExprResult LocalRHS = CallerRHS;
7440   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7441
7442   if (getLangOpts().CPlusPlus) {
7443     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7444       // C++ 5.17p3: If the left operand is not of class type, the
7445       // expression is implicitly converted (C++ 4) to the
7446       // cv-unqualified type of the left operand.
7447       ExprResult Res;
7448       if (Diagnose) {
7449         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7450                                         AA_Assigning);
7451       } else {
7452         ImplicitConversionSequence ICS =
7453             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7454                                   /*SuppressUserConversions=*/false,
7455                                   /*AllowExplicit=*/false,
7456                                   /*InOverloadResolution=*/false,
7457                                   /*CStyle=*/false,
7458                                   /*AllowObjCWritebackConversion=*/false);
7459         if (ICS.isFailure())
7460           return Incompatible;
7461         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7462                                         ICS, AA_Assigning);
7463       }
7464       if (Res.isInvalid())
7465         return Incompatible;
7466       Sema::AssignConvertType result = Compatible;
7467       if (getLangOpts().ObjCAutoRefCount &&
7468           !CheckObjCARCUnavailableWeakConversion(LHSType,
7469                                                  RHS.get()->getType()))
7470         result = IncompatibleObjCWeakRef;
7471       RHS = Res;
7472       return result;
7473     }
7474
7475     // FIXME: Currently, we fall through and treat C++ classes like C
7476     // structures.
7477     // FIXME: We also fall through for atomics; not sure what should
7478     // happen there, though.
7479   } else if (RHS.get()->getType() == Context.OverloadTy) {
7480     // As a set of extensions to C, we support overloading on functions. These
7481     // functions need to be resolved here.
7482     DeclAccessPair DAP;
7483     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7484             RHS.get(), LHSType, /*Complain=*/false, DAP))
7485       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7486     else
7487       return Incompatible;
7488   }
7489
7490   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7491   // a null pointer constant.
7492   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7493        LHSType->isBlockPointerType()) &&
7494       RHS.get()->isNullPointerConstant(Context,
7495                                        Expr::NPC_ValueDependentIsNull)) {
7496     if (Diagnose || ConvertRHS) {
7497       CastKind Kind;
7498       CXXCastPath Path;
7499       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7500                              /*IgnoreBaseAccess=*/false, Diagnose);
7501       if (ConvertRHS)
7502         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7503     }
7504     return Compatible;
7505   }
7506
7507   // This check seems unnatural, however it is necessary to ensure the proper
7508   // conversion of functions/arrays. If the conversion were done for all
7509   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7510   // expressions that suppress this implicit conversion (&, sizeof).
7511   //
7512   // Suppress this for references: C++ 8.5.3p5.
7513   if (!LHSType->isReferenceType()) {
7514     // FIXME: We potentially allocate here even if ConvertRHS is false.
7515     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7516     if (RHS.isInvalid())
7517       return Incompatible;
7518   }
7519
7520   Expr *PRE = RHS.get()->IgnoreParenCasts();
7521   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7522     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7523     if (PDecl && !PDecl->hasDefinition()) {
7524       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7525       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7526     }
7527   }
7528   
7529   CastKind Kind = CK_Invalid;
7530   Sema::AssignConvertType result =
7531     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7532
7533   // C99 6.5.16.1p2: The value of the right operand is converted to the
7534   // type of the assignment expression.
7535   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7536   // so that we can use references in built-in functions even in C.
7537   // The getNonReferenceType() call makes sure that the resulting expression
7538   // does not have reference type.
7539   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7540     QualType Ty = LHSType.getNonLValueExprType(Context);
7541     Expr *E = RHS.get();
7542     if (getLangOpts().ObjCAutoRefCount)
7543       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7544                              Diagnose, DiagnoseCFAudited);
7545     if (getLangOpts().ObjC1 &&
7546         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7547                                            E->getType(), E, Diagnose) ||
7548          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7549       RHS = E;
7550       return Compatible;
7551     }
7552     
7553     if (ConvertRHS)
7554       RHS = ImpCastExprToType(E, Ty, Kind);
7555   }
7556   return result;
7557 }
7558
7559 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7560                                ExprResult &RHS) {
7561   Diag(Loc, diag::err_typecheck_invalid_operands)
7562     << LHS.get()->getType() << RHS.get()->getType()
7563     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7564   return QualType();
7565 }
7566
7567 /// Try to convert a value of non-vector type to a vector type by converting
7568 /// the type to the element type of the vector and then performing a splat.
7569 /// If the language is OpenCL, we only use conversions that promote scalar
7570 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7571 /// for float->int.
7572 ///
7573 /// \param scalar - if non-null, actually perform the conversions
7574 /// \return true if the operation fails (but without diagnosing the failure)
7575 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7576                                      QualType scalarTy,
7577                                      QualType vectorEltTy,
7578                                      QualType vectorTy) {
7579   // The conversion to apply to the scalar before splatting it,
7580   // if necessary.
7581   CastKind scalarCast = CK_Invalid;
7582   
7583   if (vectorEltTy->isIntegralType(S.Context)) {
7584     if (!scalarTy->isIntegralType(S.Context))
7585       return true;
7586     if (S.getLangOpts().OpenCL &&
7587         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7588       return true;
7589     scalarCast = CK_IntegralCast;
7590   } else if (vectorEltTy->isRealFloatingType()) {
7591     if (scalarTy->isRealFloatingType()) {
7592       if (S.getLangOpts().OpenCL &&
7593           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7594         return true;
7595       scalarCast = CK_FloatingCast;
7596     }
7597     else if (scalarTy->isIntegralType(S.Context))
7598       scalarCast = CK_IntegralToFloating;
7599     else
7600       return true;
7601   } else {
7602     return true;
7603   }
7604
7605   // Adjust scalar if desired.
7606   if (scalar) {
7607     if (scalarCast != CK_Invalid)
7608       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7609     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7610   }
7611   return false;
7612 }
7613
7614 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7615                                    SourceLocation Loc, bool IsCompAssign,
7616                                    bool AllowBothBool,
7617                                    bool AllowBoolConversions) {
7618   if (!IsCompAssign) {
7619     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7620     if (LHS.isInvalid())
7621       return QualType();
7622   }
7623   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7624   if (RHS.isInvalid())
7625     return QualType();
7626
7627   // For conversion purposes, we ignore any qualifiers.
7628   // For example, "const float" and "float" are equivalent.
7629   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7630   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7631
7632   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7633   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7634   assert(LHSVecType || RHSVecType);
7635
7636   // AltiVec-style "vector bool op vector bool" combinations are allowed
7637   // for some operators but not others.
7638   if (!AllowBothBool &&
7639       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7640       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7641     return InvalidOperands(Loc, LHS, RHS);
7642
7643   // If the vector types are identical, return.
7644   if (Context.hasSameType(LHSType, RHSType))
7645     return LHSType;
7646
7647   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7648   if (LHSVecType && RHSVecType &&
7649       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7650     if (isa<ExtVectorType>(LHSVecType)) {
7651       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7652       return LHSType;
7653     }
7654
7655     if (!IsCompAssign)
7656       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7657     return RHSType;
7658   }
7659
7660   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7661   // can be mixed, with the result being the non-bool type.  The non-bool
7662   // operand must have integer element type.
7663   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7664       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7665       (Context.getTypeSize(LHSVecType->getElementType()) ==
7666        Context.getTypeSize(RHSVecType->getElementType()))) {
7667     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7668         LHSVecType->getElementType()->isIntegerType() &&
7669         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7670       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7671       return LHSType;
7672     }
7673     if (!IsCompAssign &&
7674         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7675         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7676         RHSVecType->getElementType()->isIntegerType()) {
7677       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7678       return RHSType;
7679     }
7680   }
7681
7682   // If there's an ext-vector type and a scalar, try to convert the scalar to
7683   // the vector element type and splat.
7684   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7685     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7686                                   LHSVecType->getElementType(), LHSType))
7687       return LHSType;
7688   }
7689   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7690     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7691                                   LHSType, RHSVecType->getElementType(),
7692                                   RHSType))
7693       return RHSType;
7694   }
7695
7696   // If we're allowing lax vector conversions, only the total (data) size
7697   // needs to be the same.
7698   // FIXME: Should we really be allowing this?
7699   // FIXME: We really just pick the LHS type arbitrarily?
7700   if (isLaxVectorConversion(RHSType, LHSType)) {
7701     QualType resultType = LHSType;
7702     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7703     return resultType;
7704   }
7705
7706   // Okay, the expression is invalid.
7707
7708   // If there's a non-vector, non-real operand, diagnose that.
7709   if ((!RHSVecType && !RHSType->isRealType()) ||
7710       (!LHSVecType && !LHSType->isRealType())) {
7711     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7712       << LHSType << RHSType
7713       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7714     return QualType();
7715   }
7716
7717   // OpenCL V1.1 6.2.6.p1:
7718   // If the operands are of more than one vector type, then an error shall
7719   // occur. Implicit conversions between vector types are not permitted, per
7720   // section 6.2.1.
7721   if (getLangOpts().OpenCL &&
7722       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7723       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7724     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7725                                                            << RHSType;
7726     return QualType();
7727   }
7728
7729   // Otherwise, use the generic diagnostic.
7730   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7731     << LHSType << RHSType
7732     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7733   return QualType();
7734 }
7735
7736 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7737 // expression.  These are mainly cases where the null pointer is used as an
7738 // integer instead of a pointer.
7739 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7740                                 SourceLocation Loc, bool IsCompare) {
7741   // The canonical way to check for a GNU null is with isNullPointerConstant,
7742   // but we use a bit of a hack here for speed; this is a relatively
7743   // hot path, and isNullPointerConstant is slow.
7744   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7745   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7746
7747   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7748
7749   // Avoid analyzing cases where the result will either be invalid (and
7750   // diagnosed as such) or entirely valid and not something to warn about.
7751   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7752       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7753     return;
7754
7755   // Comparison operations would not make sense with a null pointer no matter
7756   // what the other expression is.
7757   if (!IsCompare) {
7758     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7759         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7760         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7761     return;
7762   }
7763
7764   // The rest of the operations only make sense with a null pointer
7765   // if the other expression is a pointer.
7766   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7767       NonNullType->canDecayToPointerType())
7768     return;
7769
7770   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7771       << LHSNull /* LHS is NULL */ << NonNullType
7772       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7773 }
7774
7775 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
7776                                                ExprResult &RHS,
7777                                                SourceLocation Loc, bool IsDiv) {
7778   // Check for division/remainder by zero.
7779   llvm::APSInt RHSValue;
7780   if (!RHS.get()->isValueDependent() &&
7781       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
7782     S.DiagRuntimeBehavior(Loc, RHS.get(),
7783                           S.PDiag(diag::warn_remainder_division_by_zero)
7784                             << IsDiv << RHS.get()->getSourceRange());
7785 }
7786
7787 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7788                                            SourceLocation Loc,
7789                                            bool IsCompAssign, bool IsDiv) {
7790   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7791
7792   if (LHS.get()->getType()->isVectorType() ||
7793       RHS.get()->getType()->isVectorType())
7794     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7795                                /*AllowBothBool*/getLangOpts().AltiVec,
7796                                /*AllowBoolConversions*/false);
7797
7798   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7799   if (LHS.isInvalid() || RHS.isInvalid())
7800     return QualType();
7801
7802
7803   if (compType.isNull() || !compType->isArithmeticType())
7804     return InvalidOperands(Loc, LHS, RHS);
7805   if (IsDiv)
7806     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
7807   return compType;
7808 }
7809
7810 QualType Sema::CheckRemainderOperands(
7811   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7812   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7813
7814   if (LHS.get()->getType()->isVectorType() ||
7815       RHS.get()->getType()->isVectorType()) {
7816     if (LHS.get()->getType()->hasIntegerRepresentation() && 
7817         RHS.get()->getType()->hasIntegerRepresentation())
7818       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7819                                  /*AllowBothBool*/getLangOpts().AltiVec,
7820                                  /*AllowBoolConversions*/false);
7821     return InvalidOperands(Loc, LHS, RHS);
7822   }
7823
7824   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7825   if (LHS.isInvalid() || RHS.isInvalid())
7826     return QualType();
7827
7828   if (compType.isNull() || !compType->isIntegerType())
7829     return InvalidOperands(Loc, LHS, RHS);
7830   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
7831   return compType;
7832 }
7833
7834 /// \brief Diagnose invalid arithmetic on two void pointers.
7835 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7836                                                 Expr *LHSExpr, Expr *RHSExpr) {
7837   S.Diag(Loc, S.getLangOpts().CPlusPlus
7838                 ? diag::err_typecheck_pointer_arith_void_type
7839                 : diag::ext_gnu_void_ptr)
7840     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7841                             << RHSExpr->getSourceRange();
7842 }
7843
7844 /// \brief Diagnose invalid arithmetic on a void pointer.
7845 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7846                                             Expr *Pointer) {
7847   S.Diag(Loc, S.getLangOpts().CPlusPlus
7848                 ? diag::err_typecheck_pointer_arith_void_type
7849                 : diag::ext_gnu_void_ptr)
7850     << 0 /* one pointer */ << Pointer->getSourceRange();
7851 }
7852
7853 /// \brief Diagnose invalid arithmetic on two function pointers.
7854 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7855                                                     Expr *LHS, Expr *RHS) {
7856   assert(LHS->getType()->isAnyPointerType());
7857   assert(RHS->getType()->isAnyPointerType());
7858   S.Diag(Loc, S.getLangOpts().CPlusPlus
7859                 ? diag::err_typecheck_pointer_arith_function_type
7860                 : diag::ext_gnu_ptr_func_arith)
7861     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7862     // We only show the second type if it differs from the first.
7863     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7864                                                    RHS->getType())
7865     << RHS->getType()->getPointeeType()
7866     << LHS->getSourceRange() << RHS->getSourceRange();
7867 }
7868
7869 /// \brief Diagnose invalid arithmetic on a function pointer.
7870 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7871                                                 Expr *Pointer) {
7872   assert(Pointer->getType()->isAnyPointerType());
7873   S.Diag(Loc, S.getLangOpts().CPlusPlus
7874                 ? diag::err_typecheck_pointer_arith_function_type
7875                 : diag::ext_gnu_ptr_func_arith)
7876     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7877     << 0 /* one pointer, so only one type */
7878     << Pointer->getSourceRange();
7879 }
7880
7881 /// \brief Emit error if Operand is incomplete pointer type
7882 ///
7883 /// \returns True if pointer has incomplete type
7884 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7885                                                  Expr *Operand) {
7886   QualType ResType = Operand->getType();
7887   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7888     ResType = ResAtomicType->getValueType();
7889
7890   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7891   QualType PointeeTy = ResType->getPointeeType();
7892   return S.RequireCompleteType(Loc, PointeeTy,
7893                                diag::err_typecheck_arithmetic_incomplete_type,
7894                                PointeeTy, Operand->getSourceRange());
7895 }
7896
7897 /// \brief Check the validity of an arithmetic pointer operand.
7898 ///
7899 /// If the operand has pointer type, this code will check for pointer types
7900 /// which are invalid in arithmetic operations. These will be diagnosed
7901 /// appropriately, including whether or not the use is supported as an
7902 /// extension.
7903 ///
7904 /// \returns True when the operand is valid to use (even if as an extension).
7905 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7906                                             Expr *Operand) {
7907   QualType ResType = Operand->getType();
7908   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7909     ResType = ResAtomicType->getValueType();
7910
7911   if (!ResType->isAnyPointerType()) return true;
7912
7913   QualType PointeeTy = ResType->getPointeeType();
7914   if (PointeeTy->isVoidType()) {
7915     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7916     return !S.getLangOpts().CPlusPlus;
7917   }
7918   if (PointeeTy->isFunctionType()) {
7919     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7920     return !S.getLangOpts().CPlusPlus;
7921   }
7922
7923   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7924
7925   return true;
7926 }
7927
7928 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7929 /// operands.
7930 ///
7931 /// This routine will diagnose any invalid arithmetic on pointer operands much
7932 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7933 /// for emitting a single diagnostic even for operations where both LHS and RHS
7934 /// are (potentially problematic) pointers.
7935 ///
7936 /// \returns True when the operand is valid to use (even if as an extension).
7937 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7938                                                 Expr *LHSExpr, Expr *RHSExpr) {
7939   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7940   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7941   if (!isLHSPointer && !isRHSPointer) return true;
7942
7943   QualType LHSPointeeTy, RHSPointeeTy;
7944   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7945   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7946
7947   // if both are pointers check if operation is valid wrt address spaces
7948   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
7949     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7950     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7951     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7952       S.Diag(Loc,
7953              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7954           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7955           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7956       return false;
7957     }
7958   }
7959
7960   // Check for arithmetic on pointers to incomplete types.
7961   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7962   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7963   if (isLHSVoidPtr || isRHSVoidPtr) {
7964     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7965     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7966     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7967
7968     return !S.getLangOpts().CPlusPlus;
7969   }
7970
7971   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7972   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7973   if (isLHSFuncPtr || isRHSFuncPtr) {
7974     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7975     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7976                                                                 RHSExpr);
7977     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7978
7979     return !S.getLangOpts().CPlusPlus;
7980   }
7981
7982   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7983     return false;
7984   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7985     return false;
7986
7987   return true;
7988 }
7989
7990 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7991 /// literal.
7992 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7993                                   Expr *LHSExpr, Expr *RHSExpr) {
7994   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7995   Expr* IndexExpr = RHSExpr;
7996   if (!StrExpr) {
7997     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7998     IndexExpr = LHSExpr;
7999   }
8000
8001   bool IsStringPlusInt = StrExpr &&
8002       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8003   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8004     return;
8005
8006   llvm::APSInt index;
8007   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8008     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8009     if (index.isNonNegative() &&
8010         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8011                               index.isUnsigned()))
8012       return;
8013   }
8014
8015   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8016   Self.Diag(OpLoc, diag::warn_string_plus_int)
8017       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8018
8019   // Only print a fixit for "str" + int, not for int + "str".
8020   if (IndexExpr == RHSExpr) {
8021     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8022     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8023         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8024         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8025         << FixItHint::CreateInsertion(EndLoc, "]");
8026   } else
8027     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8028 }
8029
8030 /// \brief Emit a warning when adding a char literal to a string.
8031 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8032                                    Expr *LHSExpr, Expr *RHSExpr) {
8033   const Expr *StringRefExpr = LHSExpr;
8034   const CharacterLiteral *CharExpr =
8035       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8036
8037   if (!CharExpr) {
8038     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8039     StringRefExpr = RHSExpr;
8040   }
8041
8042   if (!CharExpr || !StringRefExpr)
8043     return;
8044
8045   const QualType StringType = StringRefExpr->getType();
8046
8047   // Return if not a PointerType.
8048   if (!StringType->isAnyPointerType())
8049     return;
8050
8051   // Return if not a CharacterType.
8052   if (!StringType->getPointeeType()->isAnyCharacterType())
8053     return;
8054
8055   ASTContext &Ctx = Self.getASTContext();
8056   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8057
8058   const QualType CharType = CharExpr->getType();
8059   if (!CharType->isAnyCharacterType() &&
8060       CharType->isIntegerType() &&
8061       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8062     Self.Diag(OpLoc, diag::warn_string_plus_char)
8063         << DiagRange << Ctx.CharTy;
8064   } else {
8065     Self.Diag(OpLoc, diag::warn_string_plus_char)
8066         << DiagRange << CharExpr->getType();
8067   }
8068
8069   // Only print a fixit for str + char, not for char + str.
8070   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8071     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8072     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8073         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8074         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8075         << FixItHint::CreateInsertion(EndLoc, "]");
8076   } else {
8077     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8078   }
8079 }
8080
8081 /// \brief Emit error when two pointers are incompatible.
8082 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8083                                            Expr *LHSExpr, Expr *RHSExpr) {
8084   assert(LHSExpr->getType()->isAnyPointerType());
8085   assert(RHSExpr->getType()->isAnyPointerType());
8086   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8087     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8088     << RHSExpr->getSourceRange();
8089 }
8090
8091 // C99 6.5.6
8092 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8093                                      SourceLocation Loc, BinaryOperatorKind Opc,
8094                                      QualType* CompLHSTy) {
8095   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8096
8097   if (LHS.get()->getType()->isVectorType() ||
8098       RHS.get()->getType()->isVectorType()) {
8099     QualType compType = CheckVectorOperands(
8100         LHS, RHS, Loc, CompLHSTy,
8101         /*AllowBothBool*/getLangOpts().AltiVec,
8102         /*AllowBoolConversions*/getLangOpts().ZVector);
8103     if (CompLHSTy) *CompLHSTy = compType;
8104     return compType;
8105   }
8106
8107   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8108   if (LHS.isInvalid() || RHS.isInvalid())
8109     return QualType();
8110
8111   // Diagnose "string literal" '+' int and string '+' "char literal".
8112   if (Opc == BO_Add) {
8113     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8114     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8115   }
8116
8117   // handle the common case first (both operands are arithmetic).
8118   if (!compType.isNull() && compType->isArithmeticType()) {
8119     if (CompLHSTy) *CompLHSTy = compType;
8120     return compType;
8121   }
8122
8123   // Type-checking.  Ultimately the pointer's going to be in PExp;
8124   // note that we bias towards the LHS being the pointer.
8125   Expr *PExp = LHS.get(), *IExp = RHS.get();
8126
8127   bool isObjCPointer;
8128   if (PExp->getType()->isPointerType()) {
8129     isObjCPointer = false;
8130   } else if (PExp->getType()->isObjCObjectPointerType()) {
8131     isObjCPointer = true;
8132   } else {
8133     std::swap(PExp, IExp);
8134     if (PExp->getType()->isPointerType()) {
8135       isObjCPointer = false;
8136     } else if (PExp->getType()->isObjCObjectPointerType()) {
8137       isObjCPointer = true;
8138     } else {
8139       return InvalidOperands(Loc, LHS, RHS);
8140     }
8141   }
8142   assert(PExp->getType()->isAnyPointerType());
8143
8144   if (!IExp->getType()->isIntegerType())
8145     return InvalidOperands(Loc, LHS, RHS);
8146
8147   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8148     return QualType();
8149
8150   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8151     return QualType();
8152
8153   // Check array bounds for pointer arithemtic
8154   CheckArrayAccess(PExp, IExp);
8155
8156   if (CompLHSTy) {
8157     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8158     if (LHSTy.isNull()) {
8159       LHSTy = LHS.get()->getType();
8160       if (LHSTy->isPromotableIntegerType())
8161         LHSTy = Context.getPromotedIntegerType(LHSTy);
8162     }
8163     *CompLHSTy = LHSTy;
8164   }
8165
8166   return PExp->getType();
8167 }
8168
8169 // C99 6.5.6
8170 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8171                                         SourceLocation Loc,
8172                                         QualType* CompLHSTy) {
8173   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8174
8175   if (LHS.get()->getType()->isVectorType() ||
8176       RHS.get()->getType()->isVectorType()) {
8177     QualType compType = CheckVectorOperands(
8178         LHS, RHS, Loc, CompLHSTy,
8179         /*AllowBothBool*/getLangOpts().AltiVec,
8180         /*AllowBoolConversions*/getLangOpts().ZVector);
8181     if (CompLHSTy) *CompLHSTy = compType;
8182     return compType;
8183   }
8184
8185   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8186   if (LHS.isInvalid() || RHS.isInvalid())
8187     return QualType();
8188
8189   // Enforce type constraints: C99 6.5.6p3.
8190
8191   // Handle the common case first (both operands are arithmetic).
8192   if (!compType.isNull() && compType->isArithmeticType()) {
8193     if (CompLHSTy) *CompLHSTy = compType;
8194     return compType;
8195   }
8196
8197   // Either ptr - int   or   ptr - ptr.
8198   if (LHS.get()->getType()->isAnyPointerType()) {
8199     QualType lpointee = LHS.get()->getType()->getPointeeType();
8200
8201     // Diagnose bad cases where we step over interface counts.
8202     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8203         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8204       return QualType();
8205
8206     // The result type of a pointer-int computation is the pointer type.
8207     if (RHS.get()->getType()->isIntegerType()) {
8208       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8209         return QualType();
8210
8211       // Check array bounds for pointer arithemtic
8212       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8213                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8214
8215       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8216       return LHS.get()->getType();
8217     }
8218
8219     // Handle pointer-pointer subtractions.
8220     if (const PointerType *RHSPTy
8221           = RHS.get()->getType()->getAs<PointerType>()) {
8222       QualType rpointee = RHSPTy->getPointeeType();
8223
8224       if (getLangOpts().CPlusPlus) {
8225         // Pointee types must be the same: C++ [expr.add]
8226         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8227           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8228         }
8229       } else {
8230         // Pointee types must be compatible C99 6.5.6p3
8231         if (!Context.typesAreCompatible(
8232                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8233                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8234           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8235           return QualType();
8236         }
8237       }
8238
8239       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8240                                                LHS.get(), RHS.get()))
8241         return QualType();
8242
8243       // The pointee type may have zero size.  As an extension, a structure or
8244       // union may have zero size or an array may have zero length.  In this
8245       // case subtraction does not make sense.
8246       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8247         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8248         if (ElementSize.isZero()) {
8249           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8250             << rpointee.getUnqualifiedType()
8251             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8252         }
8253       }
8254
8255       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8256       return Context.getPointerDiffType();
8257     }
8258   }
8259
8260   return InvalidOperands(Loc, LHS, RHS);
8261 }
8262
8263 static bool isScopedEnumerationType(QualType T) {
8264   if (const EnumType *ET = T->getAs<EnumType>())
8265     return ET->getDecl()->isScoped();
8266   return false;
8267 }
8268
8269 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8270                                    SourceLocation Loc, BinaryOperatorKind Opc,
8271                                    QualType LHSType) {
8272   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8273   // so skip remaining warnings as we don't want to modify values within Sema.
8274   if (S.getLangOpts().OpenCL)
8275     return;
8276
8277   llvm::APSInt Right;
8278   // Check right/shifter operand
8279   if (RHS.get()->isValueDependent() ||
8280       !RHS.get()->EvaluateAsInt(Right, S.Context))
8281     return;
8282
8283   if (Right.isNegative()) {
8284     S.DiagRuntimeBehavior(Loc, RHS.get(),
8285                           S.PDiag(diag::warn_shift_negative)
8286                             << RHS.get()->getSourceRange());
8287     return;
8288   }
8289   llvm::APInt LeftBits(Right.getBitWidth(),
8290                        S.Context.getTypeSize(LHS.get()->getType()));
8291   if (Right.uge(LeftBits)) {
8292     S.DiagRuntimeBehavior(Loc, RHS.get(),
8293                           S.PDiag(diag::warn_shift_gt_typewidth)
8294                             << RHS.get()->getSourceRange());
8295     return;
8296   }
8297   if (Opc != BO_Shl)
8298     return;
8299
8300   // When left shifting an ICE which is signed, we can check for overflow which
8301   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8302   // integers have defined behavior modulo one more than the maximum value
8303   // representable in the result type, so never warn for those.
8304   llvm::APSInt Left;
8305   if (LHS.get()->isValueDependent() ||
8306       LHSType->hasUnsignedIntegerRepresentation() ||
8307       !LHS.get()->EvaluateAsInt(Left, S.Context))
8308     return;
8309
8310   // If LHS does not have a signed type and non-negative value
8311   // then, the behavior is undefined. Warn about it.
8312   if (Left.isNegative()) {
8313     S.DiagRuntimeBehavior(Loc, LHS.get(),
8314                           S.PDiag(diag::warn_shift_lhs_negative)
8315                             << LHS.get()->getSourceRange());
8316     return;
8317   }
8318
8319   llvm::APInt ResultBits =
8320       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8321   if (LeftBits.uge(ResultBits))
8322     return;
8323   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8324   Result = Result.shl(Right);
8325
8326   // Print the bit representation of the signed integer as an unsigned
8327   // hexadecimal number.
8328   SmallString<40> HexResult;
8329   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8330
8331   // If we are only missing a sign bit, this is less likely to result in actual
8332   // bugs -- if the result is cast back to an unsigned type, it will have the
8333   // expected value. Thus we place this behind a different warning that can be
8334   // turned off separately if needed.
8335   if (LeftBits == ResultBits - 1) {
8336     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8337         << HexResult << LHSType
8338         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8339     return;
8340   }
8341
8342   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8343     << HexResult.str() << Result.getMinSignedBits() << LHSType
8344     << Left.getBitWidth() << LHS.get()->getSourceRange()
8345     << RHS.get()->getSourceRange();
8346 }
8347
8348 /// \brief Return the resulting type when an OpenCL vector is shifted
8349 ///        by a scalar or vector shift amount.
8350 static QualType checkOpenCLVectorShift(Sema &S,
8351                                        ExprResult &LHS, ExprResult &RHS,
8352                                        SourceLocation Loc, bool IsCompAssign) {
8353   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8354   if (!LHS.get()->getType()->isVectorType()) {
8355     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8356       << RHS.get()->getType() << LHS.get()->getType()
8357       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8358     return QualType();
8359   }
8360
8361   if (!IsCompAssign) {
8362     LHS = S.UsualUnaryConversions(LHS.get());
8363     if (LHS.isInvalid()) return QualType();
8364   }
8365
8366   RHS = S.UsualUnaryConversions(RHS.get());
8367   if (RHS.isInvalid()) return QualType();
8368
8369   QualType LHSType = LHS.get()->getType();
8370   const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8371   QualType LHSEleType = LHSVecTy->getElementType();
8372
8373   // Note that RHS might not be a vector.
8374   QualType RHSType = RHS.get()->getType();
8375   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8376   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8377
8378   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8379   if (!LHSEleType->isIntegerType()) {
8380     S.Diag(Loc, diag::err_typecheck_expect_int)
8381       << LHS.get()->getType() << LHS.get()->getSourceRange();
8382     return QualType();
8383   }
8384
8385   if (!RHSEleType->isIntegerType()) {
8386     S.Diag(Loc, diag::err_typecheck_expect_int)
8387       << RHS.get()->getType() << RHS.get()->getSourceRange();
8388     return QualType();
8389   }
8390
8391   if (RHSVecTy) {
8392     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8393     // are applied component-wise. So if RHS is a vector, then ensure
8394     // that the number of elements is the same as LHS...
8395     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8396       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8397         << LHS.get()->getType() << RHS.get()->getType()
8398         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8399       return QualType();
8400     }
8401   } else {
8402     // ...else expand RHS to match the number of elements in LHS.
8403     QualType VecTy =
8404       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8405     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8406   }
8407
8408   return LHSType;
8409 }
8410
8411 // C99 6.5.7
8412 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8413                                   SourceLocation Loc, BinaryOperatorKind Opc,
8414                                   bool IsCompAssign) {
8415   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8416
8417   // Vector shifts promote their scalar inputs to vector type.
8418   if (LHS.get()->getType()->isVectorType() ||
8419       RHS.get()->getType()->isVectorType()) {
8420     if (LangOpts.OpenCL)
8421       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8422     if (LangOpts.ZVector) {
8423       // The shift operators for the z vector extensions work basically
8424       // like OpenCL shifts, except that neither the LHS nor the RHS is
8425       // allowed to be a "vector bool".
8426       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8427         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8428           return InvalidOperands(Loc, LHS, RHS);
8429       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8430         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8431           return InvalidOperands(Loc, LHS, RHS);
8432       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8433     }
8434     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8435                                /*AllowBothBool*/true,
8436                                /*AllowBoolConversions*/false);
8437   }
8438
8439   // Shifts don't perform usual arithmetic conversions, they just do integer
8440   // promotions on each operand. C99 6.5.7p3
8441
8442   // For the LHS, do usual unary conversions, but then reset them away
8443   // if this is a compound assignment.
8444   ExprResult OldLHS = LHS;
8445   LHS = UsualUnaryConversions(LHS.get());
8446   if (LHS.isInvalid())
8447     return QualType();
8448   QualType LHSType = LHS.get()->getType();
8449   if (IsCompAssign) LHS = OldLHS;
8450
8451   // The RHS is simpler.
8452   RHS = UsualUnaryConversions(RHS.get());
8453   if (RHS.isInvalid())
8454     return QualType();
8455   QualType RHSType = RHS.get()->getType();
8456
8457   // C99 6.5.7p2: Each of the operands shall have integer type.
8458   if (!LHSType->hasIntegerRepresentation() ||
8459       !RHSType->hasIntegerRepresentation())
8460     return InvalidOperands(Loc, LHS, RHS);
8461
8462   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8463   // hasIntegerRepresentation() above instead of this.
8464   if (isScopedEnumerationType(LHSType) ||
8465       isScopedEnumerationType(RHSType)) {
8466     return InvalidOperands(Loc, LHS, RHS);
8467   }
8468   // Sanity-check shift operands
8469   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8470
8471   // "The type of the result is that of the promoted left operand."
8472   return LHSType;
8473 }
8474
8475 static bool IsWithinTemplateSpecialization(Decl *D) {
8476   if (DeclContext *DC = D->getDeclContext()) {
8477     if (isa<ClassTemplateSpecializationDecl>(DC))
8478       return true;
8479     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8480       return FD->isFunctionTemplateSpecialization();
8481   }
8482   return false;
8483 }
8484
8485 /// If two different enums are compared, raise a warning.
8486 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8487                                 Expr *RHS) {
8488   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8489   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8490
8491   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8492   if (!LHSEnumType)
8493     return;
8494   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8495   if (!RHSEnumType)
8496     return;
8497
8498   // Ignore anonymous enums.
8499   if (!LHSEnumType->getDecl()->getIdentifier())
8500     return;
8501   if (!RHSEnumType->getDecl()->getIdentifier())
8502     return;
8503
8504   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8505     return;
8506
8507   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8508       << LHSStrippedType << RHSStrippedType
8509       << LHS->getSourceRange() << RHS->getSourceRange();
8510 }
8511
8512 /// \brief Diagnose bad pointer comparisons.
8513 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8514                                               ExprResult &LHS, ExprResult &RHS,
8515                                               bool IsError) {
8516   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8517                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8518     << LHS.get()->getType() << RHS.get()->getType()
8519     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8520 }
8521
8522 /// \brief Returns false if the pointers are converted to a composite type,
8523 /// true otherwise.
8524 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8525                                            ExprResult &LHS, ExprResult &RHS) {
8526   // C++ [expr.rel]p2:
8527   //   [...] Pointer conversions (4.10) and qualification
8528   //   conversions (4.4) are performed on pointer operands (or on
8529   //   a pointer operand and a null pointer constant) to bring
8530   //   them to their composite pointer type. [...]
8531   //
8532   // C++ [expr.eq]p1 uses the same notion for (in)equality
8533   // comparisons of pointers.
8534
8535   // C++ [expr.eq]p2:
8536   //   In addition, pointers to members can be compared, or a pointer to
8537   //   member and a null pointer constant. Pointer to member conversions
8538   //   (4.11) and qualification conversions (4.4) are performed to bring
8539   //   them to a common type. If one operand is a null pointer constant,
8540   //   the common type is the type of the other operand. Otherwise, the
8541   //   common type is a pointer to member type similar (4.4) to the type
8542   //   of one of the operands, with a cv-qualification signature (4.4)
8543   //   that is the union of the cv-qualification signatures of the operand
8544   //   types.
8545
8546   QualType LHSType = LHS.get()->getType();
8547   QualType RHSType = RHS.get()->getType();
8548   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8549          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8550
8551   bool NonStandardCompositeType = false;
8552   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8553   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8554   if (T.isNull()) {
8555     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8556     return true;
8557   }
8558
8559   if (NonStandardCompositeType)
8560     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8561       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8562       << RHS.get()->getSourceRange();
8563
8564   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8565   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8566   return false;
8567 }
8568
8569 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8570                                                     ExprResult &LHS,
8571                                                     ExprResult &RHS,
8572                                                     bool IsError) {
8573   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8574                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8575     << LHS.get()->getType() << RHS.get()->getType()
8576     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8577 }
8578
8579 static bool isObjCObjectLiteral(ExprResult &E) {
8580   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8581   case Stmt::ObjCArrayLiteralClass:
8582   case Stmt::ObjCDictionaryLiteralClass:
8583   case Stmt::ObjCStringLiteralClass:
8584   case Stmt::ObjCBoxedExprClass:
8585     return true;
8586   default:
8587     // Note that ObjCBoolLiteral is NOT an object literal!
8588     return false;
8589   }
8590 }
8591
8592 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8593   const ObjCObjectPointerType *Type =
8594     LHS->getType()->getAs<ObjCObjectPointerType>();
8595
8596   // If this is not actually an Objective-C object, bail out.
8597   if (!Type)
8598     return false;
8599
8600   // Get the LHS object's interface type.
8601   QualType InterfaceType = Type->getPointeeType();
8602
8603   // If the RHS isn't an Objective-C object, bail out.
8604   if (!RHS->getType()->isObjCObjectPointerType())
8605     return false;
8606
8607   // Try to find the -isEqual: method.
8608   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8609   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8610                                                       InterfaceType,
8611                                                       /*instance=*/true);
8612   if (!Method) {
8613     if (Type->isObjCIdType()) {
8614       // For 'id', just check the global pool.
8615       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8616                                                   /*receiverId=*/true);
8617     } else {
8618       // Check protocols.
8619       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8620                                              /*instance=*/true);
8621     }
8622   }
8623
8624   if (!Method)
8625     return false;
8626
8627   QualType T = Method->parameters()[0]->getType();
8628   if (!T->isObjCObjectPointerType())
8629     return false;
8630
8631   QualType R = Method->getReturnType();
8632   if (!R->isScalarType())
8633     return false;
8634
8635   return true;
8636 }
8637
8638 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8639   FromE = FromE->IgnoreParenImpCasts();
8640   switch (FromE->getStmtClass()) {
8641     default:
8642       break;
8643     case Stmt::ObjCStringLiteralClass:
8644       // "string literal"
8645       return LK_String;
8646     case Stmt::ObjCArrayLiteralClass:
8647       // "array literal"
8648       return LK_Array;
8649     case Stmt::ObjCDictionaryLiteralClass:
8650       // "dictionary literal"
8651       return LK_Dictionary;
8652     case Stmt::BlockExprClass:
8653       return LK_Block;
8654     case Stmt::ObjCBoxedExprClass: {
8655       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8656       switch (Inner->getStmtClass()) {
8657         case Stmt::IntegerLiteralClass:
8658         case Stmt::FloatingLiteralClass:
8659         case Stmt::CharacterLiteralClass:
8660         case Stmt::ObjCBoolLiteralExprClass:
8661         case Stmt::CXXBoolLiteralExprClass:
8662           // "numeric literal"
8663           return LK_Numeric;
8664         case Stmt::ImplicitCastExprClass: {
8665           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8666           // Boolean literals can be represented by implicit casts.
8667           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8668             return LK_Numeric;
8669           break;
8670         }
8671         default:
8672           break;
8673       }
8674       return LK_Boxed;
8675     }
8676   }
8677   return LK_None;
8678 }
8679
8680 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8681                                           ExprResult &LHS, ExprResult &RHS,
8682                                           BinaryOperator::Opcode Opc){
8683   Expr *Literal;
8684   Expr *Other;
8685   if (isObjCObjectLiteral(LHS)) {
8686     Literal = LHS.get();
8687     Other = RHS.get();
8688   } else {
8689     Literal = RHS.get();
8690     Other = LHS.get();
8691   }
8692
8693   // Don't warn on comparisons against nil.
8694   Other = Other->IgnoreParenCasts();
8695   if (Other->isNullPointerConstant(S.getASTContext(),
8696                                    Expr::NPC_ValueDependentIsNotNull))
8697     return;
8698
8699   // This should be kept in sync with warn_objc_literal_comparison.
8700   // LK_String should always be after the other literals, since it has its own
8701   // warning flag.
8702   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8703   assert(LiteralKind != Sema::LK_Block);
8704   if (LiteralKind == Sema::LK_None) {
8705     llvm_unreachable("Unknown Objective-C object literal kind");
8706   }
8707
8708   if (LiteralKind == Sema::LK_String)
8709     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8710       << Literal->getSourceRange();
8711   else
8712     S.Diag(Loc, diag::warn_objc_literal_comparison)
8713       << LiteralKind << Literal->getSourceRange();
8714
8715   if (BinaryOperator::isEqualityOp(Opc) &&
8716       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8717     SourceLocation Start = LHS.get()->getLocStart();
8718     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8719     CharSourceRange OpRange =
8720       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8721
8722     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8723       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8724       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8725       << FixItHint::CreateInsertion(End, "]");
8726   }
8727 }
8728
8729 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8730                                                 ExprResult &RHS,
8731                                                 SourceLocation Loc,
8732                                                 BinaryOperatorKind Opc) {
8733   // Check that left hand side is !something.
8734   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8735   if (!UO || UO->getOpcode() != UO_LNot) return;
8736
8737   // Only check if the right hand side is non-bool arithmetic type.
8738   if (RHS.get()->isKnownToHaveBooleanValue()) return;
8739
8740   // Make sure that the something in !something is not bool.
8741   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8742   if (SubExpr->isKnownToHaveBooleanValue()) return;
8743
8744   // Emit warning.
8745   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8746       << Loc;
8747
8748   // First note suggest !(x < y)
8749   SourceLocation FirstOpen = SubExpr->getLocStart();
8750   SourceLocation FirstClose = RHS.get()->getLocEnd();
8751   FirstClose = S.getLocForEndOfToken(FirstClose);
8752   if (FirstClose.isInvalid())
8753     FirstOpen = SourceLocation();
8754   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8755       << FixItHint::CreateInsertion(FirstOpen, "(")
8756       << FixItHint::CreateInsertion(FirstClose, ")");
8757
8758   // Second note suggests (!x) < y
8759   SourceLocation SecondOpen = LHS.get()->getLocStart();
8760   SourceLocation SecondClose = LHS.get()->getLocEnd();
8761   SecondClose = S.getLocForEndOfToken(SecondClose);
8762   if (SecondClose.isInvalid())
8763     SecondOpen = SourceLocation();
8764   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8765       << FixItHint::CreateInsertion(SecondOpen, "(")
8766       << FixItHint::CreateInsertion(SecondClose, ")");
8767 }
8768
8769 // Get the decl for a simple expression: a reference to a variable,
8770 // an implicit C++ field reference, or an implicit ObjC ivar reference.
8771 static ValueDecl *getCompareDecl(Expr *E) {
8772   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8773     return DR->getDecl();
8774   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8775     if (Ivar->isFreeIvar())
8776       return Ivar->getDecl();
8777   }
8778   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8779     if (Mem->isImplicitAccess())
8780       return Mem->getMemberDecl();
8781   }
8782   return nullptr;
8783 }
8784
8785 // C99 6.5.8, C++ [expr.rel]
8786 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
8787                                     SourceLocation Loc, BinaryOperatorKind Opc,
8788                                     bool IsRelational) {
8789   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8790
8791   // Handle vector comparisons separately.
8792   if (LHS.get()->getType()->isVectorType() ||
8793       RHS.get()->getType()->isVectorType())
8794     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
8795
8796   QualType LHSType = LHS.get()->getType();
8797   QualType RHSType = RHS.get()->getType();
8798
8799   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8800   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
8801
8802   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
8803   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
8804
8805   if (!LHSType->hasFloatingRepresentation() &&
8806       !(LHSType->isBlockPointerType() && IsRelational) &&
8807       !LHS.get()->getLocStart().isMacroID() &&
8808       !RHS.get()->getLocStart().isMacroID() &&
8809       ActiveTemplateInstantiations.empty()) {
8810     // For non-floating point types, check for self-comparisons of the form
8811     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8812     // often indicate logic errors in the program.
8813     //
8814     // NOTE: Don't warn about comparison expressions resulting from macro
8815     // expansion. Also don't warn about comparisons which are only self
8816     // comparisons within a template specialization. The warnings should catch
8817     // obvious cases in the definition of the template anyways. The idea is to
8818     // warn when the typed comparison operator will always evaluate to the same
8819     // result.
8820     ValueDecl *DL = getCompareDecl(LHSStripped);
8821     ValueDecl *DR = getCompareDecl(RHSStripped);
8822     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8823       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8824                           << 0 // self-
8825                           << (Opc == BO_EQ
8826                               || Opc == BO_LE
8827                               || Opc == BO_GE));
8828     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8829                !DL->getType()->isReferenceType() &&
8830                !DR->getType()->isReferenceType()) {
8831         // what is it always going to eval to?
8832         char always_evals_to;
8833         switch(Opc) {
8834         case BO_EQ: // e.g. array1 == array2
8835           always_evals_to = 0; // false
8836           break;
8837         case BO_NE: // e.g. array1 != array2
8838           always_evals_to = 1; // true
8839           break;
8840         default:
8841           // best we can say is 'a constant'
8842           always_evals_to = 2; // e.g. array1 <= array2
8843           break;
8844         }
8845         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8846                             << 1 // array
8847                             << always_evals_to);
8848     }
8849
8850     if (isa<CastExpr>(LHSStripped))
8851       LHSStripped = LHSStripped->IgnoreParenCasts();
8852     if (isa<CastExpr>(RHSStripped))
8853       RHSStripped = RHSStripped->IgnoreParenCasts();
8854
8855     // Warn about comparisons against a string constant (unless the other
8856     // operand is null), the user probably wants strcmp.
8857     Expr *literalString = nullptr;
8858     Expr *literalStringStripped = nullptr;
8859     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8860         !RHSStripped->isNullPointerConstant(Context,
8861                                             Expr::NPC_ValueDependentIsNull)) {
8862       literalString = LHS.get();
8863       literalStringStripped = LHSStripped;
8864     } else if ((isa<StringLiteral>(RHSStripped) ||
8865                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8866                !LHSStripped->isNullPointerConstant(Context,
8867                                             Expr::NPC_ValueDependentIsNull)) {
8868       literalString = RHS.get();
8869       literalStringStripped = RHSStripped;
8870     }
8871
8872     if (literalString) {
8873       DiagRuntimeBehavior(Loc, nullptr,
8874         PDiag(diag::warn_stringcompare)
8875           << isa<ObjCEncodeExpr>(literalStringStripped)
8876           << literalString->getSourceRange());
8877     }
8878   }
8879
8880   // C99 6.5.8p3 / C99 6.5.9p4
8881   UsualArithmeticConversions(LHS, RHS);
8882   if (LHS.isInvalid() || RHS.isInvalid())
8883     return QualType();
8884
8885   LHSType = LHS.get()->getType();
8886   RHSType = RHS.get()->getType();
8887
8888   // The result of comparisons is 'bool' in C++, 'int' in C.
8889   QualType ResultTy = Context.getLogicalOperationType();
8890
8891   if (IsRelational) {
8892     if (LHSType->isRealType() && RHSType->isRealType())
8893       return ResultTy;
8894   } else {
8895     // Check for comparisons of floating point operands using != and ==.
8896     if (LHSType->hasFloatingRepresentation())
8897       CheckFloatComparison(Loc, LHS.get(), RHS.get());
8898
8899     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8900       return ResultTy;
8901   }
8902
8903   const Expr::NullPointerConstantKind LHSNullKind =
8904       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8905   const Expr::NullPointerConstantKind RHSNullKind =
8906       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8907   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8908   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8909
8910   if (!IsRelational && LHSIsNull != RHSIsNull) {
8911     bool IsEquality = Opc == BO_EQ;
8912     if (RHSIsNull)
8913       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8914                                    RHS.get()->getSourceRange());
8915     else
8916       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8917                                    LHS.get()->getSourceRange());
8918   }
8919
8920   // All of the following pointer-related warnings are GCC extensions, except
8921   // when handling null pointer constants. 
8922   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8923     QualType LCanPointeeTy =
8924       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8925     QualType RCanPointeeTy =
8926       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8927
8928     if (getLangOpts().CPlusPlus) {
8929       if (LCanPointeeTy == RCanPointeeTy)
8930         return ResultTy;
8931       if (!IsRelational &&
8932           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8933         // Valid unless comparison between non-null pointer and function pointer
8934         // This is a gcc extension compatibility comparison.
8935         // In a SFINAE context, we treat this as a hard error to maintain
8936         // conformance with the C++ standard.
8937         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8938             && !LHSIsNull && !RHSIsNull) {
8939           diagnoseFunctionPointerToVoidComparison(
8940               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8941           
8942           if (isSFINAEContext())
8943             return QualType();
8944           
8945           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8946           return ResultTy;
8947         }
8948       }
8949
8950       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8951         return QualType();
8952       else
8953         return ResultTy;
8954     }
8955     // C99 6.5.9p2 and C99 6.5.8p2
8956     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8957                                    RCanPointeeTy.getUnqualifiedType())) {
8958       // Valid unless a relational comparison of function pointers
8959       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8960         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8961           << LHSType << RHSType << LHS.get()->getSourceRange()
8962           << RHS.get()->getSourceRange();
8963       }
8964     } else if (!IsRelational &&
8965                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8966       // Valid unless comparison between non-null pointer and function pointer
8967       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8968           && !LHSIsNull && !RHSIsNull)
8969         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8970                                                 /*isError*/false);
8971     } else {
8972       // Invalid
8973       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8974     }
8975     if (LCanPointeeTy != RCanPointeeTy) {
8976       // Treat NULL constant as a special case in OpenCL.
8977       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
8978         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
8979         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8980           Diag(Loc,
8981                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8982               << LHSType << RHSType << 0 /* comparison */
8983               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8984         }
8985       }
8986       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8987       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8988       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8989                                                : CK_BitCast;
8990       if (LHSIsNull && !RHSIsNull)
8991         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8992       else
8993         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8994     }
8995     return ResultTy;
8996   }
8997
8998   if (getLangOpts().CPlusPlus) {
8999     // Comparison of nullptr_t with itself.
9000     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9001       return ResultTy;
9002     
9003     // Comparison of pointers with null pointer constants and equality
9004     // comparisons of member pointers to null pointer constants.
9005     if (RHSIsNull &&
9006         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9007          (!IsRelational && 
9008           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9009       RHS = ImpCastExprToType(RHS.get(), LHSType, 
9010                         LHSType->isMemberPointerType()
9011                           ? CK_NullToMemberPointer
9012                           : CK_NullToPointer);
9013       return ResultTy;
9014     }
9015     if (LHSIsNull &&
9016         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9017          (!IsRelational && 
9018           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9019       LHS = ImpCastExprToType(LHS.get(), RHSType, 
9020                         RHSType->isMemberPointerType()
9021                           ? CK_NullToMemberPointer
9022                           : CK_NullToPointer);
9023       return ResultTy;
9024     }
9025
9026     // Comparison of member pointers.
9027     if (!IsRelational &&
9028         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9029       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9030         return QualType();
9031       else
9032         return ResultTy;
9033     }
9034
9035     // Handle scoped enumeration types specifically, since they don't promote
9036     // to integers.
9037     if (LHS.get()->getType()->isEnumeralType() &&
9038         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9039                                        RHS.get()->getType()))
9040       return ResultTy;
9041   }
9042
9043   // Handle block pointer types.
9044   if (!IsRelational && LHSType->isBlockPointerType() &&
9045       RHSType->isBlockPointerType()) {
9046     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9047     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9048
9049     if (!LHSIsNull && !RHSIsNull &&
9050         !Context.typesAreCompatible(lpointee, rpointee)) {
9051       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9052         << LHSType << RHSType << LHS.get()->getSourceRange()
9053         << RHS.get()->getSourceRange();
9054     }
9055     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9056     return ResultTy;
9057   }
9058
9059   // Allow block pointers to be compared with null pointer constants.
9060   if (!IsRelational
9061       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9062           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9063     if (!LHSIsNull && !RHSIsNull) {
9064       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9065              ->getPointeeType()->isVoidType())
9066             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9067                 ->getPointeeType()->isVoidType())))
9068         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9069           << LHSType << RHSType << LHS.get()->getSourceRange()
9070           << RHS.get()->getSourceRange();
9071     }
9072     if (LHSIsNull && !RHSIsNull)
9073       LHS = ImpCastExprToType(LHS.get(), RHSType,
9074                               RHSType->isPointerType() ? CK_BitCast
9075                                 : CK_AnyPointerToBlockPointerCast);
9076     else
9077       RHS = ImpCastExprToType(RHS.get(), LHSType,
9078                               LHSType->isPointerType() ? CK_BitCast
9079                                 : CK_AnyPointerToBlockPointerCast);
9080     return ResultTy;
9081   }
9082
9083   if (LHSType->isObjCObjectPointerType() ||
9084       RHSType->isObjCObjectPointerType()) {
9085     const PointerType *LPT = LHSType->getAs<PointerType>();
9086     const PointerType *RPT = RHSType->getAs<PointerType>();
9087     if (LPT || RPT) {
9088       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9089       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9090
9091       if (!LPtrToVoid && !RPtrToVoid &&
9092           !Context.typesAreCompatible(LHSType, RHSType)) {
9093         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9094                                           /*isError*/false);
9095       }
9096       if (LHSIsNull && !RHSIsNull) {
9097         Expr *E = LHS.get();
9098         if (getLangOpts().ObjCAutoRefCount)
9099           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9100         LHS = ImpCastExprToType(E, RHSType,
9101                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9102       }
9103       else {
9104         Expr *E = RHS.get();
9105         if (getLangOpts().ObjCAutoRefCount)
9106           CheckObjCARCConversion(SourceRange(), LHSType, E,
9107                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9108                                  /*DiagnoseCFAudited=*/false, Opc);
9109         RHS = ImpCastExprToType(E, LHSType,
9110                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9111       }
9112       return ResultTy;
9113     }
9114     if (LHSType->isObjCObjectPointerType() &&
9115         RHSType->isObjCObjectPointerType()) {
9116       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9117         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9118                                           /*isError*/false);
9119       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9120         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9121
9122       if (LHSIsNull && !RHSIsNull)
9123         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9124       else
9125         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9126       return ResultTy;
9127     }
9128   }
9129   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9130       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9131     unsigned DiagID = 0;
9132     bool isError = false;
9133     if (LangOpts.DebuggerSupport) {
9134       // Under a debugger, allow the comparison of pointers to integers,
9135       // since users tend to want to compare addresses.
9136     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9137         (RHSIsNull && RHSType->isIntegerType())) {
9138       if (IsRelational && !getLangOpts().CPlusPlus)
9139         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9140     } else if (IsRelational && !getLangOpts().CPlusPlus)
9141       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9142     else if (getLangOpts().CPlusPlus) {
9143       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9144       isError = true;
9145     } else
9146       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9147
9148     if (DiagID) {
9149       Diag(Loc, DiagID)
9150         << LHSType << RHSType << LHS.get()->getSourceRange()
9151         << RHS.get()->getSourceRange();
9152       if (isError)
9153         return QualType();
9154     }
9155     
9156     if (LHSType->isIntegerType())
9157       LHS = ImpCastExprToType(LHS.get(), RHSType,
9158                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9159     else
9160       RHS = ImpCastExprToType(RHS.get(), LHSType,
9161                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9162     return ResultTy;
9163   }
9164   
9165   // Handle block pointers.
9166   if (!IsRelational && RHSIsNull
9167       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9168     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9169     return ResultTy;
9170   }
9171   if (!IsRelational && LHSIsNull
9172       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9173     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9174     return ResultTy;
9175   }
9176
9177   return InvalidOperands(Loc, LHS, RHS);
9178 }
9179
9180
9181 // Return a signed type that is of identical size and number of elements.
9182 // For floating point vectors, return an integer type of identical size 
9183 // and number of elements.
9184 QualType Sema::GetSignedVectorType(QualType V) {
9185   const VectorType *VTy = V->getAs<VectorType>();
9186   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9187   if (TypeSize == Context.getTypeSize(Context.CharTy))
9188     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9189   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9190     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9191   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9192     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9193   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9194     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9195   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9196          "Unhandled vector element size in vector compare");
9197   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9198 }
9199
9200 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9201 /// operates on extended vector types.  Instead of producing an IntTy result,
9202 /// like a scalar comparison, a vector comparison produces a vector of integer
9203 /// types.
9204 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9205                                           SourceLocation Loc,
9206                                           bool IsRelational) {
9207   // Check to make sure we're operating on vectors of the same type and width,
9208   // Allowing one side to be a scalar of element type.
9209   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9210                               /*AllowBothBool*/true,
9211                               /*AllowBoolConversions*/getLangOpts().ZVector);
9212   if (vType.isNull())
9213     return vType;
9214
9215   QualType LHSType = LHS.get()->getType();
9216
9217   // If AltiVec, the comparison results in a numeric type, i.e.
9218   // bool for C++, int for C
9219   if (getLangOpts().AltiVec &&
9220       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9221     return Context.getLogicalOperationType();
9222
9223   // For non-floating point types, check for self-comparisons of the form
9224   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9225   // often indicate logic errors in the program.
9226   if (!LHSType->hasFloatingRepresentation() &&
9227       ActiveTemplateInstantiations.empty()) {
9228     if (DeclRefExpr* DRL
9229           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9230       if (DeclRefExpr* DRR
9231             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9232         if (DRL->getDecl() == DRR->getDecl())
9233           DiagRuntimeBehavior(Loc, nullptr,
9234                               PDiag(diag::warn_comparison_always)
9235                                 << 0 // self-
9236                                 << 2 // "a constant"
9237                               );
9238   }
9239
9240   // Check for comparisons of floating point operands using != and ==.
9241   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9242     assert (RHS.get()->getType()->hasFloatingRepresentation());
9243     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9244   }
9245   
9246   // Return a signed type for the vector.
9247   return GetSignedVectorType(LHSType);
9248 }
9249
9250 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9251                                           SourceLocation Loc) {
9252   // Ensure that either both operands are of the same vector type, or
9253   // one operand is of a vector type and the other is of its element type.
9254   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9255                                        /*AllowBothBool*/true,
9256                                        /*AllowBoolConversions*/false);
9257   if (vType.isNull())
9258     return InvalidOperands(Loc, LHS, RHS);
9259   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9260       vType->hasFloatingRepresentation())
9261     return InvalidOperands(Loc, LHS, RHS);
9262   
9263   return GetSignedVectorType(LHS.get()->getType());
9264 }
9265
9266 inline QualType Sema::CheckBitwiseOperands(
9267   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9268   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9269
9270   if (LHS.get()->getType()->isVectorType() ||
9271       RHS.get()->getType()->isVectorType()) {
9272     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9273         RHS.get()->getType()->hasIntegerRepresentation())
9274       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9275                         /*AllowBothBool*/true,
9276                         /*AllowBoolConversions*/getLangOpts().ZVector);
9277     return InvalidOperands(Loc, LHS, RHS);
9278   }
9279
9280   ExprResult LHSResult = LHS, RHSResult = RHS;
9281   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9282                                                  IsCompAssign);
9283   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9284     return QualType();
9285   LHS = LHSResult.get();
9286   RHS = RHSResult.get();
9287
9288   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9289     return compType;
9290   return InvalidOperands(Loc, LHS, RHS);
9291 }
9292
9293 // C99 6.5.[13,14]
9294 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9295                                            SourceLocation Loc,
9296                                            BinaryOperatorKind Opc) {
9297   // Check vector operands differently.
9298   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9299     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9300   
9301   // Diagnose cases where the user write a logical and/or but probably meant a
9302   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9303   // is a constant.
9304   if (LHS.get()->getType()->isIntegerType() &&
9305       !LHS.get()->getType()->isBooleanType() &&
9306       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9307       // Don't warn in macros or template instantiations.
9308       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9309     // If the RHS can be constant folded, and if it constant folds to something
9310     // that isn't 0 or 1 (which indicate a potential logical operation that
9311     // happened to fold to true/false) then warn.
9312     // Parens on the RHS are ignored.
9313     llvm::APSInt Result;
9314     if (RHS.get()->EvaluateAsInt(Result, Context))
9315       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9316            !RHS.get()->getExprLoc().isMacroID()) ||
9317           (Result != 0 && Result != 1)) {
9318         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9319           << RHS.get()->getSourceRange()
9320           << (Opc == BO_LAnd ? "&&" : "||");
9321         // Suggest replacing the logical operator with the bitwise version
9322         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9323             << (Opc == BO_LAnd ? "&" : "|")
9324             << FixItHint::CreateReplacement(SourceRange(
9325                                                  Loc, getLocForEndOfToken(Loc)),
9326                                             Opc == BO_LAnd ? "&" : "|");
9327         if (Opc == BO_LAnd)
9328           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9329           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9330               << FixItHint::CreateRemoval(
9331                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9332                               RHS.get()->getLocEnd()));
9333       }
9334   }
9335
9336   if (!Context.getLangOpts().CPlusPlus) {
9337     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9338     // not operate on the built-in scalar and vector float types.
9339     if (Context.getLangOpts().OpenCL &&
9340         Context.getLangOpts().OpenCLVersion < 120) {
9341       if (LHS.get()->getType()->isFloatingType() ||
9342           RHS.get()->getType()->isFloatingType())
9343         return InvalidOperands(Loc, LHS, RHS);
9344     }
9345
9346     LHS = UsualUnaryConversions(LHS.get());
9347     if (LHS.isInvalid())
9348       return QualType();
9349
9350     RHS = UsualUnaryConversions(RHS.get());
9351     if (RHS.isInvalid())
9352       return QualType();
9353
9354     if (!LHS.get()->getType()->isScalarType() ||
9355         !RHS.get()->getType()->isScalarType())
9356       return InvalidOperands(Loc, LHS, RHS);
9357
9358     return Context.IntTy;
9359   }
9360
9361   // The following is safe because we only use this method for
9362   // non-overloadable operands.
9363
9364   // C++ [expr.log.and]p1
9365   // C++ [expr.log.or]p1
9366   // The operands are both contextually converted to type bool.
9367   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9368   if (LHSRes.isInvalid())
9369     return InvalidOperands(Loc, LHS, RHS);
9370   LHS = LHSRes;
9371
9372   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9373   if (RHSRes.isInvalid())
9374     return InvalidOperands(Loc, LHS, RHS);
9375   RHS = RHSRes;
9376
9377   // C++ [expr.log.and]p2
9378   // C++ [expr.log.or]p2
9379   // The result is a bool.
9380   return Context.BoolTy;
9381 }
9382
9383 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9384   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9385   if (!ME) return false;
9386   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9387   ObjCMessageExpr *Base =
9388     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9389   if (!Base) return false;
9390   return Base->getMethodDecl() != nullptr;
9391 }
9392
9393 /// Is the given expression (which must be 'const') a reference to a
9394 /// variable which was originally non-const, but which has become
9395 /// 'const' due to being captured within a block?
9396 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9397 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9398   assert(E->isLValue() && E->getType().isConstQualified());
9399   E = E->IgnoreParens();
9400
9401   // Must be a reference to a declaration from an enclosing scope.
9402   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9403   if (!DRE) return NCCK_None;
9404   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9405
9406   // The declaration must be a variable which is not declared 'const'.
9407   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9408   if (!var) return NCCK_None;
9409   if (var->getType().isConstQualified()) return NCCK_None;
9410   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9411
9412   // Decide whether the first capture was for a block or a lambda.
9413   DeclContext *DC = S.CurContext, *Prev = nullptr;
9414   while (DC != var->getDeclContext()) {
9415     Prev = DC;
9416     DC = DC->getParent();
9417   }
9418   // Unless we have an init-capture, we've gone one step too far.
9419   if (!var->isInitCapture())
9420     DC = Prev;
9421   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9422 }
9423
9424 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9425   Ty = Ty.getNonReferenceType();
9426   if (IsDereference && Ty->isPointerType())
9427     Ty = Ty->getPointeeType();
9428   return !Ty.isConstQualified();
9429 }
9430
9431 /// Emit the "read-only variable not assignable" error and print notes to give
9432 /// more information about why the variable is not assignable, such as pointing
9433 /// to the declaration of a const variable, showing that a method is const, or
9434 /// that the function is returning a const reference.
9435 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9436                                     SourceLocation Loc) {
9437   // Update err_typecheck_assign_const and note_typecheck_assign_const
9438   // when this enum is changed.
9439   enum {
9440     ConstFunction,
9441     ConstVariable,
9442     ConstMember,
9443     ConstMethod,
9444     ConstUnknown,  // Keep as last element
9445   };
9446
9447   SourceRange ExprRange = E->getSourceRange();
9448
9449   // Only emit one error on the first const found.  All other consts will emit
9450   // a note to the error.
9451   bool DiagnosticEmitted = false;
9452
9453   // Track if the current expression is the result of a derefence, and if the
9454   // next checked expression is the result of a derefence.
9455   bool IsDereference = false;
9456   bool NextIsDereference = false;
9457
9458   // Loop to process MemberExpr chains.
9459   while (true) {
9460     IsDereference = NextIsDereference;
9461     NextIsDereference = false;
9462
9463     E = E->IgnoreParenImpCasts();
9464     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9465       NextIsDereference = ME->isArrow();
9466       const ValueDecl *VD = ME->getMemberDecl();
9467       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9468         // Mutable fields can be modified even if the class is const.
9469         if (Field->isMutable()) {
9470           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9471           break;
9472         }
9473
9474         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9475           if (!DiagnosticEmitted) {
9476             S.Diag(Loc, diag::err_typecheck_assign_const)
9477                 << ExprRange << ConstMember << false /*static*/ << Field
9478                 << Field->getType();
9479             DiagnosticEmitted = true;
9480           }
9481           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9482               << ConstMember << false /*static*/ << Field << Field->getType()
9483               << Field->getSourceRange();
9484         }
9485         E = ME->getBase();
9486         continue;
9487       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9488         if (VDecl->getType().isConstQualified()) {
9489           if (!DiagnosticEmitted) {
9490             S.Diag(Loc, diag::err_typecheck_assign_const)
9491                 << ExprRange << ConstMember << true /*static*/ << VDecl
9492                 << VDecl->getType();
9493             DiagnosticEmitted = true;
9494           }
9495           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9496               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9497               << VDecl->getSourceRange();
9498         }
9499         // Static fields do not inherit constness from parents.
9500         break;
9501       }
9502       break;
9503     } // End MemberExpr
9504     break;
9505   }
9506
9507   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9508     // Function calls
9509     const FunctionDecl *FD = CE->getDirectCallee();
9510     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9511       if (!DiagnosticEmitted) {
9512         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9513                                                       << ConstFunction << FD;
9514         DiagnosticEmitted = true;
9515       }
9516       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9517              diag::note_typecheck_assign_const)
9518           << ConstFunction << FD << FD->getReturnType()
9519           << FD->getReturnTypeSourceRange();
9520     }
9521   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9522     // Point to variable declaration.
9523     if (const ValueDecl *VD = DRE->getDecl()) {
9524       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9525         if (!DiagnosticEmitted) {
9526           S.Diag(Loc, diag::err_typecheck_assign_const)
9527               << ExprRange << ConstVariable << VD << VD->getType();
9528           DiagnosticEmitted = true;
9529         }
9530         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9531             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9532       }
9533     }
9534   } else if (isa<CXXThisExpr>(E)) {
9535     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9536       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9537         if (MD->isConst()) {
9538           if (!DiagnosticEmitted) {
9539             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9540                                                           << ConstMethod << MD;
9541             DiagnosticEmitted = true;
9542           }
9543           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9544               << ConstMethod << MD << MD->getSourceRange();
9545         }
9546       }
9547     }
9548   }
9549
9550   if (DiagnosticEmitted)
9551     return;
9552
9553   // Can't determine a more specific message, so display the generic error.
9554   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9555 }
9556
9557 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9558 /// emit an error and return true.  If so, return false.
9559 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9560   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9561   SourceLocation OrigLoc = Loc;
9562   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9563                                                               &Loc);
9564   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9565     IsLV = Expr::MLV_InvalidMessageExpression;
9566   if (IsLV == Expr::MLV_Valid)
9567     return false;
9568
9569   unsigned DiagID = 0;
9570   bool NeedType = false;
9571   switch (IsLV) { // C99 6.5.16p2
9572   case Expr::MLV_ConstQualified:
9573     // Use a specialized diagnostic when we're assigning to an object
9574     // from an enclosing function or block.
9575     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9576       if (NCCK == NCCK_Block)
9577         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9578       else
9579         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9580       break;
9581     }
9582
9583     // In ARC, use some specialized diagnostics for occasions where we
9584     // infer 'const'.  These are always pseudo-strong variables.
9585     if (S.getLangOpts().ObjCAutoRefCount) {
9586       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9587       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9588         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9589
9590         // Use the normal diagnostic if it's pseudo-__strong but the
9591         // user actually wrote 'const'.
9592         if (var->isARCPseudoStrong() &&
9593             (!var->getTypeSourceInfo() ||
9594              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9595           // There are two pseudo-strong cases:
9596           //  - self
9597           ObjCMethodDecl *method = S.getCurMethodDecl();
9598           if (method && var == method->getSelfDecl())
9599             DiagID = method->isClassMethod()
9600               ? diag::err_typecheck_arc_assign_self_class_method
9601               : diag::err_typecheck_arc_assign_self;
9602
9603           //  - fast enumeration variables
9604           else
9605             DiagID = diag::err_typecheck_arr_assign_enumeration;
9606
9607           SourceRange Assign;
9608           if (Loc != OrigLoc)
9609             Assign = SourceRange(OrigLoc, OrigLoc);
9610           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9611           // We need to preserve the AST regardless, so migration tool
9612           // can do its job.
9613           return false;
9614         }
9615       }
9616     }
9617
9618     // If none of the special cases above are triggered, then this is a
9619     // simple const assignment.
9620     if (DiagID == 0) {
9621       DiagnoseConstAssignment(S, E, Loc);
9622       return true;
9623     }
9624
9625     break;
9626   case Expr::MLV_ConstAddrSpace:
9627     DiagnoseConstAssignment(S, E, Loc);
9628     return true;
9629   case Expr::MLV_ArrayType:
9630   case Expr::MLV_ArrayTemporary:
9631     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9632     NeedType = true;
9633     break;
9634   case Expr::MLV_NotObjectType:
9635     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9636     NeedType = true;
9637     break;
9638   case Expr::MLV_LValueCast:
9639     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9640     break;
9641   case Expr::MLV_Valid:
9642     llvm_unreachable("did not take early return for MLV_Valid");
9643   case Expr::MLV_InvalidExpression:
9644   case Expr::MLV_MemberFunction:
9645   case Expr::MLV_ClassTemporary:
9646     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9647     break;
9648   case Expr::MLV_IncompleteType:
9649   case Expr::MLV_IncompleteVoidType:
9650     return S.RequireCompleteType(Loc, E->getType(),
9651              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9652   case Expr::MLV_DuplicateVectorComponents:
9653     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9654     break;
9655   case Expr::MLV_NoSetterProperty:
9656     llvm_unreachable("readonly properties should be processed differently");
9657   case Expr::MLV_InvalidMessageExpression:
9658     DiagID = diag::error_readonly_message_assignment;
9659     break;
9660   case Expr::MLV_SubObjCPropertySetting:
9661     DiagID = diag::error_no_subobject_property_setting;
9662     break;
9663   }
9664
9665   SourceRange Assign;
9666   if (Loc != OrigLoc)
9667     Assign = SourceRange(OrigLoc, OrigLoc);
9668   if (NeedType)
9669     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9670   else
9671     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9672   return true;
9673 }
9674
9675 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9676                                          SourceLocation Loc,
9677                                          Sema &Sema) {
9678   // C / C++ fields
9679   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9680   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9681   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9682     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9683       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9684   }
9685
9686   // Objective-C instance variables
9687   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9688   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9689   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9690     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9691     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9692     if (RL && RR && RL->getDecl() == RR->getDecl())
9693       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9694   }
9695 }
9696
9697 // C99 6.5.16.1
9698 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9699                                        SourceLocation Loc,
9700                                        QualType CompoundType) {
9701   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9702
9703   // Verify that LHS is a modifiable lvalue, and emit error if not.
9704   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9705     return QualType();
9706
9707   QualType LHSType = LHSExpr->getType();
9708   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9709                                              CompoundType;
9710   AssignConvertType ConvTy;
9711   if (CompoundType.isNull()) {
9712     Expr *RHSCheck = RHS.get();
9713
9714     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9715
9716     QualType LHSTy(LHSType);
9717     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9718     if (RHS.isInvalid())
9719       return QualType();
9720     // Special case of NSObject attributes on c-style pointer types.
9721     if (ConvTy == IncompatiblePointer &&
9722         ((Context.isObjCNSObjectType(LHSType) &&
9723           RHSType->isObjCObjectPointerType()) ||
9724          (Context.isObjCNSObjectType(RHSType) &&
9725           LHSType->isObjCObjectPointerType())))
9726       ConvTy = Compatible;
9727
9728     if (ConvTy == Compatible &&
9729         LHSType->isObjCObjectType())
9730         Diag(Loc, diag::err_objc_object_assignment)
9731           << LHSType;
9732
9733     // If the RHS is a unary plus or minus, check to see if they = and + are
9734     // right next to each other.  If so, the user may have typo'd "x =+ 4"
9735     // instead of "x += 4".
9736     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9737       RHSCheck = ICE->getSubExpr();
9738     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9739       if ((UO->getOpcode() == UO_Plus ||
9740            UO->getOpcode() == UO_Minus) &&
9741           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9742           // Only if the two operators are exactly adjacent.
9743           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9744           // And there is a space or other character before the subexpr of the
9745           // unary +/-.  We don't want to warn on "x=-1".
9746           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9747           UO->getSubExpr()->getLocStart().isFileID()) {
9748         Diag(Loc, diag::warn_not_compound_assign)
9749           << (UO->getOpcode() == UO_Plus ? "+" : "-")
9750           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9751       }
9752     }
9753
9754     if (ConvTy == Compatible) {
9755       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9756         // Warn about retain cycles where a block captures the LHS, but
9757         // not if the LHS is a simple variable into which the block is
9758         // being stored...unless that variable can be captured by reference!
9759         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9760         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9761         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9762           checkRetainCycles(LHSExpr, RHS.get());
9763
9764         // It is safe to assign a weak reference into a strong variable.
9765         // Although this code can still have problems:
9766         //   id x = self.weakProp;
9767         //   id y = self.weakProp;
9768         // we do not warn to warn spuriously when 'x' and 'y' are on separate
9769         // paths through the function. This should be revisited if
9770         // -Wrepeated-use-of-weak is made flow-sensitive.
9771         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9772                              RHS.get()->getLocStart()))
9773           getCurFunction()->markSafeWeakUse(RHS.get());
9774
9775       } else if (getLangOpts().ObjCAutoRefCount) {
9776         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
9777       }
9778     }
9779   } else {
9780     // Compound assignment "x += y"
9781     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
9782   }
9783
9784   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
9785                                RHS.get(), AA_Assigning))
9786     return QualType();
9787
9788   CheckForNullPointerDereference(*this, LHSExpr);
9789
9790   // C99 6.5.16p3: The type of an assignment expression is the type of the
9791   // left operand unless the left operand has qualified type, in which case
9792   // it is the unqualified version of the type of the left operand.
9793   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9794   // is converted to the type of the assignment expression (above).
9795   // C++ 5.17p1: the type of the assignment expression is that of its left
9796   // operand.
9797   return (getLangOpts().CPlusPlus
9798           ? LHSType : LHSType.getUnqualifiedType());
9799 }
9800
9801 // C99 6.5.17
9802 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
9803                                    SourceLocation Loc) {
9804   LHS = S.CheckPlaceholderExpr(LHS.get());
9805   RHS = S.CheckPlaceholderExpr(RHS.get());
9806   if (LHS.isInvalid() || RHS.isInvalid())
9807     return QualType();
9808
9809   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9810   // operands, but not unary promotions.
9811   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
9812
9813   // So we treat the LHS as a ignored value, and in C++ we allow the
9814   // containing site to determine what should be done with the RHS.
9815   LHS = S.IgnoredValueConversions(LHS.get());
9816   if (LHS.isInvalid())
9817     return QualType();
9818
9819   S.DiagnoseUnusedExprResult(LHS.get());
9820
9821   if (!S.getLangOpts().CPlusPlus) {
9822     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9823     if (RHS.isInvalid())
9824       return QualType();
9825     if (!RHS.get()->getType()->isVoidType())
9826       S.RequireCompleteType(Loc, RHS.get()->getType(),
9827                             diag::err_incomplete_type);
9828   }
9829
9830   return RHS.get()->getType();
9831 }
9832
9833 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9834 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
9835 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9836                                                ExprValueKind &VK,
9837                                                ExprObjectKind &OK,
9838                                                SourceLocation OpLoc,
9839                                                bool IsInc, bool IsPrefix) {
9840   if (Op->isTypeDependent())
9841     return S.Context.DependentTy;
9842
9843   QualType ResType = Op->getType();
9844   // Atomic types can be used for increment / decrement where the non-atomic
9845   // versions can, so ignore the _Atomic() specifier for the purpose of
9846   // checking.
9847   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9848     ResType = ResAtomicType->getValueType();
9849
9850   assert(!ResType.isNull() && "no type for increment/decrement expression");
9851
9852   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
9853     // Decrement of bool is not allowed.
9854     if (!IsInc) {
9855       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
9856       return QualType();
9857     }
9858     // Increment of bool sets it to true, but is deprecated.
9859     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
9860                                               : diag::warn_increment_bool)
9861       << Op->getSourceRange();
9862   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9863     // Error on enum increments and decrements in C++ mode
9864     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9865     return QualType();
9866   } else if (ResType->isRealType()) {
9867     // OK!
9868   } else if (ResType->isPointerType()) {
9869     // C99 6.5.2.4p2, 6.5.6p2
9870     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
9871       return QualType();
9872   } else if (ResType->isObjCObjectPointerType()) {
9873     // On modern runtimes, ObjC pointer arithmetic is forbidden.
9874     // Otherwise, we just need a complete type.
9875     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9876         checkArithmeticOnObjCPointer(S, OpLoc, Op))
9877       return QualType();    
9878   } else if (ResType->isAnyComplexType()) {
9879     // C99 does not support ++/-- on complex types, we allow as an extension.
9880     S.Diag(OpLoc, diag::ext_integer_increment_complex)
9881       << ResType << Op->getSourceRange();
9882   } else if (ResType->isPlaceholderType()) {
9883     ExprResult PR = S.CheckPlaceholderExpr(Op);
9884     if (PR.isInvalid()) return QualType();
9885     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
9886                                           IsInc, IsPrefix);
9887   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
9888     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
9889   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
9890              (ResType->getAs<VectorType>()->getVectorKind() !=
9891               VectorType::AltiVecBool)) {
9892     // The z vector extensions allow ++ and -- for non-bool vectors.
9893   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9894             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9895     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
9896   } else {
9897     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
9898       << ResType << int(IsInc) << Op->getSourceRange();
9899     return QualType();
9900   }
9901   // At this point, we know we have a real, complex or pointer type.
9902   // Now make sure the operand is a modifiable lvalue.
9903   if (CheckForModifiableLvalue(Op, OpLoc, S))
9904     return QualType();
9905   // In C++, a prefix increment is the same type as the operand. Otherwise
9906   // (in C or with postfix), the increment is the unqualified type of the
9907   // operand.
9908   if (IsPrefix && S.getLangOpts().CPlusPlus) {
9909     VK = VK_LValue;
9910     OK = Op->getObjectKind();
9911     return ResType;
9912   } else {
9913     VK = VK_RValue;
9914     return ResType.getUnqualifiedType();
9915   }
9916 }
9917   
9918
9919 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
9920 /// This routine allows us to typecheck complex/recursive expressions
9921 /// where the declaration is needed for type checking. We only need to
9922 /// handle cases when the expression references a function designator
9923 /// or is an lvalue. Here are some examples:
9924 ///  - &(x) => x
9925 ///  - &*****f => f for f a function designator.
9926 ///  - &s.xx => s
9927 ///  - &s.zz[1].yy -> s, if zz is an array
9928 ///  - *(x + 1) -> x, if x is an array
9929 ///  - &"123"[2] -> 0
9930 ///  - & __real__ x -> x
9931 static ValueDecl *getPrimaryDecl(Expr *E) {
9932   switch (E->getStmtClass()) {
9933   case Stmt::DeclRefExprClass:
9934     return cast<DeclRefExpr>(E)->getDecl();
9935   case Stmt::MemberExprClass:
9936     // If this is an arrow operator, the address is an offset from
9937     // the base's value, so the object the base refers to is
9938     // irrelevant.
9939     if (cast<MemberExpr>(E)->isArrow())
9940       return nullptr;
9941     // Otherwise, the expression refers to a part of the base
9942     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
9943   case Stmt::ArraySubscriptExprClass: {
9944     // FIXME: This code shouldn't be necessary!  We should catch the implicit
9945     // promotion of register arrays earlier.
9946     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9947     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9948       if (ICE->getSubExpr()->getType()->isArrayType())
9949         return getPrimaryDecl(ICE->getSubExpr());
9950     }
9951     return nullptr;
9952   }
9953   case Stmt::UnaryOperatorClass: {
9954     UnaryOperator *UO = cast<UnaryOperator>(E);
9955
9956     switch(UO->getOpcode()) {
9957     case UO_Real:
9958     case UO_Imag:
9959     case UO_Extension:
9960       return getPrimaryDecl(UO->getSubExpr());
9961     default:
9962       return nullptr;
9963     }
9964   }
9965   case Stmt::ParenExprClass:
9966     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
9967   case Stmt::ImplicitCastExprClass:
9968     // If the result of an implicit cast is an l-value, we care about
9969     // the sub-expression; otherwise, the result here doesn't matter.
9970     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
9971   default:
9972     return nullptr;
9973   }
9974 }
9975
9976 namespace {
9977   enum {
9978     AO_Bit_Field = 0,
9979     AO_Vector_Element = 1,
9980     AO_Property_Expansion = 2,
9981     AO_Register_Variable = 3,
9982     AO_No_Error = 4
9983   };
9984 }
9985 /// \brief Diagnose invalid operand for address of operations.
9986 ///
9987 /// \param Type The type of operand which cannot have its address taken.
9988 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9989                                          Expr *E, unsigned Type) {
9990   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9991 }
9992
9993 /// CheckAddressOfOperand - The operand of & must be either a function
9994 /// designator or an lvalue designating an object. If it is an lvalue, the
9995 /// object cannot be declared with storage class register or be a bit field.
9996 /// Note: The usual conversions are *not* applied to the operand of the &
9997 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9998 /// In C++, the operand might be an overloaded function name, in which case
9999 /// we allow the '&' but retain the overloaded-function type.
10000 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10001   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10002     if (PTy->getKind() == BuiltinType::Overload) {
10003       Expr *E = OrigOp.get()->IgnoreParens();
10004       if (!isa<OverloadExpr>(E)) {
10005         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10006         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10007           << OrigOp.get()->getSourceRange();
10008         return QualType();
10009       }
10010
10011       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10012       if (isa<UnresolvedMemberExpr>(Ovl))
10013         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10014           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10015             << OrigOp.get()->getSourceRange();
10016           return QualType();
10017         }
10018
10019       return Context.OverloadTy;
10020     }
10021
10022     if (PTy->getKind() == BuiltinType::UnknownAny)
10023       return Context.UnknownAnyTy;
10024
10025     if (PTy->getKind() == BuiltinType::BoundMember) {
10026       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10027         << OrigOp.get()->getSourceRange();
10028       return QualType();
10029     }
10030
10031     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10032     if (OrigOp.isInvalid()) return QualType();
10033   }
10034
10035   if (OrigOp.get()->isTypeDependent())
10036     return Context.DependentTy;
10037
10038   assert(!OrigOp.get()->getType()->isPlaceholderType());
10039
10040   // Make sure to ignore parentheses in subsequent checks
10041   Expr *op = OrigOp.get()->IgnoreParens();
10042
10043   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10044   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10045     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10046     return QualType();
10047   }
10048
10049   if (getLangOpts().C99) {
10050     // Implement C99-only parts of addressof rules.
10051     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10052       if (uOp->getOpcode() == UO_Deref)
10053         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10054         // (assuming the deref expression is valid).
10055         return uOp->getSubExpr()->getType();
10056     }
10057     // Technically, there should be a check for array subscript
10058     // expressions here, but the result of one is always an lvalue anyway.
10059   }
10060   ValueDecl *dcl = getPrimaryDecl(op);
10061
10062   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10063     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10064                                            op->getLocStart()))
10065       return QualType();
10066
10067   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10068   unsigned AddressOfError = AO_No_Error;
10069
10070   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10071     bool sfinae = (bool)isSFINAEContext();
10072     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10073                                   : diag::ext_typecheck_addrof_temporary)
10074       << op->getType() << op->getSourceRange();
10075     if (sfinae)
10076       return QualType();
10077     // Materialize the temporary as an lvalue so that we can take its address.
10078     OrigOp = op = new (Context)
10079         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10080   } else if (isa<ObjCSelectorExpr>(op)) {
10081     return Context.getPointerType(op->getType());
10082   } else if (lval == Expr::LV_MemberFunction) {
10083     // If it's an instance method, make a member pointer.
10084     // The expression must have exactly the form &A::foo.
10085
10086     // If the underlying expression isn't a decl ref, give up.
10087     if (!isa<DeclRefExpr>(op)) {
10088       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10089         << OrigOp.get()->getSourceRange();
10090       return QualType();
10091     }
10092     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10093     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10094
10095     // The id-expression was parenthesized.
10096     if (OrigOp.get() != DRE) {
10097       Diag(OpLoc, diag::err_parens_pointer_member_function)
10098         << OrigOp.get()->getSourceRange();
10099
10100     // The method was named without a qualifier.
10101     } else if (!DRE->getQualifier()) {
10102       if (MD->getParent()->getName().empty())
10103         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10104           << op->getSourceRange();
10105       else {
10106         SmallString<32> Str;
10107         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10108         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10109           << op->getSourceRange()
10110           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10111       }
10112     }
10113
10114     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10115     if (isa<CXXDestructorDecl>(MD))
10116       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10117
10118     QualType MPTy = Context.getMemberPointerType(
10119         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10120     // Under the MS ABI, lock down the inheritance model now.
10121     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10122       (void)isCompleteType(OpLoc, MPTy);
10123     return MPTy;
10124   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10125     // C99 6.5.3.2p1
10126     // The operand must be either an l-value or a function designator
10127     if (!op->getType()->isFunctionType()) {
10128       // Use a special diagnostic for loads from property references.
10129       if (isa<PseudoObjectExpr>(op)) {
10130         AddressOfError = AO_Property_Expansion;
10131       } else {
10132         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10133           << op->getType() << op->getSourceRange();
10134         return QualType();
10135       }
10136     }
10137   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10138     // The operand cannot be a bit-field
10139     AddressOfError = AO_Bit_Field;
10140   } else if (op->getObjectKind() == OK_VectorComponent) {
10141     // The operand cannot be an element of a vector
10142     AddressOfError = AO_Vector_Element;
10143   } else if (dcl) { // C99 6.5.3.2p1
10144     // We have an lvalue with a decl. Make sure the decl is not declared
10145     // with the register storage-class specifier.
10146     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10147       // in C++ it is not error to take address of a register
10148       // variable (c++03 7.1.1P3)
10149       if (vd->getStorageClass() == SC_Register &&
10150           !getLangOpts().CPlusPlus) {
10151         AddressOfError = AO_Register_Variable;
10152       }
10153     } else if (isa<MSPropertyDecl>(dcl)) {
10154       AddressOfError = AO_Property_Expansion;
10155     } else if (isa<FunctionTemplateDecl>(dcl)) {
10156       return Context.OverloadTy;
10157     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10158       // Okay: we can take the address of a field.
10159       // Could be a pointer to member, though, if there is an explicit
10160       // scope qualifier for the class.
10161       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10162         DeclContext *Ctx = dcl->getDeclContext();
10163         if (Ctx && Ctx->isRecord()) {
10164           if (dcl->getType()->isReferenceType()) {
10165             Diag(OpLoc,
10166                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10167               << dcl->getDeclName() << dcl->getType();
10168             return QualType();
10169           }
10170
10171           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10172             Ctx = Ctx->getParent();
10173
10174           QualType MPTy = Context.getMemberPointerType(
10175               op->getType(),
10176               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10177           // Under the MS ABI, lock down the inheritance model now.
10178           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10179             (void)isCompleteType(OpLoc, MPTy);
10180           return MPTy;
10181         }
10182       }
10183     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10184       llvm_unreachable("Unknown/unexpected decl type");
10185   }
10186
10187   if (AddressOfError != AO_No_Error) {
10188     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10189     return QualType();
10190   }
10191
10192   if (lval == Expr::LV_IncompleteVoidType) {
10193     // Taking the address of a void variable is technically illegal, but we
10194     // allow it in cases which are otherwise valid.
10195     // Example: "extern void x; void* y = &x;".
10196     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10197   }
10198
10199   // If the operand has type "type", the result has type "pointer to type".
10200   if (op->getType()->isObjCObjectType())
10201     return Context.getObjCObjectPointerType(op->getType());
10202   return Context.getPointerType(op->getType());
10203 }
10204
10205 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10206   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10207   if (!DRE)
10208     return;
10209   const Decl *D = DRE->getDecl();
10210   if (!D)
10211     return;
10212   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10213   if (!Param)
10214     return;
10215   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10216     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10217       return;
10218   if (FunctionScopeInfo *FD = S.getCurFunction())
10219     if (!FD->ModifiedNonNullParams.count(Param))
10220       FD->ModifiedNonNullParams.insert(Param);
10221 }
10222
10223 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10224 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10225                                         SourceLocation OpLoc) {
10226   if (Op->isTypeDependent())
10227     return S.Context.DependentTy;
10228
10229   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10230   if (ConvResult.isInvalid())
10231     return QualType();
10232   Op = ConvResult.get();
10233   QualType OpTy = Op->getType();
10234   QualType Result;
10235
10236   if (isa<CXXReinterpretCastExpr>(Op)) {
10237     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10238     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10239                                      Op->getSourceRange());
10240   }
10241
10242   if (const PointerType *PT = OpTy->getAs<PointerType>())
10243     Result = PT->getPointeeType();
10244   else if (const ObjCObjectPointerType *OPT =
10245              OpTy->getAs<ObjCObjectPointerType>())
10246     Result = OPT->getPointeeType();
10247   else {
10248     ExprResult PR = S.CheckPlaceholderExpr(Op);
10249     if (PR.isInvalid()) return QualType();
10250     if (PR.get() != Op)
10251       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10252   }
10253
10254   if (Result.isNull()) {
10255     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10256       << OpTy << Op->getSourceRange();
10257     return QualType();
10258   }
10259
10260   // Note that per both C89 and C99, indirection is always legal, even if Result
10261   // is an incomplete type or void.  It would be possible to warn about
10262   // dereferencing a void pointer, but it's completely well-defined, and such a
10263   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10264   // for pointers to 'void' but is fine for any other pointer type:
10265   //
10266   // C++ [expr.unary.op]p1:
10267   //   [...] the expression to which [the unary * operator] is applied shall
10268   //   be a pointer to an object type, or a pointer to a function type
10269   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10270     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10271       << OpTy << Op->getSourceRange();
10272
10273   // Dereferences are usually l-values...
10274   VK = VK_LValue;
10275
10276   // ...except that certain expressions are never l-values in C.
10277   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10278     VK = VK_RValue;
10279   
10280   return Result;
10281 }
10282
10283 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10284   BinaryOperatorKind Opc;
10285   switch (Kind) {
10286   default: llvm_unreachable("Unknown binop!");
10287   case tok::periodstar:           Opc = BO_PtrMemD; break;
10288   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10289   case tok::star:                 Opc = BO_Mul; break;
10290   case tok::slash:                Opc = BO_Div; break;
10291   case tok::percent:              Opc = BO_Rem; break;
10292   case tok::plus:                 Opc = BO_Add; break;
10293   case tok::minus:                Opc = BO_Sub; break;
10294   case tok::lessless:             Opc = BO_Shl; break;
10295   case tok::greatergreater:       Opc = BO_Shr; break;
10296   case tok::lessequal:            Opc = BO_LE; break;
10297   case tok::less:                 Opc = BO_LT; break;
10298   case tok::greaterequal:         Opc = BO_GE; break;
10299   case tok::greater:              Opc = BO_GT; break;
10300   case tok::exclaimequal:         Opc = BO_NE; break;
10301   case tok::equalequal:           Opc = BO_EQ; break;
10302   case tok::amp:                  Opc = BO_And; break;
10303   case tok::caret:                Opc = BO_Xor; break;
10304   case tok::pipe:                 Opc = BO_Or; break;
10305   case tok::ampamp:               Opc = BO_LAnd; break;
10306   case tok::pipepipe:             Opc = BO_LOr; break;
10307   case tok::equal:                Opc = BO_Assign; break;
10308   case tok::starequal:            Opc = BO_MulAssign; break;
10309   case tok::slashequal:           Opc = BO_DivAssign; break;
10310   case tok::percentequal:         Opc = BO_RemAssign; break;
10311   case tok::plusequal:            Opc = BO_AddAssign; break;
10312   case tok::minusequal:           Opc = BO_SubAssign; break;
10313   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10314   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10315   case tok::ampequal:             Opc = BO_AndAssign; break;
10316   case tok::caretequal:           Opc = BO_XorAssign; break;
10317   case tok::pipeequal:            Opc = BO_OrAssign; break;
10318   case tok::comma:                Opc = BO_Comma; break;
10319   }
10320   return Opc;
10321 }
10322
10323 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10324   tok::TokenKind Kind) {
10325   UnaryOperatorKind Opc;
10326   switch (Kind) {
10327   default: llvm_unreachable("Unknown unary op!");
10328   case tok::plusplus:     Opc = UO_PreInc; break;
10329   case tok::minusminus:   Opc = UO_PreDec; break;
10330   case tok::amp:          Opc = UO_AddrOf; break;
10331   case tok::star:         Opc = UO_Deref; break;
10332   case tok::plus:         Opc = UO_Plus; break;
10333   case tok::minus:        Opc = UO_Minus; break;
10334   case tok::tilde:        Opc = UO_Not; break;
10335   case tok::exclaim:      Opc = UO_LNot; break;
10336   case tok::kw___real:    Opc = UO_Real; break;
10337   case tok::kw___imag:    Opc = UO_Imag; break;
10338   case tok::kw___extension__: Opc = UO_Extension; break;
10339   }
10340   return Opc;
10341 }
10342
10343 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10344 /// This warning is only emitted for builtin assignment operations. It is also
10345 /// suppressed in the event of macro expansions.
10346 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10347                                    SourceLocation OpLoc) {
10348   if (!S.ActiveTemplateInstantiations.empty())
10349     return;
10350   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10351     return;
10352   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10353   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10354   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10355   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10356   if (!LHSDeclRef || !RHSDeclRef ||
10357       LHSDeclRef->getLocation().isMacroID() ||
10358       RHSDeclRef->getLocation().isMacroID())
10359     return;
10360   const ValueDecl *LHSDecl =
10361     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10362   const ValueDecl *RHSDecl =
10363     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10364   if (LHSDecl != RHSDecl)
10365     return;
10366   if (LHSDecl->getType().isVolatileQualified())
10367     return;
10368   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10369     if (RefTy->getPointeeType().isVolatileQualified())
10370       return;
10371
10372   S.Diag(OpLoc, diag::warn_self_assignment)
10373       << LHSDeclRef->getType()
10374       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10375 }
10376
10377 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10378 /// is usually indicative of introspection within the Objective-C pointer.
10379 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10380                                           SourceLocation OpLoc) {
10381   if (!S.getLangOpts().ObjC1)
10382     return;
10383
10384   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10385   const Expr *LHS = L.get();
10386   const Expr *RHS = R.get();
10387
10388   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10389     ObjCPointerExpr = LHS;
10390     OtherExpr = RHS;
10391   }
10392   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10393     ObjCPointerExpr = RHS;
10394     OtherExpr = LHS;
10395   }
10396
10397   // This warning is deliberately made very specific to reduce false
10398   // positives with logic that uses '&' for hashing.  This logic mainly
10399   // looks for code trying to introspect into tagged pointers, which
10400   // code should generally never do.
10401   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10402     unsigned Diag = diag::warn_objc_pointer_masking;
10403     // Determine if we are introspecting the result of performSelectorXXX.
10404     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10405     // Special case messages to -performSelector and friends, which
10406     // can return non-pointer values boxed in a pointer value.
10407     // Some clients may wish to silence warnings in this subcase.
10408     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10409       Selector S = ME->getSelector();
10410       StringRef SelArg0 = S.getNameForSlot(0);
10411       if (SelArg0.startswith("performSelector"))
10412         Diag = diag::warn_objc_pointer_masking_performSelector;
10413     }
10414     
10415     S.Diag(OpLoc, Diag)
10416       << ObjCPointerExpr->getSourceRange();
10417   }
10418 }
10419
10420 static NamedDecl *getDeclFromExpr(Expr *E) {
10421   if (!E)
10422     return nullptr;
10423   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10424     return DRE->getDecl();
10425   if (auto *ME = dyn_cast<MemberExpr>(E))
10426     return ME->getMemberDecl();
10427   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10428     return IRE->getDecl();
10429   return nullptr;
10430 }
10431
10432 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10433 /// operator @p Opc at location @c TokLoc. This routine only supports
10434 /// built-in operations; ActOnBinOp handles overloaded operators.
10435 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10436                                     BinaryOperatorKind Opc,
10437                                     Expr *LHSExpr, Expr *RHSExpr) {
10438   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10439     // The syntax only allows initializer lists on the RHS of assignment,
10440     // so we don't need to worry about accepting invalid code for
10441     // non-assignment operators.
10442     // C++11 5.17p9:
10443     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10444     //   of x = {} is x = T().
10445     InitializationKind Kind =
10446         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10447     InitializedEntity Entity =
10448         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10449     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10450     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10451     if (Init.isInvalid())
10452       return Init;
10453     RHSExpr = Init.get();
10454   }
10455
10456   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10457   QualType ResultTy;     // Result type of the binary operator.
10458   // The following two variables are used for compound assignment operators
10459   QualType CompLHSTy;    // Type of LHS after promotions for computation
10460   QualType CompResultTy; // Type of computation result
10461   ExprValueKind VK = VK_RValue;
10462   ExprObjectKind OK = OK_Ordinary;
10463
10464   if (!getLangOpts().CPlusPlus) {
10465     // C cannot handle TypoExpr nodes on either side of a binop because it
10466     // doesn't handle dependent types properly, so make sure any TypoExprs have
10467     // been dealt with before checking the operands.
10468     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10469     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10470       if (Opc != BO_Assign)
10471         return ExprResult(E);
10472       // Avoid correcting the RHS to the same Expr as the LHS.
10473       Decl *D = getDeclFromExpr(E);
10474       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10475     });
10476     if (!LHS.isUsable() || !RHS.isUsable())
10477       return ExprError();
10478   }
10479
10480   if (getLangOpts().OpenCL) {
10481     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10482     // the ATOMIC_VAR_INIT macro.
10483     if (LHSExpr->getType()->isAtomicType() ||
10484         RHSExpr->getType()->isAtomicType()) {
10485       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10486       if (BO_Assign == Opc)
10487         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10488       else
10489         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10490       return ExprError();
10491     }
10492   }
10493
10494   switch (Opc) {
10495   case BO_Assign:
10496     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10497     if (getLangOpts().CPlusPlus &&
10498         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10499       VK = LHS.get()->getValueKind();
10500       OK = LHS.get()->getObjectKind();
10501     }
10502     if (!ResultTy.isNull()) {
10503       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10504       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10505     }
10506     RecordModifiableNonNullParam(*this, LHS.get());
10507     break;
10508   case BO_PtrMemD:
10509   case BO_PtrMemI:
10510     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10511                                             Opc == BO_PtrMemI);
10512     break;
10513   case BO_Mul:
10514   case BO_Div:
10515     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10516                                            Opc == BO_Div);
10517     break;
10518   case BO_Rem:
10519     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10520     break;
10521   case BO_Add:
10522     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10523     break;
10524   case BO_Sub:
10525     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10526     break;
10527   case BO_Shl:
10528   case BO_Shr:
10529     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10530     break;
10531   case BO_LE:
10532   case BO_LT:
10533   case BO_GE:
10534   case BO_GT:
10535     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10536     break;
10537   case BO_EQ:
10538   case BO_NE:
10539     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10540     break;
10541   case BO_And:
10542     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10543   case BO_Xor:
10544   case BO_Or:
10545     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10546     break;
10547   case BO_LAnd:
10548   case BO_LOr:
10549     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10550     break;
10551   case BO_MulAssign:
10552   case BO_DivAssign:
10553     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10554                                                Opc == BO_DivAssign);
10555     CompLHSTy = CompResultTy;
10556     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10557       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10558     break;
10559   case BO_RemAssign:
10560     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10561     CompLHSTy = CompResultTy;
10562     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10563       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10564     break;
10565   case BO_AddAssign:
10566     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10567     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10568       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10569     break;
10570   case BO_SubAssign:
10571     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10572     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10573       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10574     break;
10575   case BO_ShlAssign:
10576   case BO_ShrAssign:
10577     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10578     CompLHSTy = CompResultTy;
10579     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10580       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10581     break;
10582   case BO_AndAssign:
10583   case BO_OrAssign: // fallthrough
10584     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10585   case BO_XorAssign:
10586     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10587     CompLHSTy = CompResultTy;
10588     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10589       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10590     break;
10591   case BO_Comma:
10592     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10593     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10594       VK = RHS.get()->getValueKind();
10595       OK = RHS.get()->getObjectKind();
10596     }
10597     break;
10598   }
10599   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10600     return ExprError();
10601
10602   // Check for array bounds violations for both sides of the BinaryOperator
10603   CheckArrayAccess(LHS.get());
10604   CheckArrayAccess(RHS.get());
10605
10606   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10607     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10608                                                  &Context.Idents.get("object_setClass"),
10609                                                  SourceLocation(), LookupOrdinaryName);
10610     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10611       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10612       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10613       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10614       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10615       FixItHint::CreateInsertion(RHSLocEnd, ")");
10616     }
10617     else
10618       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10619   }
10620   else if (const ObjCIvarRefExpr *OIRE =
10621            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10622     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10623   
10624   if (CompResultTy.isNull())
10625     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10626                                         OK, OpLoc, FPFeatures.fp_contract);
10627   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10628       OK_ObjCProperty) {
10629     VK = VK_LValue;
10630     OK = LHS.get()->getObjectKind();
10631   }
10632   return new (Context) CompoundAssignOperator(
10633       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10634       OpLoc, FPFeatures.fp_contract);
10635 }
10636
10637 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10638 /// operators are mixed in a way that suggests that the programmer forgot that
10639 /// comparison operators have higher precedence. The most typical example of
10640 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
10641 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10642                                       SourceLocation OpLoc, Expr *LHSExpr,
10643                                       Expr *RHSExpr) {
10644   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10645   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10646
10647   // Check that one of the sides is a comparison operator and the other isn't.
10648   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10649   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10650   if (isLeftComp == isRightComp)
10651     return;
10652
10653   // Bitwise operations are sometimes used as eager logical ops.
10654   // Don't diagnose this.
10655   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10656   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10657   if (isLeftBitwise || isRightBitwise)
10658     return;
10659
10660   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10661                                                    OpLoc)
10662                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
10663   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10664   SourceRange ParensRange = isLeftComp ?
10665       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10666     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10667
10668   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10669     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10670   SuggestParentheses(Self, OpLoc,
10671     Self.PDiag(diag::note_precedence_silence) << OpStr,
10672     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10673   SuggestParentheses(Self, OpLoc,
10674     Self.PDiag(diag::note_precedence_bitwise_first)
10675       << BinaryOperator::getOpcodeStr(Opc),
10676     ParensRange);
10677 }
10678
10679 /// \brief It accepts a '&&' expr that is inside a '||' one.
10680 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10681 /// in parentheses.
10682 static void
10683 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
10684                                        BinaryOperator *Bop) {
10685   assert(Bop->getOpcode() == BO_LAnd);
10686   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10687       << Bop->getSourceRange() << OpLoc;
10688   SuggestParentheses(Self, Bop->getOperatorLoc(),
10689     Self.PDiag(diag::note_precedence_silence)
10690       << Bop->getOpcodeStr(),
10691     Bop->getSourceRange());
10692 }
10693
10694 /// \brief Returns true if the given expression can be evaluated as a constant
10695 /// 'true'.
10696 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10697   bool Res;
10698   return !E->isValueDependent() &&
10699          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
10700 }
10701
10702 /// \brief Returns true if the given expression can be evaluated as a constant
10703 /// 'false'.
10704 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10705   bool Res;
10706   return !E->isValueDependent() &&
10707          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
10708 }
10709
10710 /// \brief Look for '&&' in the left hand of a '||' expr.
10711 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
10712                                              Expr *LHSExpr, Expr *RHSExpr) {
10713   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
10714     if (Bop->getOpcode() == BO_LAnd) {
10715       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
10716       if (EvaluatesAsFalse(S, RHSExpr))
10717         return;
10718       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10719       if (!EvaluatesAsTrue(S, Bop->getLHS()))
10720         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10721     } else if (Bop->getOpcode() == BO_LOr) {
10722       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10723         // If it's "a || b && 1 || c" we didn't warn earlier for
10724         // "a || b && 1", but warn now.
10725         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10726           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10727       }
10728     }
10729   }
10730 }
10731
10732 /// \brief Look for '&&' in the right hand of a '||' expr.
10733 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
10734                                              Expr *LHSExpr, Expr *RHSExpr) {
10735   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
10736     if (Bop->getOpcode() == BO_LAnd) {
10737       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
10738       if (EvaluatesAsFalse(S, LHSExpr))
10739         return;
10740       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10741       if (!EvaluatesAsTrue(S, Bop->getRHS()))
10742         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10743     }
10744   }
10745 }
10746
10747 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
10748 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
10749 /// the '&' expression in parentheses.
10750 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
10751                                          SourceLocation OpLoc, Expr *SubExpr) {
10752   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10753     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
10754       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
10755         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
10756         << Bop->getSourceRange() << OpLoc;
10757       SuggestParentheses(S, Bop->getOperatorLoc(),
10758         S.PDiag(diag::note_precedence_silence)
10759           << Bop->getOpcodeStr(),
10760         Bop->getSourceRange());
10761     }
10762   }
10763 }
10764
10765 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
10766                                     Expr *SubExpr, StringRef Shift) {
10767   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10768     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
10769       StringRef Op = Bop->getOpcodeStr();
10770       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
10771           << Bop->getSourceRange() << OpLoc << Shift << Op;
10772       SuggestParentheses(S, Bop->getOperatorLoc(),
10773           S.PDiag(diag::note_precedence_silence) << Op,
10774           Bop->getSourceRange());
10775     }
10776   }
10777 }
10778
10779 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10780                                  Expr *LHSExpr, Expr *RHSExpr) {
10781   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10782   if (!OCE)
10783     return;
10784
10785   FunctionDecl *FD = OCE->getDirectCallee();
10786   if (!FD || !FD->isOverloadedOperator())
10787     return;
10788
10789   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10790   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10791     return;
10792
10793   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10794       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10795       << (Kind == OO_LessLess);
10796   SuggestParentheses(S, OCE->getOperatorLoc(),
10797                      S.PDiag(diag::note_precedence_silence)
10798                          << (Kind == OO_LessLess ? "<<" : ">>"),
10799                      OCE->getSourceRange());
10800   SuggestParentheses(S, OpLoc,
10801                      S.PDiag(diag::note_evaluate_comparison_first),
10802                      SourceRange(OCE->getArg(1)->getLocStart(),
10803                                  RHSExpr->getLocEnd()));
10804 }
10805
10806 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
10807 /// precedence.
10808 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
10809                                     SourceLocation OpLoc, Expr *LHSExpr,
10810                                     Expr *RHSExpr){
10811   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
10812   if (BinaryOperator::isBitwiseOp(Opc))
10813     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
10814
10815   // Diagnose "arg1 & arg2 | arg3"
10816   if ((Opc == BO_Or || Opc == BO_Xor) &&
10817       !OpLoc.isMacroID()/* Don't warn in macros. */) {
10818     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
10819     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
10820   }
10821
10822   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10823   // We don't warn for 'assert(a || b && "bad")' since this is safe.
10824   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10825     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10826     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
10827   }
10828
10829   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10830       || Opc == BO_Shr) {
10831     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10832     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10833     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
10834   }
10835
10836   // Warn on overloaded shift operators and comparisons, such as:
10837   // cout << 5 == 4;
10838   if (BinaryOperator::isComparisonOp(Opc))
10839     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
10840 }
10841
10842 // Binary Operators.  'Tok' is the token for the operator.
10843 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
10844                             tok::TokenKind Kind,
10845                             Expr *LHSExpr, Expr *RHSExpr) {
10846   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
10847   assert(LHSExpr && "ActOnBinOp(): missing left expression");
10848   assert(RHSExpr && "ActOnBinOp(): missing right expression");
10849
10850   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
10851   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
10852
10853   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
10854 }
10855
10856 /// Build an overloaded binary operator expression in the given scope.
10857 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10858                                        BinaryOperatorKind Opc,
10859                                        Expr *LHS, Expr *RHS) {
10860   // Find all of the overloaded operators visible from this
10861   // point. We perform both an operator-name lookup from the local
10862   // scope and an argument-dependent lookup based on the types of
10863   // the arguments.
10864   UnresolvedSet<16> Functions;
10865   OverloadedOperatorKind OverOp
10866     = BinaryOperator::getOverloadedOperator(Opc);
10867   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
10868     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10869                                    RHS->getType(), Functions);
10870
10871   // Build the (potentially-overloaded, potentially-dependent)
10872   // binary operation.
10873   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10874 }
10875
10876 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
10877                             BinaryOperatorKind Opc,
10878                             Expr *LHSExpr, Expr *RHSExpr) {
10879   // We want to end up calling one of checkPseudoObjectAssignment
10880   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10881   // both expressions are overloadable or either is type-dependent),
10882   // or CreateBuiltinBinOp (in any other case).  We also want to get
10883   // any placeholder types out of the way.
10884
10885   // Handle pseudo-objects in the LHS.
10886   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10887     // Assignments with a pseudo-object l-value need special analysis.
10888     if (pty->getKind() == BuiltinType::PseudoObject &&
10889         BinaryOperator::isAssignmentOp(Opc))
10890       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10891
10892     // Don't resolve overloads if the other type is overloadable.
10893     if (pty->getKind() == BuiltinType::Overload) {
10894       // We can't actually test that if we still have a placeholder,
10895       // though.  Fortunately, none of the exceptions we see in that
10896       // code below are valid when the LHS is an overload set.  Note
10897       // that an overload set can be dependently-typed, but it never
10898       // instantiates to having an overloadable type.
10899       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10900       if (resolvedRHS.isInvalid()) return ExprError();
10901       RHSExpr = resolvedRHS.get();
10902
10903       if (RHSExpr->isTypeDependent() ||
10904           RHSExpr->getType()->isOverloadableType())
10905         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10906     }
10907         
10908     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10909     if (LHS.isInvalid()) return ExprError();
10910     LHSExpr = LHS.get();
10911   }
10912
10913   // Handle pseudo-objects in the RHS.
10914   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10915     // An overload in the RHS can potentially be resolved by the type
10916     // being assigned to.
10917     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10918       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10919         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10920
10921       if (LHSExpr->getType()->isOverloadableType())
10922         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10923
10924       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10925     }
10926
10927     // Don't resolve overloads if the other type is overloadable.
10928     if (pty->getKind() == BuiltinType::Overload &&
10929         LHSExpr->getType()->isOverloadableType())
10930       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10931
10932     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10933     if (!resolvedRHS.isUsable()) return ExprError();
10934     RHSExpr = resolvedRHS.get();
10935   }
10936
10937   if (getLangOpts().CPlusPlus) {
10938     // If either expression is type-dependent, always build an
10939     // overloaded op.
10940     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10941       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10942
10943     // Otherwise, build an overloaded op if either expression has an
10944     // overloadable type.
10945     if (LHSExpr->getType()->isOverloadableType() ||
10946         RHSExpr->getType()->isOverloadableType())
10947       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10948   }
10949
10950   // Build a built-in binary operation.
10951   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10952 }
10953
10954 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
10955                                       UnaryOperatorKind Opc,
10956                                       Expr *InputExpr) {
10957   ExprResult Input = InputExpr;
10958   ExprValueKind VK = VK_RValue;
10959   ExprObjectKind OK = OK_Ordinary;
10960   QualType resultType;
10961   if (getLangOpts().OpenCL) {
10962     // The only legal unary operation for atomics is '&'.
10963     if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
10964       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10965                        << InputExpr->getType()
10966                        << Input.get()->getSourceRange());
10967     }
10968   }
10969   switch (Opc) {
10970   case UO_PreInc:
10971   case UO_PreDec:
10972   case UO_PostInc:
10973   case UO_PostDec:
10974     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10975                                                 OpLoc,
10976                                                 Opc == UO_PreInc ||
10977                                                 Opc == UO_PostInc,
10978                                                 Opc == UO_PreInc ||
10979                                                 Opc == UO_PreDec);
10980     break;
10981   case UO_AddrOf:
10982     resultType = CheckAddressOfOperand(Input, OpLoc);
10983     RecordModifiableNonNullParam(*this, InputExpr);
10984     break;
10985   case UO_Deref: {
10986     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10987     if (Input.isInvalid()) return ExprError();
10988     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
10989     break;
10990   }
10991   case UO_Plus:
10992   case UO_Minus:
10993     Input = UsualUnaryConversions(Input.get());
10994     if (Input.isInvalid()) return ExprError();
10995     resultType = Input.get()->getType();
10996     if (resultType->isDependentType())
10997       break;
10998     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
10999       break;
11000     else if (resultType->isVectorType() &&
11001              // The z vector extensions don't allow + or - with bool vectors.
11002              (!Context.getLangOpts().ZVector ||
11003               resultType->getAs<VectorType>()->getVectorKind() !=
11004               VectorType::AltiVecBool))
11005       break;
11006     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11007              Opc == UO_Plus &&
11008              resultType->isPointerType())
11009       break;
11010
11011     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11012       << resultType << Input.get()->getSourceRange());
11013
11014   case UO_Not: // bitwise complement
11015     Input = UsualUnaryConversions(Input.get());
11016     if (Input.isInvalid())
11017       return ExprError();
11018     resultType = Input.get()->getType();
11019     if (resultType->isDependentType())
11020       break;
11021     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11022     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11023       // C99 does not support '~' for complex conjugation.
11024       Diag(OpLoc, diag::ext_integer_complement_complex)
11025           << resultType << Input.get()->getSourceRange();
11026     else if (resultType->hasIntegerRepresentation())
11027       break;
11028     else if (resultType->isExtVectorType()) {
11029       if (Context.getLangOpts().OpenCL) {
11030         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11031         // on vector float types.
11032         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11033         if (!T->isIntegerType())
11034           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11035                            << resultType << Input.get()->getSourceRange());
11036       }
11037       break;
11038     } else {
11039       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11040                        << resultType << Input.get()->getSourceRange());
11041     }
11042     break;
11043
11044   case UO_LNot: // logical negation
11045     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11046     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11047     if (Input.isInvalid()) return ExprError();
11048     resultType = Input.get()->getType();
11049
11050     // Though we still have to promote half FP to float...
11051     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11052       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11053       resultType = Context.FloatTy;
11054     }
11055
11056     if (resultType->isDependentType())
11057       break;
11058     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11059       // C99 6.5.3.3p1: ok, fallthrough;
11060       if (Context.getLangOpts().CPlusPlus) {
11061         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11062         // operand contextually converted to bool.
11063         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11064                                   ScalarTypeToBooleanCastKind(resultType));
11065       } else if (Context.getLangOpts().OpenCL &&
11066                  Context.getLangOpts().OpenCLVersion < 120) {
11067         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11068         // operate on scalar float types.
11069         if (!resultType->isIntegerType())
11070           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11071                            << resultType << Input.get()->getSourceRange());
11072       }
11073     } else if (resultType->isExtVectorType()) {
11074       if (Context.getLangOpts().OpenCL &&
11075           Context.getLangOpts().OpenCLVersion < 120) {
11076         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11077         // operate on vector float types.
11078         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11079         if (!T->isIntegerType())
11080           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11081                            << resultType << Input.get()->getSourceRange());
11082       }
11083       // Vector logical not returns the signed variant of the operand type.
11084       resultType = GetSignedVectorType(resultType);
11085       break;
11086     } else {
11087       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11088         << resultType << Input.get()->getSourceRange());
11089     }
11090     
11091     // LNot always has type int. C99 6.5.3.3p5.
11092     // In C++, it's bool. C++ 5.3.1p8
11093     resultType = Context.getLogicalOperationType();
11094     break;
11095   case UO_Real:
11096   case UO_Imag:
11097     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11098     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11099     // complex l-values to ordinary l-values and all other values to r-values.
11100     if (Input.isInvalid()) return ExprError();
11101     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11102       if (Input.get()->getValueKind() != VK_RValue &&
11103           Input.get()->getObjectKind() == OK_Ordinary)
11104         VK = Input.get()->getValueKind();
11105     } else if (!getLangOpts().CPlusPlus) {
11106       // In C, a volatile scalar is read by __imag. In C++, it is not.
11107       Input = DefaultLvalueConversion(Input.get());
11108     }
11109     break;
11110   case UO_Extension:
11111   case UO_Coawait:
11112     resultType = Input.get()->getType();
11113     VK = Input.get()->getValueKind();
11114     OK = Input.get()->getObjectKind();
11115     break;
11116   }
11117   if (resultType.isNull() || Input.isInvalid())
11118     return ExprError();
11119
11120   // Check for array bounds violations in the operand of the UnaryOperator,
11121   // except for the '*' and '&' operators that have to be handled specially
11122   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11123   // that are explicitly defined as valid by the standard).
11124   if (Opc != UO_AddrOf && Opc != UO_Deref)
11125     CheckArrayAccess(Input.get());
11126
11127   return new (Context)
11128       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11129 }
11130
11131 /// \brief Determine whether the given expression is a qualified member
11132 /// access expression, of a form that could be turned into a pointer to member
11133 /// with the address-of operator.
11134 static bool isQualifiedMemberAccess(Expr *E) {
11135   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11136     if (!DRE->getQualifier())
11137       return false;
11138     
11139     ValueDecl *VD = DRE->getDecl();
11140     if (!VD->isCXXClassMember())
11141       return false;
11142     
11143     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11144       return true;
11145     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11146       return Method->isInstance();
11147       
11148     return false;
11149   }
11150   
11151   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11152     if (!ULE->getQualifier())
11153       return false;
11154     
11155     for (NamedDecl *D : ULE->decls()) {
11156       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11157         if (Method->isInstance())
11158           return true;
11159       } else {
11160         // Overload set does not contain methods.
11161         break;
11162       }
11163     }
11164     
11165     return false;
11166   }
11167   
11168   return false;
11169 }
11170
11171 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11172                               UnaryOperatorKind Opc, Expr *Input) {
11173   // First things first: handle placeholders so that the
11174   // overloaded-operator check considers the right type.
11175   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11176     // Increment and decrement of pseudo-object references.
11177     if (pty->getKind() == BuiltinType::PseudoObject &&
11178         UnaryOperator::isIncrementDecrementOp(Opc))
11179       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11180
11181     // extension is always a builtin operator.
11182     if (Opc == UO_Extension)
11183       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11184
11185     // & gets special logic for several kinds of placeholder.
11186     // The builtin code knows what to do.
11187     if (Opc == UO_AddrOf &&
11188         (pty->getKind() == BuiltinType::Overload ||
11189          pty->getKind() == BuiltinType::UnknownAny ||
11190          pty->getKind() == BuiltinType::BoundMember))
11191       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11192
11193     // Anything else needs to be handled now.
11194     ExprResult Result = CheckPlaceholderExpr(Input);
11195     if (Result.isInvalid()) return ExprError();
11196     Input = Result.get();
11197   }
11198
11199   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11200       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11201       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11202     // Find all of the overloaded operators visible from this
11203     // point. We perform both an operator-name lookup from the local
11204     // scope and an argument-dependent lookup based on the types of
11205     // the arguments.
11206     UnresolvedSet<16> Functions;
11207     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11208     if (S && OverOp != OO_None)
11209       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11210                                    Functions);
11211
11212     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11213   }
11214
11215   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11216 }
11217
11218 // Unary Operators.  'Tok' is the token for the operator.
11219 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11220                               tok::TokenKind Op, Expr *Input) {
11221   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11222 }
11223
11224 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11225 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11226                                 LabelDecl *TheDecl) {
11227   TheDecl->markUsed(Context);
11228   // Create the AST node.  The address of a label always has type 'void*'.
11229   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11230                                      Context.getPointerType(Context.VoidTy));
11231 }
11232
11233 /// Given the last statement in a statement-expression, check whether
11234 /// the result is a producing expression (like a call to an
11235 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11236 /// release out of the full-expression.  Otherwise, return null.
11237 /// Cannot fail.
11238 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11239   // Should always be wrapped with one of these.
11240   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11241   if (!cleanups) return nullptr;
11242
11243   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11244   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11245     return nullptr;
11246
11247   // Splice out the cast.  This shouldn't modify any interesting
11248   // features of the statement.
11249   Expr *producer = cast->getSubExpr();
11250   assert(producer->getType() == cast->getType());
11251   assert(producer->getValueKind() == cast->getValueKind());
11252   cleanups->setSubExpr(producer);
11253   return cleanups;
11254 }
11255
11256 void Sema::ActOnStartStmtExpr() {
11257   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11258 }
11259
11260 void Sema::ActOnStmtExprError() {
11261   // Note that function is also called by TreeTransform when leaving a
11262   // StmtExpr scope without rebuilding anything.
11263
11264   DiscardCleanupsInEvaluationContext();
11265   PopExpressionEvaluationContext();
11266 }
11267
11268 ExprResult
11269 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11270                     SourceLocation RPLoc) { // "({..})"
11271   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11272   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11273
11274   if (hasAnyUnrecoverableErrorsInThisFunction())
11275     DiscardCleanupsInEvaluationContext();
11276   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11277   PopExpressionEvaluationContext();
11278
11279   // FIXME: there are a variety of strange constraints to enforce here, for
11280   // example, it is not possible to goto into a stmt expression apparently.
11281   // More semantic analysis is needed.
11282
11283   // If there are sub-stmts in the compound stmt, take the type of the last one
11284   // as the type of the stmtexpr.
11285   QualType Ty = Context.VoidTy;
11286   bool StmtExprMayBindToTemp = false;
11287   if (!Compound->body_empty()) {
11288     Stmt *LastStmt = Compound->body_back();
11289     LabelStmt *LastLabelStmt = nullptr;
11290     // If LastStmt is a label, skip down through into the body.
11291     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11292       LastLabelStmt = Label;
11293       LastStmt = Label->getSubStmt();
11294     }
11295
11296     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11297       // Do function/array conversion on the last expression, but not
11298       // lvalue-to-rvalue.  However, initialize an unqualified type.
11299       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11300       if (LastExpr.isInvalid())
11301         return ExprError();
11302       Ty = LastExpr.get()->getType().getUnqualifiedType();
11303
11304       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11305         // In ARC, if the final expression ends in a consume, splice
11306         // the consume out and bind it later.  In the alternate case
11307         // (when dealing with a retainable type), the result
11308         // initialization will create a produce.  In both cases the
11309         // result will be +1, and we'll need to balance that out with
11310         // a bind.
11311         if (Expr *rebuiltLastStmt
11312               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11313           LastExpr = rebuiltLastStmt;
11314         } else {
11315           LastExpr = PerformCopyInitialization(
11316                             InitializedEntity::InitializeResult(LPLoc, 
11317                                                                 Ty,
11318                                                                 false),
11319                                                    SourceLocation(),
11320                                                LastExpr);
11321         }
11322
11323         if (LastExpr.isInvalid())
11324           return ExprError();
11325         if (LastExpr.get() != nullptr) {
11326           if (!LastLabelStmt)
11327             Compound->setLastStmt(LastExpr.get());
11328           else
11329             LastLabelStmt->setSubStmt(LastExpr.get());
11330           StmtExprMayBindToTemp = true;
11331         }
11332       }
11333     }
11334   }
11335
11336   // FIXME: Check that expression type is complete/non-abstract; statement
11337   // expressions are not lvalues.
11338   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11339   if (StmtExprMayBindToTemp)
11340     return MaybeBindToTemporary(ResStmtExpr);
11341   return ResStmtExpr;
11342 }
11343
11344 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11345                                       TypeSourceInfo *TInfo,
11346                                       ArrayRef<OffsetOfComponent> Components,
11347                                       SourceLocation RParenLoc) {
11348   QualType ArgTy = TInfo->getType();
11349   bool Dependent = ArgTy->isDependentType();
11350   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11351   
11352   // We must have at least one component that refers to the type, and the first
11353   // one is known to be a field designator.  Verify that the ArgTy represents
11354   // a struct/union/class.
11355   if (!Dependent && !ArgTy->isRecordType())
11356     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
11357                        << ArgTy << TypeRange);
11358   
11359   // Type must be complete per C99 7.17p3 because a declaring a variable
11360   // with an incomplete type would be ill-formed.
11361   if (!Dependent 
11362       && RequireCompleteType(BuiltinLoc, ArgTy,
11363                              diag::err_offsetof_incomplete_type, TypeRange))
11364     return ExprError();
11365   
11366   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11367   // GCC extension, diagnose them.
11368   // FIXME: This diagnostic isn't actually visible because the location is in
11369   // a system header!
11370   if (Components.size() != 1)
11371     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11372       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11373   
11374   bool DidWarnAboutNonPOD = false;
11375   QualType CurrentType = ArgTy;
11376   SmallVector<OffsetOfNode, 4> Comps;
11377   SmallVector<Expr*, 4> Exprs;
11378   for (const OffsetOfComponent &OC : Components) {
11379     if (OC.isBrackets) {
11380       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11381       if (!CurrentType->isDependentType()) {
11382         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11383         if(!AT)
11384           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11385                            << CurrentType);
11386         CurrentType = AT->getElementType();
11387       } else
11388         CurrentType = Context.DependentTy;
11389       
11390       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11391       if (IdxRval.isInvalid())
11392         return ExprError();
11393       Expr *Idx = IdxRval.get();
11394
11395       // The expression must be an integral expression.
11396       // FIXME: An integral constant expression?
11397       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11398           !Idx->getType()->isIntegerType())
11399         return ExprError(Diag(Idx->getLocStart(),
11400                               diag::err_typecheck_subscript_not_integer)
11401                          << Idx->getSourceRange());
11402
11403       // Record this array index.
11404       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11405       Exprs.push_back(Idx);
11406       continue;
11407     }
11408     
11409     // Offset of a field.
11410     if (CurrentType->isDependentType()) {
11411       // We have the offset of a field, but we can't look into the dependent
11412       // type. Just record the identifier of the field.
11413       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11414       CurrentType = Context.DependentTy;
11415       continue;
11416     }
11417     
11418     // We need to have a complete type to look into.
11419     if (RequireCompleteType(OC.LocStart, CurrentType,
11420                             diag::err_offsetof_incomplete_type))
11421       return ExprError();
11422     
11423     // Look for the designated field.
11424     const RecordType *RC = CurrentType->getAs<RecordType>();
11425     if (!RC) 
11426       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11427                        << CurrentType);
11428     RecordDecl *RD = RC->getDecl();
11429     
11430     // C++ [lib.support.types]p5:
11431     //   The macro offsetof accepts a restricted set of type arguments in this
11432     //   International Standard. type shall be a POD structure or a POD union
11433     //   (clause 9).
11434     // C++11 [support.types]p4:
11435     //   If type is not a standard-layout class (Clause 9), the results are
11436     //   undefined.
11437     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11438       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11439       unsigned DiagID =
11440         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11441                             : diag::ext_offsetof_non_pod_type;
11442
11443       if (!IsSafe && !DidWarnAboutNonPOD &&
11444           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11445                               PDiag(DiagID)
11446                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11447                               << CurrentType))
11448         DidWarnAboutNonPOD = true;
11449     }
11450     
11451     // Look for the field.
11452     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11453     LookupQualifiedName(R, RD);
11454     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11455     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11456     if (!MemberDecl) {
11457       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11458         MemberDecl = IndirectMemberDecl->getAnonField();
11459     }
11460
11461     if (!MemberDecl)
11462       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11463                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
11464                                                               OC.LocEnd));
11465     
11466     // C99 7.17p3:
11467     //   (If the specified member is a bit-field, the behavior is undefined.)
11468     //
11469     // We diagnose this as an error.
11470     if (MemberDecl->isBitField()) {
11471       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11472         << MemberDecl->getDeclName()
11473         << SourceRange(BuiltinLoc, RParenLoc);
11474       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11475       return ExprError();
11476     }
11477
11478     RecordDecl *Parent = MemberDecl->getParent();
11479     if (IndirectMemberDecl)
11480       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11481
11482     // If the member was found in a base class, introduce OffsetOfNodes for
11483     // the base class indirections.
11484     CXXBasePaths Paths;
11485     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11486                       Paths)) {
11487       if (Paths.getDetectedVirtual()) {
11488         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11489           << MemberDecl->getDeclName()
11490           << SourceRange(BuiltinLoc, RParenLoc);
11491         return ExprError();
11492       }
11493
11494       CXXBasePath &Path = Paths.front();
11495       for (const CXXBasePathElement &B : Path)
11496         Comps.push_back(OffsetOfNode(B.Base));
11497     }
11498
11499     if (IndirectMemberDecl) {
11500       for (auto *FI : IndirectMemberDecl->chain()) {
11501         assert(isa<FieldDecl>(FI));
11502         Comps.push_back(OffsetOfNode(OC.LocStart,
11503                                      cast<FieldDecl>(FI), OC.LocEnd));
11504       }
11505     } else
11506       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11507
11508     CurrentType = MemberDecl->getType().getNonReferenceType(); 
11509   }
11510   
11511   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11512                               Comps, Exprs, RParenLoc);
11513 }
11514
11515 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11516                                       SourceLocation BuiltinLoc,
11517                                       SourceLocation TypeLoc,
11518                                       ParsedType ParsedArgTy,
11519                                       ArrayRef<OffsetOfComponent> Components,
11520                                       SourceLocation RParenLoc) {
11521   
11522   TypeSourceInfo *ArgTInfo;
11523   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11524   if (ArgTy.isNull())
11525     return ExprError();
11526
11527   if (!ArgTInfo)
11528     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11529
11530   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11531 }
11532
11533
11534 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11535                                  Expr *CondExpr,
11536                                  Expr *LHSExpr, Expr *RHSExpr,
11537                                  SourceLocation RPLoc) {
11538   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11539
11540   ExprValueKind VK = VK_RValue;
11541   ExprObjectKind OK = OK_Ordinary;
11542   QualType resType;
11543   bool ValueDependent = false;
11544   bool CondIsTrue = false;
11545   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11546     resType = Context.DependentTy;
11547     ValueDependent = true;
11548   } else {
11549     // The conditional expression is required to be a constant expression.
11550     llvm::APSInt condEval(32);
11551     ExprResult CondICE
11552       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11553           diag::err_typecheck_choose_expr_requires_constant, false);
11554     if (CondICE.isInvalid())
11555       return ExprError();
11556     CondExpr = CondICE.get();
11557     CondIsTrue = condEval.getZExtValue();
11558
11559     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11560     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11561
11562     resType = ActiveExpr->getType();
11563     ValueDependent = ActiveExpr->isValueDependent();
11564     VK = ActiveExpr->getValueKind();
11565     OK = ActiveExpr->getObjectKind();
11566   }
11567
11568   return new (Context)
11569       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11570                  CondIsTrue, resType->isDependentType(), ValueDependent);
11571 }
11572
11573 //===----------------------------------------------------------------------===//
11574 // Clang Extensions.
11575 //===----------------------------------------------------------------------===//
11576
11577 /// ActOnBlockStart - This callback is invoked when a block literal is started.
11578 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11579   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11580
11581   if (LangOpts.CPlusPlus) {
11582     Decl *ManglingContextDecl;
11583     if (MangleNumberingContext *MCtx =
11584             getCurrentMangleNumberContext(Block->getDeclContext(),
11585                                           ManglingContextDecl)) {
11586       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11587       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11588     }
11589   }
11590
11591   PushBlockScope(CurScope, Block);
11592   CurContext->addDecl(Block);
11593   if (CurScope)
11594     PushDeclContext(CurScope, Block);
11595   else
11596     CurContext = Block;
11597
11598   getCurBlock()->HasImplicitReturnType = true;
11599
11600   // Enter a new evaluation context to insulate the block from any
11601   // cleanups from the enclosing full-expression.
11602   PushExpressionEvaluationContext(PotentiallyEvaluated);  
11603 }
11604
11605 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11606                                Scope *CurScope) {
11607   assert(ParamInfo.getIdentifier() == nullptr &&
11608          "block-id should have no identifier!");
11609   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11610   BlockScopeInfo *CurBlock = getCurBlock();
11611
11612   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11613   QualType T = Sig->getType();
11614
11615   // FIXME: We should allow unexpanded parameter packs here, but that would,
11616   // in turn, make the block expression contain unexpanded parameter packs.
11617   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11618     // Drop the parameters.
11619     FunctionProtoType::ExtProtoInfo EPI;
11620     EPI.HasTrailingReturn = false;
11621     EPI.TypeQuals |= DeclSpec::TQ_const;
11622     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11623     Sig = Context.getTrivialTypeSourceInfo(T);
11624   }
11625   
11626   // GetTypeForDeclarator always produces a function type for a block
11627   // literal signature.  Furthermore, it is always a FunctionProtoType
11628   // unless the function was written with a typedef.
11629   assert(T->isFunctionType() &&
11630          "GetTypeForDeclarator made a non-function block signature");
11631
11632   // Look for an explicit signature in that function type.
11633   FunctionProtoTypeLoc ExplicitSignature;
11634
11635   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11636   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11637
11638     // Check whether that explicit signature was synthesized by
11639     // GetTypeForDeclarator.  If so, don't save that as part of the
11640     // written signature.
11641     if (ExplicitSignature.getLocalRangeBegin() ==
11642         ExplicitSignature.getLocalRangeEnd()) {
11643       // This would be much cheaper if we stored TypeLocs instead of
11644       // TypeSourceInfos.
11645       TypeLoc Result = ExplicitSignature.getReturnLoc();
11646       unsigned Size = Result.getFullDataSize();
11647       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11648       Sig->getTypeLoc().initializeFullCopy(Result, Size);
11649
11650       ExplicitSignature = FunctionProtoTypeLoc();
11651     }
11652   }
11653
11654   CurBlock->TheDecl->setSignatureAsWritten(Sig);
11655   CurBlock->FunctionType = T;
11656
11657   const FunctionType *Fn = T->getAs<FunctionType>();
11658   QualType RetTy = Fn->getReturnType();
11659   bool isVariadic =
11660     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11661
11662   CurBlock->TheDecl->setIsVariadic(isVariadic);
11663
11664   // Context.DependentTy is used as a placeholder for a missing block
11665   // return type.  TODO:  what should we do with declarators like:
11666   //   ^ * { ... }
11667   // If the answer is "apply template argument deduction"....
11668   if (RetTy != Context.DependentTy) {
11669     CurBlock->ReturnType = RetTy;
11670     CurBlock->TheDecl->setBlockMissingReturnType(false);
11671     CurBlock->HasImplicitReturnType = false;
11672   }
11673
11674   // Push block parameters from the declarator if we had them.
11675   SmallVector<ParmVarDecl*, 8> Params;
11676   if (ExplicitSignature) {
11677     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11678       ParmVarDecl *Param = ExplicitSignature.getParam(I);
11679       if (Param->getIdentifier() == nullptr &&
11680           !Param->isImplicit() &&
11681           !Param->isInvalidDecl() &&
11682           !getLangOpts().CPlusPlus)
11683         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11684       Params.push_back(Param);
11685     }
11686
11687   // Fake up parameter variables if we have a typedef, like
11688   //   ^ fntype { ... }
11689   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
11690     for (const auto &I : Fn->param_types()) {
11691       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11692           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
11693       Params.push_back(Param);
11694     }
11695   }
11696
11697   // Set the parameters on the block decl.
11698   if (!Params.empty()) {
11699     CurBlock->TheDecl->setParams(Params);
11700     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11701                              CurBlock->TheDecl->param_end(),
11702                              /*CheckParameterNames=*/false);
11703   }
11704   
11705   // Finally we can process decl attributes.
11706   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
11707
11708   // Put the parameter variables in scope.
11709   for (auto AI : CurBlock->TheDecl->params()) {
11710     AI->setOwningFunction(CurBlock->TheDecl);
11711
11712     // If this has an identifier, add it to the scope stack.
11713     if (AI->getIdentifier()) {
11714       CheckShadow(CurBlock->TheScope, AI);
11715
11716       PushOnScopeChains(AI, CurBlock->TheScope);
11717     }
11718   }
11719 }
11720
11721 /// ActOnBlockError - If there is an error parsing a block, this callback
11722 /// is invoked to pop the information about the block from the action impl.
11723 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
11724   // Leave the expression-evaluation context.
11725   DiscardCleanupsInEvaluationContext();
11726   PopExpressionEvaluationContext();
11727
11728   // Pop off CurBlock, handle nested blocks.
11729   PopDeclContext();
11730   PopFunctionScopeInfo();
11731 }
11732
11733 /// ActOnBlockStmtExpr - This is called when the body of a block statement
11734 /// literal was successfully completed.  ^(int x){...}
11735 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
11736                                     Stmt *Body, Scope *CurScope) {
11737   // If blocks are disabled, emit an error.
11738   if (!LangOpts.Blocks)
11739     Diag(CaretLoc, diag::err_blocks_disable);
11740
11741   // Leave the expression-evaluation context.
11742   if (hasAnyUnrecoverableErrorsInThisFunction())
11743     DiscardCleanupsInEvaluationContext();
11744   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11745   PopExpressionEvaluationContext();
11746
11747   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
11748
11749   if (BSI->HasImplicitReturnType)
11750     deduceClosureReturnType(*BSI);
11751
11752   PopDeclContext();
11753
11754   QualType RetTy = Context.VoidTy;
11755   if (!BSI->ReturnType.isNull())
11756     RetTy = BSI->ReturnType;
11757
11758   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
11759   QualType BlockTy;
11760
11761   // Set the captured variables on the block.
11762   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11763   SmallVector<BlockDecl::Capture, 4> Captures;
11764   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
11765     if (Cap.isThisCapture())
11766       continue;
11767     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
11768                               Cap.isNested(), Cap.getInitExpr());
11769     Captures.push_back(NewCap);
11770   }
11771   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
11772
11773   // If the user wrote a function type in some form, try to use that.
11774   if (!BSI->FunctionType.isNull()) {
11775     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11776
11777     FunctionType::ExtInfo Ext = FTy->getExtInfo();
11778     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11779     
11780     // Turn protoless block types into nullary block types.
11781     if (isa<FunctionNoProtoType>(FTy)) {
11782       FunctionProtoType::ExtProtoInfo EPI;
11783       EPI.ExtInfo = Ext;
11784       BlockTy = Context.getFunctionType(RetTy, None, EPI);
11785
11786     // Otherwise, if we don't need to change anything about the function type,
11787     // preserve its sugar structure.
11788     } else if (FTy->getReturnType() == RetTy &&
11789                (!NoReturn || FTy->getNoReturnAttr())) {
11790       BlockTy = BSI->FunctionType;
11791
11792     // Otherwise, make the minimal modifications to the function type.
11793     } else {
11794       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
11795       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11796       EPI.TypeQuals = 0; // FIXME: silently?
11797       EPI.ExtInfo = Ext;
11798       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
11799     }
11800
11801   // If we don't have a function type, just build one from nothing.
11802   } else {
11803     FunctionProtoType::ExtProtoInfo EPI;
11804     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
11805     BlockTy = Context.getFunctionType(RetTy, None, EPI);
11806   }
11807
11808   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11809                            BSI->TheDecl->param_end());
11810   BlockTy = Context.getBlockPointerType(BlockTy);
11811
11812   // If needed, diagnose invalid gotos and switches in the block.
11813   if (getCurFunction()->NeedsScopeChecking() &&
11814       !PP.isCodeCompletionEnabled())
11815     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
11816
11817   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
11818
11819   // Try to apply the named return value optimization. We have to check again
11820   // if we can do this, though, because blocks keep return statements around
11821   // to deduce an implicit return type.
11822   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11823       !BSI->TheDecl->isDependentContext())
11824     computeNRVO(Body, BSI);
11825   
11826   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
11827   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11828   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
11829
11830   // If the block isn't obviously global, i.e. it captures anything at
11831   // all, then we need to do a few things in the surrounding context:
11832   if (Result->getBlockDecl()->hasCaptures()) {
11833     // First, this expression has a new cleanup object.
11834     ExprCleanupObjects.push_back(Result->getBlockDecl());
11835     ExprNeedsCleanups = true;
11836
11837     // It also gets a branch-protected scope if any of the captured
11838     // variables needs destruction.
11839     for (const auto &CI : Result->getBlockDecl()->captures()) {
11840       const VarDecl *var = CI.getVariable();
11841       if (var->getType().isDestructedType() != QualType::DK_none) {
11842         getCurFunction()->setHasBranchProtectedScope();
11843         break;
11844       }
11845     }
11846   }
11847
11848   return Result;
11849 }
11850
11851 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
11852                                         Expr *E, ParsedType Ty,
11853                                         SourceLocation RPLoc) {
11854   TypeSourceInfo *TInfo;
11855   GetTypeFromParser(Ty, &TInfo);
11856   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
11857 }
11858
11859 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
11860                                 Expr *E, TypeSourceInfo *TInfo,
11861                                 SourceLocation RPLoc) {
11862   Expr *OrigExpr = E;
11863   bool IsMS = false;
11864
11865   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
11866   // as Microsoft ABI on an actual Microsoft platform, where
11867   // __builtin_ms_va_list and __builtin_va_list are the same.)
11868   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
11869       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
11870     QualType MSVaListType = Context.getBuiltinMSVaListType();
11871     if (Context.hasSameType(MSVaListType, E->getType())) {
11872       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
11873         return ExprError();
11874       IsMS = true;
11875     }
11876   }
11877
11878   // Get the va_list type
11879   QualType VaListType = Context.getBuiltinVaListType();
11880   if (!IsMS) {
11881     if (VaListType->isArrayType()) {
11882       // Deal with implicit array decay; for example, on x86-64,
11883       // va_list is an array, but it's supposed to decay to
11884       // a pointer for va_arg.
11885       VaListType = Context.getArrayDecayedType(VaListType);
11886       // Make sure the input expression also decays appropriately.
11887       ExprResult Result = UsualUnaryConversions(E);
11888       if (Result.isInvalid())
11889         return ExprError();
11890       E = Result.get();
11891     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11892       // If va_list is a record type and we are compiling in C++ mode,
11893       // check the argument using reference binding.
11894       InitializedEntity Entity = InitializedEntity::InitializeParameter(
11895           Context, Context.getLValueReferenceType(VaListType), false);
11896       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11897       if (Init.isInvalid())
11898         return ExprError();
11899       E = Init.getAs<Expr>();
11900     } else {
11901       // Otherwise, the va_list argument must be an l-value because
11902       // it is modified by va_arg.
11903       if (!E->isTypeDependent() &&
11904           CheckForModifiableLvalue(E, BuiltinLoc, *this))
11905         return ExprError();
11906     }
11907   }
11908
11909   if (!IsMS && !E->isTypeDependent() &&
11910       !Context.hasSameType(VaListType, E->getType()))
11911     return ExprError(Diag(E->getLocStart(),
11912                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
11913       << OrigExpr->getType() << E->getSourceRange());
11914
11915   if (!TInfo->getType()->isDependentType()) {
11916     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
11917                             diag::err_second_parameter_to_va_arg_incomplete,
11918                             TInfo->getTypeLoc()))
11919       return ExprError();
11920
11921     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
11922                                TInfo->getType(),
11923                                diag::err_second_parameter_to_va_arg_abstract,
11924                                TInfo->getTypeLoc()))
11925       return ExprError();
11926
11927     if (!TInfo->getType().isPODType(Context)) {
11928       Diag(TInfo->getTypeLoc().getBeginLoc(),
11929            TInfo->getType()->isObjCLifetimeType()
11930              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11931              : diag::warn_second_parameter_to_va_arg_not_pod)
11932         << TInfo->getType()
11933         << TInfo->getTypeLoc().getSourceRange();
11934     }
11935
11936     // Check for va_arg where arguments of the given type will be promoted
11937     // (i.e. this va_arg is guaranteed to have undefined behavior).
11938     QualType PromoteType;
11939     if (TInfo->getType()->isPromotableIntegerType()) {
11940       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11941       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11942         PromoteType = QualType();
11943     }
11944     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11945       PromoteType = Context.DoubleTy;
11946     if (!PromoteType.isNull())
11947       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11948                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11949                           << TInfo->getType()
11950                           << PromoteType
11951                           << TInfo->getTypeLoc().getSourceRange());
11952   }
11953
11954   QualType T = TInfo->getType().getNonLValueExprType(Context);
11955   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
11956 }
11957
11958 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
11959   // The type of __null will be int or long, depending on the size of
11960   // pointers on the target.
11961   QualType Ty;
11962   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11963   if (pw == Context.getTargetInfo().getIntWidth())
11964     Ty = Context.IntTy;
11965   else if (pw == Context.getTargetInfo().getLongWidth())
11966     Ty = Context.LongTy;
11967   else if (pw == Context.getTargetInfo().getLongLongWidth())
11968     Ty = Context.LongLongTy;
11969   else {
11970     llvm_unreachable("I don't know size of pointer!");
11971   }
11972
11973   return new (Context) GNUNullExpr(Ty, TokenLoc);
11974 }
11975
11976 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
11977                                               bool Diagnose) {
11978   if (!getLangOpts().ObjC1)
11979     return false;
11980
11981   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11982   if (!PT)
11983     return false;
11984
11985   if (!PT->isObjCIdType()) {
11986     // Check if the destination is the 'NSString' interface.
11987     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11988     if (!ID || !ID->getIdentifier()->isStr("NSString"))
11989       return false;
11990   }
11991   
11992   // Ignore any parens, implicit casts (should only be
11993   // array-to-pointer decays), and not-so-opaque values.  The last is
11994   // important for making this trigger for property assignments.
11995   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
11996   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11997     if (OV->getSourceExpr())
11998       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11999
12000   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12001   if (!SL || !SL->isAscii())
12002     return false;
12003   if (Diagnose)
12004     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12005       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12006   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12007   return true;
12008 }
12009
12010 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12011                                               const Expr *SrcExpr) {
12012   if (!DstType->isFunctionPointerType() ||
12013       !SrcExpr->getType()->isFunctionType())
12014     return false;
12015
12016   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12017   if (!DRE)
12018     return false;
12019
12020   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12021   if (!FD)
12022     return false;
12023
12024   return !S.checkAddressOfFunctionIsAvailable(FD,
12025                                               /*Complain=*/true,
12026                                               SrcExpr->getLocStart());
12027 }
12028
12029 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12030                                     SourceLocation Loc,
12031                                     QualType DstType, QualType SrcType,
12032                                     Expr *SrcExpr, AssignmentAction Action,
12033                                     bool *Complained) {
12034   if (Complained)
12035     *Complained = false;
12036
12037   // Decode the result (notice that AST's are still created for extensions).
12038   bool CheckInferredResultType = false;
12039   bool isInvalid = false;
12040   unsigned DiagKind = 0;
12041   FixItHint Hint;
12042   ConversionFixItGenerator ConvHints;
12043   bool MayHaveConvFixit = false;
12044   bool MayHaveFunctionDiff = false;
12045   const ObjCInterfaceDecl *IFace = nullptr;
12046   const ObjCProtocolDecl *PDecl = nullptr;
12047
12048   switch (ConvTy) {
12049   case Compatible:
12050       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12051       return false;
12052
12053   case PointerToInt:
12054     DiagKind = diag::ext_typecheck_convert_pointer_int;
12055     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12056     MayHaveConvFixit = true;
12057     break;
12058   case IntToPointer:
12059     DiagKind = diag::ext_typecheck_convert_int_pointer;
12060     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12061     MayHaveConvFixit = true;
12062     break;
12063   case IncompatiblePointer:
12064       DiagKind =
12065         (Action == AA_Passing_CFAudited ?
12066           diag::err_arc_typecheck_convert_incompatible_pointer :
12067           diag::ext_typecheck_convert_incompatible_pointer);
12068     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12069       SrcType->isObjCObjectPointerType();
12070     if (Hint.isNull() && !CheckInferredResultType) {
12071       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12072     }
12073     else if (CheckInferredResultType) {
12074       SrcType = SrcType.getUnqualifiedType();
12075       DstType = DstType.getUnqualifiedType();
12076     }
12077     MayHaveConvFixit = true;
12078     break;
12079   case IncompatiblePointerSign:
12080     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12081     break;
12082   case FunctionVoidPointer:
12083     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12084     break;
12085   case IncompatiblePointerDiscardsQualifiers: {
12086     // Perform array-to-pointer decay if necessary.
12087     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12088
12089     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12090     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12091     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12092       DiagKind = diag::err_typecheck_incompatible_address_space;
12093       break;
12094
12095
12096     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12097       DiagKind = diag::err_typecheck_incompatible_ownership;
12098       break;
12099     }
12100
12101     llvm_unreachable("unknown error case for discarding qualifiers!");
12102     // fallthrough
12103   }
12104   case CompatiblePointerDiscardsQualifiers:
12105     // If the qualifiers lost were because we were applying the
12106     // (deprecated) C++ conversion from a string literal to a char*
12107     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12108     // Ideally, this check would be performed in
12109     // checkPointerTypesForAssignment. However, that would require a
12110     // bit of refactoring (so that the second argument is an
12111     // expression, rather than a type), which should be done as part
12112     // of a larger effort to fix checkPointerTypesForAssignment for
12113     // C++ semantics.
12114     if (getLangOpts().CPlusPlus &&
12115         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12116       return false;
12117     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12118     break;
12119   case IncompatibleNestedPointerQualifiers:
12120     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12121     break;
12122   case IntToBlockPointer:
12123     DiagKind = diag::err_int_to_block_pointer;
12124     break;
12125   case IncompatibleBlockPointer:
12126     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12127     break;
12128   case IncompatibleObjCQualifiedId: {
12129     if (SrcType->isObjCQualifiedIdType()) {
12130       const ObjCObjectPointerType *srcOPT =
12131                 SrcType->getAs<ObjCObjectPointerType>();
12132       for (auto *srcProto : srcOPT->quals()) {
12133         PDecl = srcProto;
12134         break;
12135       }
12136       if (const ObjCInterfaceType *IFaceT =
12137             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12138         IFace = IFaceT->getDecl();
12139     }
12140     else if (DstType->isObjCQualifiedIdType()) {
12141       const ObjCObjectPointerType *dstOPT =
12142         DstType->getAs<ObjCObjectPointerType>();
12143       for (auto *dstProto : dstOPT->quals()) {
12144         PDecl = dstProto;
12145         break;
12146       }
12147       if (const ObjCInterfaceType *IFaceT =
12148             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12149         IFace = IFaceT->getDecl();
12150     }
12151     DiagKind = diag::warn_incompatible_qualified_id;
12152     break;
12153   }
12154   case IncompatibleVectors:
12155     DiagKind = diag::warn_incompatible_vectors;
12156     break;
12157   case IncompatibleObjCWeakRef:
12158     DiagKind = diag::err_arc_weak_unavailable_assign;
12159     break;
12160   case Incompatible:
12161     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12162       if (Complained)
12163         *Complained = true;
12164       return true;
12165     }
12166
12167     DiagKind = diag::err_typecheck_convert_incompatible;
12168     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12169     MayHaveConvFixit = true;
12170     isInvalid = true;
12171     MayHaveFunctionDiff = true;
12172     break;
12173   }
12174
12175   QualType FirstType, SecondType;
12176   switch (Action) {
12177   case AA_Assigning:
12178   case AA_Initializing:
12179     // The destination type comes first.
12180     FirstType = DstType;
12181     SecondType = SrcType;
12182     break;
12183
12184   case AA_Returning:
12185   case AA_Passing:
12186   case AA_Passing_CFAudited:
12187   case AA_Converting:
12188   case AA_Sending:
12189   case AA_Casting:
12190     // The source type comes first.
12191     FirstType = SrcType;
12192     SecondType = DstType;
12193     break;
12194   }
12195
12196   PartialDiagnostic FDiag = PDiag(DiagKind);
12197   if (Action == AA_Passing_CFAudited)
12198     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12199   else
12200     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12201
12202   // If we can fix the conversion, suggest the FixIts.
12203   assert(ConvHints.isNull() || Hint.isNull());
12204   if (!ConvHints.isNull()) {
12205     for (FixItHint &H : ConvHints.Hints)
12206       FDiag << H;
12207   } else {
12208     FDiag << Hint;
12209   }
12210   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12211
12212   if (MayHaveFunctionDiff)
12213     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12214
12215   Diag(Loc, FDiag);
12216   if (DiagKind == diag::warn_incompatible_qualified_id &&
12217       PDecl && IFace && !IFace->hasDefinition())
12218       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12219         << IFace->getName() << PDecl->getName();
12220     
12221   if (SecondType == Context.OverloadTy)
12222     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12223                               FirstType, /*TakingAddress=*/true);
12224
12225   if (CheckInferredResultType)
12226     EmitRelatedResultTypeNote(SrcExpr);
12227
12228   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12229     EmitRelatedResultTypeNoteForReturn(DstType);
12230   
12231   if (Complained)
12232     *Complained = true;
12233   return isInvalid;
12234 }
12235
12236 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12237                                                  llvm::APSInt *Result) {
12238   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12239   public:
12240     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12241       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12242     }
12243   } Diagnoser;
12244   
12245   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12246 }
12247
12248 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12249                                                  llvm::APSInt *Result,
12250                                                  unsigned DiagID,
12251                                                  bool AllowFold) {
12252   class IDDiagnoser : public VerifyICEDiagnoser {
12253     unsigned DiagID;
12254     
12255   public:
12256     IDDiagnoser(unsigned DiagID)
12257       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12258     
12259     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12260       S.Diag(Loc, DiagID) << SR;
12261     }
12262   } Diagnoser(DiagID);
12263   
12264   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12265 }
12266
12267 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12268                                             SourceRange SR) {
12269   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12270 }
12271
12272 ExprResult
12273 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12274                                       VerifyICEDiagnoser &Diagnoser,
12275                                       bool AllowFold) {
12276   SourceLocation DiagLoc = E->getLocStart();
12277
12278   if (getLangOpts().CPlusPlus11) {
12279     // C++11 [expr.const]p5:
12280     //   If an expression of literal class type is used in a context where an
12281     //   integral constant expression is required, then that class type shall
12282     //   have a single non-explicit conversion function to an integral or
12283     //   unscoped enumeration type
12284     ExprResult Converted;
12285     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12286     public:
12287       CXX11ConvertDiagnoser(bool Silent)
12288           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12289                                 Silent, true) {}
12290
12291       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12292                                            QualType T) override {
12293         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12294       }
12295
12296       SemaDiagnosticBuilder diagnoseIncomplete(
12297           Sema &S, SourceLocation Loc, QualType T) override {
12298         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12299       }
12300
12301       SemaDiagnosticBuilder diagnoseExplicitConv(
12302           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12303         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12304       }
12305
12306       SemaDiagnosticBuilder noteExplicitConv(
12307           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12308         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12309                  << ConvTy->isEnumeralType() << ConvTy;
12310       }
12311
12312       SemaDiagnosticBuilder diagnoseAmbiguous(
12313           Sema &S, SourceLocation Loc, QualType T) override {
12314         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12315       }
12316
12317       SemaDiagnosticBuilder noteAmbiguous(
12318           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12319         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12320                  << ConvTy->isEnumeralType() << ConvTy;
12321       }
12322
12323       SemaDiagnosticBuilder diagnoseConversion(
12324           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12325         llvm_unreachable("conversion functions are permitted");
12326       }
12327     } ConvertDiagnoser(Diagnoser.Suppress);
12328
12329     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12330                                                     ConvertDiagnoser);
12331     if (Converted.isInvalid())
12332       return Converted;
12333     E = Converted.get();
12334     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12335       return ExprError();
12336   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12337     // An ICE must be of integral or unscoped enumeration type.
12338     if (!Diagnoser.Suppress)
12339       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12340     return ExprError();
12341   }
12342
12343   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12344   // in the non-ICE case.
12345   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12346     if (Result)
12347       *Result = E->EvaluateKnownConstInt(Context);
12348     return E;
12349   }
12350
12351   Expr::EvalResult EvalResult;
12352   SmallVector<PartialDiagnosticAt, 8> Notes;
12353   EvalResult.Diag = &Notes;
12354
12355   // Try to evaluate the expression, and produce diagnostics explaining why it's
12356   // not a constant expression as a side-effect.
12357   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12358                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12359
12360   // In C++11, we can rely on diagnostics being produced for any expression
12361   // which is not a constant expression. If no diagnostics were produced, then
12362   // this is a constant expression.
12363   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12364     if (Result)
12365       *Result = EvalResult.Val.getInt();
12366     return E;
12367   }
12368
12369   // If our only note is the usual "invalid subexpression" note, just point
12370   // the caret at its location rather than producing an essentially
12371   // redundant note.
12372   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12373         diag::note_invalid_subexpr_in_const_expr) {
12374     DiagLoc = Notes[0].first;
12375     Notes.clear();
12376   }
12377
12378   if (!Folded || !AllowFold) {
12379     if (!Diagnoser.Suppress) {
12380       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12381       for (const PartialDiagnosticAt &Note : Notes)
12382         Diag(Note.first, Note.second);
12383     }
12384
12385     return ExprError();
12386   }
12387
12388   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12389   for (const PartialDiagnosticAt &Note : Notes)
12390     Diag(Note.first, Note.second);
12391
12392   if (Result)
12393     *Result = EvalResult.Val.getInt();
12394   return E;
12395 }
12396
12397 namespace {
12398   // Handle the case where we conclude a expression which we speculatively
12399   // considered to be unevaluated is actually evaluated.
12400   class TransformToPE : public TreeTransform<TransformToPE> {
12401     typedef TreeTransform<TransformToPE> BaseTransform;
12402
12403   public:
12404     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12405
12406     // Make sure we redo semantic analysis
12407     bool AlwaysRebuild() { return true; }
12408
12409     // Make sure we handle LabelStmts correctly.
12410     // FIXME: This does the right thing, but maybe we need a more general
12411     // fix to TreeTransform?
12412     StmtResult TransformLabelStmt(LabelStmt *S) {
12413       S->getDecl()->setStmt(nullptr);
12414       return BaseTransform::TransformLabelStmt(S);
12415     }
12416
12417     // We need to special-case DeclRefExprs referring to FieldDecls which
12418     // are not part of a member pointer formation; normal TreeTransforming
12419     // doesn't catch this case because of the way we represent them in the AST.
12420     // FIXME: This is a bit ugly; is it really the best way to handle this
12421     // case?
12422     //
12423     // Error on DeclRefExprs referring to FieldDecls.
12424     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12425       if (isa<FieldDecl>(E->getDecl()) &&
12426           !SemaRef.isUnevaluatedContext())
12427         return SemaRef.Diag(E->getLocation(),
12428                             diag::err_invalid_non_static_member_use)
12429             << E->getDecl() << E->getSourceRange();
12430
12431       return BaseTransform::TransformDeclRefExpr(E);
12432     }
12433
12434     // Exception: filter out member pointer formation
12435     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12436       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12437         return E;
12438
12439       return BaseTransform::TransformUnaryOperator(E);
12440     }
12441
12442     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12443       // Lambdas never need to be transformed.
12444       return E;
12445     }
12446   };
12447 }
12448
12449 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12450   assert(isUnevaluatedContext() &&
12451          "Should only transform unevaluated expressions");
12452   ExprEvalContexts.back().Context =
12453       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12454   if (isUnevaluatedContext())
12455     return E;
12456   return TransformToPE(*this).TransformExpr(E);
12457 }
12458
12459 void
12460 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12461                                       Decl *LambdaContextDecl,
12462                                       bool IsDecltype) {
12463   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12464                                 ExprNeedsCleanups, LambdaContextDecl,
12465                                 IsDecltype);
12466   ExprNeedsCleanups = false;
12467   if (!MaybeODRUseExprs.empty())
12468     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12469 }
12470
12471 void
12472 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12473                                       ReuseLambdaContextDecl_t,
12474                                       bool IsDecltype) {
12475   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12476   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12477 }
12478
12479 void Sema::PopExpressionEvaluationContext() {
12480   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12481   unsigned NumTypos = Rec.NumTypos;
12482
12483   if (!Rec.Lambdas.empty()) {
12484     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12485       unsigned D;
12486       if (Rec.isUnevaluated()) {
12487         // C++11 [expr.prim.lambda]p2:
12488         //   A lambda-expression shall not appear in an unevaluated operand
12489         //   (Clause 5).
12490         D = diag::err_lambda_unevaluated_operand;
12491       } else {
12492         // C++1y [expr.const]p2:
12493         //   A conditional-expression e is a core constant expression unless the
12494         //   evaluation of e, following the rules of the abstract machine, would
12495         //   evaluate [...] a lambda-expression.
12496         D = diag::err_lambda_in_constant_expression;
12497       }
12498       for (const auto *L : Rec.Lambdas)
12499         Diag(L->getLocStart(), D);
12500     } else {
12501       // Mark the capture expressions odr-used. This was deferred
12502       // during lambda expression creation.
12503       for (auto *Lambda : Rec.Lambdas) {
12504         for (auto *C : Lambda->capture_inits())
12505           MarkDeclarationsReferencedInExpr(C);
12506       }
12507     }
12508   }
12509
12510   // When are coming out of an unevaluated context, clear out any
12511   // temporaries that we may have created as part of the evaluation of
12512   // the expression in that context: they aren't relevant because they
12513   // will never be constructed.
12514   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12515     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12516                              ExprCleanupObjects.end());
12517     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12518     CleanupVarDeclMarking();
12519     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12520   // Otherwise, merge the contexts together.
12521   } else {
12522     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12523     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12524                             Rec.SavedMaybeODRUseExprs.end());
12525   }
12526
12527   // Pop the current expression evaluation context off the stack.
12528   ExprEvalContexts.pop_back();
12529
12530   if (!ExprEvalContexts.empty())
12531     ExprEvalContexts.back().NumTypos += NumTypos;
12532   else
12533     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12534                             "last ExpressionEvaluationContextRecord");
12535 }
12536
12537 void Sema::DiscardCleanupsInEvaluationContext() {
12538   ExprCleanupObjects.erase(
12539          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12540          ExprCleanupObjects.end());
12541   ExprNeedsCleanups = false;
12542   MaybeODRUseExprs.clear();
12543 }
12544
12545 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12546   if (!E->getType()->isVariablyModifiedType())
12547     return E;
12548   return TransformToPotentiallyEvaluated(E);
12549 }
12550
12551 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12552   // Do not mark anything as "used" within a dependent context; wait for
12553   // an instantiation.
12554   if (SemaRef.CurContext->isDependentContext())
12555     return false;
12556
12557   switch (SemaRef.ExprEvalContexts.back().Context) {
12558     case Sema::Unevaluated:
12559     case Sema::UnevaluatedAbstract:
12560       // We are in an expression that is not potentially evaluated; do nothing.
12561       // (Depending on how you read the standard, we actually do need to do
12562       // something here for null pointer constants, but the standard's
12563       // definition of a null pointer constant is completely crazy.)
12564       return false;
12565
12566     case Sema::ConstantEvaluated:
12567     case Sema::PotentiallyEvaluated:
12568       // We are in a potentially evaluated expression (or a constant-expression
12569       // in C++03); we need to do implicit template instantiation, implicitly
12570       // define class members, and mark most declarations as used.
12571       return true;
12572
12573     case Sema::PotentiallyEvaluatedIfUsed:
12574       // Referenced declarations will only be used if the construct in the
12575       // containing expression is used.
12576       return false;
12577   }
12578   llvm_unreachable("Invalid context");
12579 }
12580
12581 /// \brief Mark a function referenced, and check whether it is odr-used
12582 /// (C++ [basic.def.odr]p2, C99 6.9p3)
12583 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12584                                   bool OdrUse) {
12585   assert(Func && "No function?");
12586
12587   Func->setReferenced();
12588
12589   // C++11 [basic.def.odr]p3:
12590   //   A function whose name appears as a potentially-evaluated expression is
12591   //   odr-used if it is the unique lookup result or the selected member of a
12592   //   set of overloaded functions [...].
12593   //
12594   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12595   // can just check that here. Skip the rest of this function if we've already
12596   // marked the function as used.
12597   if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12598       !IsPotentiallyEvaluatedContext(*this)) {
12599     // C++11 [temp.inst]p3:
12600     //   Unless a function template specialization has been explicitly
12601     //   instantiated or explicitly specialized, the function template
12602     //   specialization is implicitly instantiated when the specialization is
12603     //   referenced in a context that requires a function definition to exist.
12604     //
12605     // We consider constexpr function templates to be referenced in a context
12606     // that requires a definition to exist whenever they are referenced.
12607     //
12608     // FIXME: This instantiates constexpr functions too frequently. If this is
12609     // really an unevaluated context (and we're not just in the definition of a
12610     // function template or overload resolution or other cases which we
12611     // incorrectly consider to be unevaluated contexts), and we're not in a
12612     // subexpression which we actually need to evaluate (for instance, a
12613     // template argument, array bound or an expression in a braced-init-list),
12614     // we are not permitted to instantiate this constexpr function definition.
12615     //
12616     // FIXME: This also implicitly defines special members too frequently. They
12617     // are only supposed to be implicitly defined if they are odr-used, but they
12618     // are not odr-used from constant expressions in unevaluated contexts.
12619     // However, they cannot be referenced if they are deleted, and they are
12620     // deleted whenever the implicit definition of the special member would
12621     // fail.
12622     if (!Func->isConstexpr() || Func->getBody())
12623       return;
12624     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12625     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12626       return;
12627   }
12628
12629   // Note that this declaration has been used.
12630   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12631     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12632     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12633       if (Constructor->isDefaultConstructor()) {
12634         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12635           return;
12636         DefineImplicitDefaultConstructor(Loc, Constructor);
12637       } else if (Constructor->isCopyConstructor()) {
12638         DefineImplicitCopyConstructor(Loc, Constructor);
12639       } else if (Constructor->isMoveConstructor()) {
12640         DefineImplicitMoveConstructor(Loc, Constructor);
12641       }
12642     } else if (Constructor->getInheritedConstructor()) {
12643       DefineInheritingConstructor(Loc, Constructor);
12644     }
12645   } else if (CXXDestructorDecl *Destructor =
12646                  dyn_cast<CXXDestructorDecl>(Func)) {
12647     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12648     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12649       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12650         return;
12651       DefineImplicitDestructor(Loc, Destructor);
12652     }
12653     if (Destructor->isVirtual() && getLangOpts().AppleKext)
12654       MarkVTableUsed(Loc, Destructor->getParent());
12655   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
12656     if (MethodDecl->isOverloadedOperator() &&
12657         MethodDecl->getOverloadedOperator() == OO_Equal) {
12658       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12659       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
12660         if (MethodDecl->isCopyAssignmentOperator())
12661           DefineImplicitCopyAssignment(Loc, MethodDecl);
12662         else
12663           DefineImplicitMoveAssignment(Loc, MethodDecl);
12664       }
12665     } else if (isa<CXXConversionDecl>(MethodDecl) &&
12666                MethodDecl->getParent()->isLambda()) {
12667       CXXConversionDecl *Conversion =
12668           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
12669       if (Conversion->isLambdaToBlockPointerConversion())
12670         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12671       else
12672         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
12673     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
12674       MarkVTableUsed(Loc, MethodDecl->getParent());
12675   }
12676
12677   // Recursive functions should be marked when used from another function.
12678   // FIXME: Is this really right?
12679   if (CurContext == Func) return;
12680
12681   // Resolve the exception specification for any function which is
12682   // used: CodeGen will need it.
12683   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
12684   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12685     ResolveExceptionSpec(Loc, FPT);
12686
12687   if (!OdrUse) return;
12688
12689   // Implicit instantiation of function templates and member functions of
12690   // class templates.
12691   if (Func->isImplicitlyInstantiable()) {
12692     bool AlreadyInstantiated = false;
12693     SourceLocation PointOfInstantiation = Loc;
12694     if (FunctionTemplateSpecializationInfo *SpecInfo
12695                               = Func->getTemplateSpecializationInfo()) {
12696       if (SpecInfo->getPointOfInstantiation().isInvalid())
12697         SpecInfo->setPointOfInstantiation(Loc);
12698       else if (SpecInfo->getTemplateSpecializationKind()
12699                  == TSK_ImplicitInstantiation) {
12700         AlreadyInstantiated = true;
12701         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12702       }
12703     } else if (MemberSpecializationInfo *MSInfo
12704                                 = Func->getMemberSpecializationInfo()) {
12705       if (MSInfo->getPointOfInstantiation().isInvalid())
12706         MSInfo->setPointOfInstantiation(Loc);
12707       else if (MSInfo->getTemplateSpecializationKind()
12708                  == TSK_ImplicitInstantiation) {
12709         AlreadyInstantiated = true;
12710         PointOfInstantiation = MSInfo->getPointOfInstantiation();
12711       }
12712     }
12713
12714     if (!AlreadyInstantiated || Func->isConstexpr()) {
12715       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
12716           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12717           ActiveTemplateInstantiations.size())
12718         PendingLocalImplicitInstantiations.push_back(
12719             std::make_pair(Func, PointOfInstantiation));
12720       else if (Func->isConstexpr())
12721         // Do not defer instantiations of constexpr functions, to avoid the
12722         // expression evaluator needing to call back into Sema if it sees a
12723         // call to such a function.
12724         InstantiateFunctionDefinition(PointOfInstantiation, Func);
12725       else {
12726         PendingInstantiations.push_back(std::make_pair(Func,
12727                                                        PointOfInstantiation));
12728         // Notify the consumer that a function was implicitly instantiated.
12729         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12730       }
12731     }
12732   } else {
12733     // Walk redefinitions, as some of them may be instantiable.
12734     for (auto i : Func->redecls()) {
12735       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
12736         MarkFunctionReferenced(Loc, i);
12737     }
12738   }
12739
12740   // Keep track of used but undefined functions.
12741   if (!Func->isDefined()) {
12742     if (mightHaveNonExternalLinkage(Func))
12743       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12744     else if (Func->getMostRecentDecl()->isInlined() &&
12745              !LangOpts.GNUInline &&
12746              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12747       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12748   }
12749
12750   // Normally the most current decl is marked used while processing the use and
12751   // any subsequent decls are marked used by decl merging. This fails with
12752   // template instantiation since marking can happen at the end of the file
12753   // and, because of the two phase lookup, this function is called with at
12754   // decl in the middle of a decl chain. We loop to maintain the invariant
12755   // that once a decl is used, all decls after it are also used.
12756   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
12757     F->markUsed(Context);
12758     if (F == Func)
12759       break;
12760   }
12761 }
12762
12763 static void
12764 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12765                                    VarDecl *var, DeclContext *DC) {
12766   DeclContext *VarDC = var->getDeclContext();
12767
12768   //  If the parameter still belongs to the translation unit, then
12769   //  we're actually just using one parameter in the declaration of
12770   //  the next.
12771   if (isa<ParmVarDecl>(var) &&
12772       isa<TranslationUnitDecl>(VarDC))
12773     return;
12774
12775   // For C code, don't diagnose about capture if we're not actually in code
12776   // right now; it's impossible to write a non-constant expression outside of
12777   // function context, so we'll get other (more useful) diagnostics later.
12778   //
12779   // For C++, things get a bit more nasty... it would be nice to suppress this
12780   // diagnostic for certain cases like using a local variable in an array bound
12781   // for a member of a local class, but the correct predicate is not obvious.
12782   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
12783     return;
12784
12785   if (isa<CXXMethodDecl>(VarDC) &&
12786       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12787     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12788       << var->getIdentifier();
12789   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12790     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12791       << var->getIdentifier() << fn->getDeclName();
12792   } else if (isa<BlockDecl>(VarDC)) {
12793     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12794       << var->getIdentifier();
12795   } else {
12796     // FIXME: Is there any other context where a local variable can be
12797     // declared?
12798     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12799       << var->getIdentifier();
12800   }
12801
12802   S.Diag(var->getLocation(), diag::note_entity_declared_at)
12803       << var->getIdentifier();
12804
12805   // FIXME: Add additional diagnostic info about class etc. which prevents
12806   // capture.
12807 }
12808
12809  
12810 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
12811                                       bool &SubCapturesAreNested,
12812                                       QualType &CaptureType, 
12813                                       QualType &DeclRefType) {
12814    // Check whether we've already captured it.
12815   if (CSI->CaptureMap.count(Var)) {
12816     // If we found a capture, any subcaptures are nested.
12817     SubCapturesAreNested = true;
12818       
12819     // Retrieve the capture type for this variable.
12820     CaptureType = CSI->getCapture(Var).getCaptureType();
12821       
12822     // Compute the type of an expression that refers to this variable.
12823     DeclRefType = CaptureType.getNonReferenceType();
12824
12825     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
12826     // are mutable in the sense that user can change their value - they are
12827     // private instances of the captured declarations.
12828     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12829     if (Cap.isCopyCapture() &&
12830         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
12831         !(isa<CapturedRegionScopeInfo>(CSI) &&
12832           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
12833       DeclRefType.addConst();
12834     return true;
12835   }
12836   return false;
12837 }
12838
12839 // Only block literals, captured statements, and lambda expressions can
12840 // capture; other scopes don't work.
12841 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
12842                                  SourceLocation Loc, 
12843                                  const bool Diagnose, Sema &S) {
12844   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12845     return getLambdaAwareParentOfDeclContext(DC);
12846   else if (Var->hasLocalStorage()) {
12847     if (Diagnose)
12848        diagnoseUncapturableValueReference(S, Loc, Var, DC);
12849   }
12850   return nullptr;
12851 }
12852
12853 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
12854 // certain types of variables (unnamed, variably modified types etc.)
12855 // so check for eligibility.
12856 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
12857                                  SourceLocation Loc, 
12858                                  const bool Diagnose, Sema &S) {
12859
12860   bool IsBlock = isa<BlockScopeInfo>(CSI);
12861   bool IsLambda = isa<LambdaScopeInfo>(CSI);
12862
12863   // Lambdas are not allowed to capture unnamed variables
12864   // (e.g. anonymous unions).
12865   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12866   // assuming that's the intent.
12867   if (IsLambda && !Var->getDeclName()) {
12868     if (Diagnose) {
12869       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12870       S.Diag(Var->getLocation(), diag::note_declared_at);
12871     }
12872     return false;
12873   }
12874
12875   // Prohibit variably-modified types in blocks; they're difficult to deal with.
12876   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
12877     if (Diagnose) {
12878       S.Diag(Loc, diag::err_ref_vm_type);
12879       S.Diag(Var->getLocation(), diag::note_previous_decl) 
12880         << Var->getDeclName();
12881     }
12882     return false;
12883   }
12884   // Prohibit structs with flexible array members too.
12885   // We cannot capture what is in the tail end of the struct.
12886   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12887     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12888       if (Diagnose) {
12889         if (IsBlock)
12890           S.Diag(Loc, diag::err_ref_flexarray_type);
12891         else
12892           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12893             << Var->getDeclName();
12894         S.Diag(Var->getLocation(), diag::note_previous_decl)
12895           << Var->getDeclName();
12896       }
12897       return false;
12898     }
12899   }
12900   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12901   // Lambdas and captured statements are not allowed to capture __block
12902   // variables; they don't support the expected semantics.
12903   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12904     if (Diagnose) {
12905       S.Diag(Loc, diag::err_capture_block_variable)
12906         << Var->getDeclName() << !IsLambda;
12907       S.Diag(Var->getLocation(), diag::note_previous_decl)
12908         << Var->getDeclName();
12909     }
12910     return false;
12911   }
12912
12913   return true;
12914 }
12915
12916 // Returns true if the capture by block was successful.
12917 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
12918                                  SourceLocation Loc, 
12919                                  const bool BuildAndDiagnose, 
12920                                  QualType &CaptureType,
12921                                  QualType &DeclRefType, 
12922                                  const bool Nested,
12923                                  Sema &S) {
12924   Expr *CopyExpr = nullptr;
12925   bool ByRef = false;
12926       
12927   // Blocks are not allowed to capture arrays.
12928   if (CaptureType->isArrayType()) {
12929     if (BuildAndDiagnose) {
12930       S.Diag(Loc, diag::err_ref_array_type);
12931       S.Diag(Var->getLocation(), diag::note_previous_decl) 
12932       << Var->getDeclName();
12933     }
12934     return false;
12935   }
12936
12937   // Forbid the block-capture of autoreleasing variables.
12938   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12939     if (BuildAndDiagnose) {
12940       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12941         << /*block*/ 0;
12942       S.Diag(Var->getLocation(), diag::note_previous_decl)
12943         << Var->getDeclName();
12944     }
12945     return false;
12946   }
12947   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12948   if (HasBlocksAttr || CaptureType->isReferenceType()) {
12949     // Block capture by reference does not change the capture or
12950     // declaration reference types.
12951     ByRef = true;
12952   } else {
12953     // Block capture by copy introduces 'const'.
12954     CaptureType = CaptureType.getNonReferenceType().withConst();
12955     DeclRefType = CaptureType;
12956                 
12957     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12958       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12959         // The capture logic needs the destructor, so make sure we mark it.
12960         // Usually this is unnecessary because most local variables have
12961         // their destructors marked at declaration time, but parameters are
12962         // an exception because it's technically only the call site that
12963         // actually requires the destructor.
12964         if (isa<ParmVarDecl>(Var))
12965           S.FinalizeVarWithDestructor(Var, Record);
12966
12967         // Enter a new evaluation context to insulate the copy
12968         // full-expression.
12969         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12970
12971         // According to the blocks spec, the capture of a variable from
12972         // the stack requires a const copy constructor.  This is not true
12973         // of the copy/move done to move a __block variable to the heap.
12974         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12975                                                   DeclRefType.withConst(), 
12976                                                   VK_LValue, Loc);
12977             
12978         ExprResult Result
12979           = S.PerformCopyInitialization(
12980               InitializedEntity::InitializeBlock(Var->getLocation(),
12981                                                   CaptureType, false),
12982               Loc, DeclRef);
12983             
12984         // Build a full-expression copy expression if initialization
12985         // succeeded and used a non-trivial constructor.  Recover from
12986         // errors by pretending that the copy isn't necessary.
12987         if (!Result.isInvalid() &&
12988             !cast<CXXConstructExpr>(Result.get())->getConstructor()
12989                 ->isTrivial()) {
12990           Result = S.MaybeCreateExprWithCleanups(Result);
12991           CopyExpr = Result.get();
12992         }
12993       }
12994     }
12995   }
12996
12997   // Actually capture the variable.
12998   if (BuildAndDiagnose)
12999     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
13000                     SourceLocation(), CaptureType, CopyExpr);
13001
13002   return true;
13003
13004 }
13005
13006
13007 /// \brief Capture the given variable in the captured region.
13008 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13009                                     VarDecl *Var, 
13010                                     SourceLocation Loc, 
13011                                     const bool BuildAndDiagnose, 
13012                                     QualType &CaptureType,
13013                                     QualType &DeclRefType, 
13014                                     const bool RefersToCapturedVariable,
13015                                     Sema &S) {
13016   
13017   // By default, capture variables by reference.
13018   bool ByRef = true;
13019   // Using an LValue reference type is consistent with Lambdas (see below).
13020   if (S.getLangOpts().OpenMP) {
13021     ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
13022     if (S.IsOpenMPCapturedVar(Var))
13023       DeclRefType = DeclRefType.getUnqualifiedType();
13024   }
13025
13026   if (ByRef)
13027     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13028   else
13029     CaptureType = DeclRefType;
13030
13031   Expr *CopyExpr = nullptr;
13032   if (BuildAndDiagnose) {
13033     // The current implementation assumes that all variables are captured
13034     // by references. Since there is no capture by copy, no expression
13035     // evaluation will be needed.
13036     RecordDecl *RD = RSI->TheRecordDecl;
13037
13038     FieldDecl *Field
13039       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13040                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13041                           nullptr, false, ICIS_NoInit);
13042     Field->setImplicit(true);
13043     Field->setAccess(AS_private);
13044     RD->addDecl(Field);
13045  
13046     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13047                                             DeclRefType, VK_LValue, Loc);
13048     Var->setReferenced(true);
13049     Var->markUsed(S.Context);
13050   }
13051
13052   // Actually capture the variable.
13053   if (BuildAndDiagnose)
13054     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13055                     SourceLocation(), CaptureType, CopyExpr);
13056   
13057   
13058   return true;
13059 }
13060
13061 /// \brief Create a field within the lambda class for the variable
13062 /// being captured.
13063 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
13064                                     QualType FieldType, QualType DeclRefType,
13065                                     SourceLocation Loc,
13066                                     bool RefersToCapturedVariable) {
13067   CXXRecordDecl *Lambda = LSI->Lambda;
13068
13069   // Build the non-static data member.
13070   FieldDecl *Field
13071     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13072                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13073                         nullptr, false, ICIS_NoInit);
13074   Field->setImplicit(true);
13075   Field->setAccess(AS_private);
13076   Lambda->addDecl(Field);
13077 }
13078
13079 /// \brief Capture the given variable in the lambda.
13080 static bool captureInLambda(LambdaScopeInfo *LSI,
13081                             VarDecl *Var, 
13082                             SourceLocation Loc, 
13083                             const bool BuildAndDiagnose, 
13084                             QualType &CaptureType,
13085                             QualType &DeclRefType, 
13086                             const bool RefersToCapturedVariable,
13087                             const Sema::TryCaptureKind Kind, 
13088                             SourceLocation EllipsisLoc,
13089                             const bool IsTopScope,
13090                             Sema &S) {
13091
13092   // Determine whether we are capturing by reference or by value.
13093   bool ByRef = false;
13094   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13095     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13096   } else {
13097     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13098   }
13099     
13100   // Compute the type of the field that will capture this variable.
13101   if (ByRef) {
13102     // C++11 [expr.prim.lambda]p15:
13103     //   An entity is captured by reference if it is implicitly or
13104     //   explicitly captured but not captured by copy. It is
13105     //   unspecified whether additional unnamed non-static data
13106     //   members are declared in the closure type for entities
13107     //   captured by reference.
13108     //
13109     // FIXME: It is not clear whether we want to build an lvalue reference
13110     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13111     // to do the former, while EDG does the latter. Core issue 1249 will 
13112     // clarify, but for now we follow GCC because it's a more permissive and
13113     // easily defensible position.
13114     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13115   } else {
13116     // C++11 [expr.prim.lambda]p14:
13117     //   For each entity captured by copy, an unnamed non-static
13118     //   data member is declared in the closure type. The
13119     //   declaration order of these members is unspecified. The type
13120     //   of such a data member is the type of the corresponding
13121     //   captured entity if the entity is not a reference to an
13122     //   object, or the referenced type otherwise. [Note: If the
13123     //   captured entity is a reference to a function, the
13124     //   corresponding data member is also a reference to a
13125     //   function. - end note ]
13126     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13127       if (!RefType->getPointeeType()->isFunctionType())
13128         CaptureType = RefType->getPointeeType();
13129     }
13130
13131     // Forbid the lambda copy-capture of autoreleasing variables.
13132     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13133       if (BuildAndDiagnose) {
13134         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13135         S.Diag(Var->getLocation(), diag::note_previous_decl)
13136           << Var->getDeclName();
13137       }
13138       return false;
13139     }
13140
13141     // Make sure that by-copy captures are of a complete and non-abstract type.
13142     if (BuildAndDiagnose) {
13143       if (!CaptureType->isDependentType() &&
13144           S.RequireCompleteType(Loc, CaptureType,
13145                                 diag::err_capture_of_incomplete_type,
13146                                 Var->getDeclName()))
13147         return false;
13148
13149       if (S.RequireNonAbstractType(Loc, CaptureType,
13150                                    diag::err_capture_of_abstract_type))
13151         return false;
13152     }
13153   }
13154
13155   // Capture this variable in the lambda.
13156   if (BuildAndDiagnose)
13157     addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
13158                             RefersToCapturedVariable);
13159     
13160   // Compute the type of a reference to this captured variable.
13161   if (ByRef)
13162     DeclRefType = CaptureType.getNonReferenceType();
13163   else {
13164     // C++ [expr.prim.lambda]p5:
13165     //   The closure type for a lambda-expression has a public inline 
13166     //   function call operator [...]. This function call operator is 
13167     //   declared const (9.3.1) if and only if the lambda-expression’s 
13168     //   parameter-declaration-clause is not followed by mutable.
13169     DeclRefType = CaptureType.getNonReferenceType();
13170     if (!LSI->Mutable && !CaptureType->isReferenceType())
13171       DeclRefType.addConst();      
13172   }
13173     
13174   // Add the capture.
13175   if (BuildAndDiagnose)
13176     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
13177                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13178       
13179   return true;
13180 }
13181
13182 bool Sema::tryCaptureVariable(
13183     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13184     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13185     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13186   // An init-capture is notionally from the context surrounding its
13187   // declaration, but its parent DC is the lambda class.
13188   DeclContext *VarDC = Var->getDeclContext();
13189   if (Var->isInitCapture())
13190     VarDC = VarDC->getParent();
13191   
13192   DeclContext *DC = CurContext;
13193   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
13194       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
13195   // We need to sync up the Declaration Context with the
13196   // FunctionScopeIndexToStopAt
13197   if (FunctionScopeIndexToStopAt) {
13198     unsigned FSIndex = FunctionScopes.size() - 1;
13199     while (FSIndex != MaxFunctionScopesIndex) {
13200       DC = getLambdaAwareParentOfDeclContext(DC);
13201       --FSIndex;
13202     }
13203   }
13204
13205   
13206   // If the variable is declared in the current context, there is no need to
13207   // capture it.
13208   if (VarDC == DC) return true;
13209
13210   // Capture global variables if it is required to use private copy of this
13211   // variable.
13212   bool IsGlobal = !Var->hasLocalStorage();
13213   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
13214     return true;
13215
13216   // Walk up the stack to determine whether we can capture the variable,
13217   // performing the "simple" checks that don't depend on type. We stop when
13218   // we've either hit the declared scope of the variable or find an existing
13219   // capture of that variable.  We start from the innermost capturing-entity
13220   // (the DC) and ensure that all intervening capturing-entities 
13221   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13222   // declcontext can either capture the variable or have already captured
13223   // the variable.
13224   CaptureType = Var->getType();
13225   DeclRefType = CaptureType.getNonReferenceType();
13226   bool Nested = false;
13227   bool Explicit = (Kind != TryCapture_Implicit);
13228   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13229   unsigned OpenMPLevel = 0;
13230   do {
13231     // Only block literals, captured statements, and lambda expressions can
13232     // capture; other scopes don't work.
13233     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
13234                                                               ExprLoc, 
13235                                                               BuildAndDiagnose,
13236                                                               *this);
13237     // We need to check for the parent *first* because, if we *have*
13238     // private-captured a global variable, we need to recursively capture it in
13239     // intermediate blocks, lambdas, etc.
13240     if (!ParentDC) {
13241       if (IsGlobal) {
13242         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13243         break;
13244       }
13245       return true;
13246     }
13247
13248     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13249     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13250
13251
13252     // Check whether we've already captured it.
13253     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
13254                                              DeclRefType)) 
13255       break;
13256     // If we are instantiating a generic lambda call operator body, 
13257     // we do not want to capture new variables.  What was captured
13258     // during either a lambdas transformation or initial parsing
13259     // should be used. 
13260     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13261       if (BuildAndDiagnose) {
13262         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
13263         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13264           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13265           Diag(Var->getLocation(), diag::note_previous_decl) 
13266              << Var->getDeclName();
13267           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
13268         } else
13269           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13270       }
13271       return true;
13272     }
13273     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13274     // certain types of variables (unnamed, variably modified types etc.)
13275     // so check for eligibility.
13276     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13277        return true;
13278
13279     // Try to capture variable-length arrays types.
13280     if (Var->getType()->isVariablyModifiedType()) {
13281       // We're going to walk down into the type and look for VLA
13282       // expressions.
13283       QualType QTy = Var->getType();
13284       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13285         QTy = PVD->getOriginalType();
13286       captureVariablyModifiedType(Context, QTy, CSI);
13287     }
13288
13289     if (getLangOpts().OpenMP) {
13290       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13291         // OpenMP private variables should not be captured in outer scope, so
13292         // just break here. Similarly, global variables that are captured in a
13293         // target region should not be captured outside the scope of the region.
13294         if (RSI->CapRegionKind == CR_OpenMP) {
13295           auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel);
13296           // When we detect target captures we are looking from inside the
13297           // target region, therefore we need to propagate the capture from the
13298           // enclosing region. Therefore, the capture is not initially nested.
13299           if (isTargetCap)
13300             FunctionScopesIndex--;
13301
13302           if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) {
13303             Nested = !isTargetCap;
13304             DeclRefType = DeclRefType.getUnqualifiedType();
13305             CaptureType = Context.getLValueReferenceType(DeclRefType);
13306             break;
13307           }
13308           ++OpenMPLevel;
13309         }
13310       }
13311     }
13312     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13313       // No capture-default, and this is not an explicit capture 
13314       // so cannot capture this variable.  
13315       if (BuildAndDiagnose) {
13316         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13317         Diag(Var->getLocation(), diag::note_previous_decl) 
13318           << Var->getDeclName();
13319         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13320              diag::note_lambda_decl);
13321         // FIXME: If we error out because an outer lambda can not implicitly
13322         // capture a variable that an inner lambda explicitly captures, we
13323         // should have the inner lambda do the explicit capture - because
13324         // it makes for cleaner diagnostics later.  This would purely be done
13325         // so that the diagnostic does not misleadingly claim that a variable 
13326         // can not be captured by a lambda implicitly even though it is captured 
13327         // explicitly.  Suggestion:
13328         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
13329         //    at the function head
13330         //  - cache the StartingDeclContext - this must be a lambda 
13331         //  - captureInLambda in the innermost lambda the variable.
13332       }
13333       return true;
13334     }
13335
13336     FunctionScopesIndex--;
13337     DC = ParentDC;
13338     Explicit = false;
13339   } while (!VarDC->Equals(DC));
13340
13341   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13342   // computing the type of the capture at each step, checking type-specific 
13343   // requirements, and adding captures if requested. 
13344   // If the variable had already been captured previously, we start capturing 
13345   // at the lambda nested within that one.   
13346   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
13347        ++I) {
13348     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13349     
13350     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13351       if (!captureInBlock(BSI, Var, ExprLoc, 
13352                           BuildAndDiagnose, CaptureType, 
13353                           DeclRefType, Nested, *this))
13354         return true;
13355       Nested = true;
13356     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13357       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
13358                                    BuildAndDiagnose, CaptureType, 
13359                                    DeclRefType, Nested, *this))
13360         return true;
13361       Nested = true;
13362     } else {
13363       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13364       if (!captureInLambda(LSI, Var, ExprLoc, 
13365                            BuildAndDiagnose, CaptureType, 
13366                            DeclRefType, Nested, Kind, EllipsisLoc, 
13367                             /*IsTopScope*/I == N - 1, *this))
13368         return true;
13369       Nested = true;
13370     }
13371   }
13372   return false;
13373 }
13374
13375 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13376                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
13377   QualType CaptureType;
13378   QualType DeclRefType;
13379   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13380                             /*BuildAndDiagnose=*/true, CaptureType,
13381                             DeclRefType, nullptr);
13382 }
13383
13384 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13385   QualType CaptureType;
13386   QualType DeclRefType;
13387   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13388                              /*BuildAndDiagnose=*/false, CaptureType,
13389                              DeclRefType, nullptr);
13390 }
13391
13392 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13393   QualType CaptureType;
13394   QualType DeclRefType;
13395   
13396   // Determine whether we can capture this variable.
13397   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13398                          /*BuildAndDiagnose=*/false, CaptureType, 
13399                          DeclRefType, nullptr))
13400     return QualType();
13401
13402   return DeclRefType;
13403 }
13404
13405
13406
13407 // If either the type of the variable or the initializer is dependent, 
13408 // return false. Otherwise, determine whether the variable is a constant
13409 // expression. Use this if you need to know if a variable that might or
13410 // might not be dependent is truly a constant expression.
13411 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
13412     ASTContext &Context) {
13413  
13414   if (Var->getType()->isDependentType()) 
13415     return false;
13416   const VarDecl *DefVD = nullptr;
13417   Var->getAnyInitializer(DefVD);
13418   if (!DefVD) 
13419     return false;
13420   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13421   Expr *Init = cast<Expr>(Eval->Value);
13422   if (Init->isValueDependent()) 
13423     return false;
13424   return IsVariableAConstantExpression(Var, Context); 
13425 }
13426
13427
13428 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13429   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
13430   // an object that satisfies the requirements for appearing in a
13431   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13432   // is immediately applied."  This function handles the lvalue-to-rvalue
13433   // conversion part.
13434   MaybeODRUseExprs.erase(E->IgnoreParens());
13435   
13436   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13437   // to a variable that is a constant expression, and if so, identify it as
13438   // a reference to a variable that does not involve an odr-use of that 
13439   // variable. 
13440   if (LambdaScopeInfo *LSI = getCurLambda()) {
13441     Expr *SansParensExpr = E->IgnoreParens();
13442     VarDecl *Var = nullptr;
13443     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
13444       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13445     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13446       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13447     
13448     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
13449       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
13450   }
13451 }
13452
13453 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13454   Res = CorrectDelayedTyposInExpr(Res);
13455
13456   if (!Res.isUsable())
13457     return Res;
13458
13459   // If a constant-expression is a reference to a variable where we delay
13460   // deciding whether it is an odr-use, just assume we will apply the
13461   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13462   // (a non-type template argument), we have special handling anyway.
13463   UpdateMarkingForLValueToRValue(Res.get());
13464   return Res;
13465 }
13466
13467 void Sema::CleanupVarDeclMarking() {
13468   for (Expr *E : MaybeODRUseExprs) {
13469     VarDecl *Var;
13470     SourceLocation Loc;
13471     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13472       Var = cast<VarDecl>(DRE->getDecl());
13473       Loc = DRE->getLocation();
13474     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13475       Var = cast<VarDecl>(ME->getMemberDecl());
13476       Loc = ME->getMemberLoc();
13477     } else {
13478       llvm_unreachable("Unexpected expression");
13479     }
13480
13481     MarkVarDeclODRUsed(Var, Loc, *this,
13482                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13483   }
13484
13485   MaybeODRUseExprs.clear();
13486 }
13487
13488
13489 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13490                                     VarDecl *Var, Expr *E) {
13491   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13492          "Invalid Expr argument to DoMarkVarDeclReferenced");
13493   Var->setReferenced();
13494
13495   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13496   bool MarkODRUsed = true;
13497
13498   // If the context is not potentially evaluated, this is not an odr-use and
13499   // does not trigger instantiation.
13500   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13501     if (SemaRef.isUnevaluatedContext())
13502       return;
13503
13504     // If we don't yet know whether this context is going to end up being an
13505     // evaluated context, and we're referencing a variable from an enclosing
13506     // scope, add a potential capture.
13507     //
13508     // FIXME: Is this necessary? These contexts are only used for default
13509     // arguments, where local variables can't be used.
13510     const bool RefersToEnclosingScope =
13511         (SemaRef.CurContext != Var->getDeclContext() &&
13512          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13513     if (RefersToEnclosingScope) {
13514       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13515         // If a variable could potentially be odr-used, defer marking it so
13516         // until we finish analyzing the full expression for any
13517         // lvalue-to-rvalue
13518         // or discarded value conversions that would obviate odr-use.
13519         // Add it to the list of potential captures that will be analyzed
13520         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13521         // unless the variable is a reference that was initialized by a constant
13522         // expression (this will never need to be captured or odr-used).
13523         assert(E && "Capture variable should be used in an expression.");
13524         if (!Var->getType()->isReferenceType() ||
13525             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13526           LSI->addPotentialCapture(E->IgnoreParens());
13527       }
13528     }
13529
13530     if (!isTemplateInstantiation(TSK))
13531       return;
13532
13533     // Instantiate, but do not mark as odr-used, variable templates.
13534     MarkODRUsed = false;
13535   }
13536
13537   VarTemplateSpecializationDecl *VarSpec =
13538       dyn_cast<VarTemplateSpecializationDecl>(Var);
13539   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13540          "Can't instantiate a partial template specialization.");
13541
13542   // Perform implicit instantiation of static data members, static data member
13543   // templates of class templates, and variable template specializations. Delay
13544   // instantiations of variable templates, except for those that could be used
13545   // in a constant expression.
13546   if (isTemplateInstantiation(TSK)) {
13547     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13548
13549     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13550       if (Var->getPointOfInstantiation().isInvalid()) {
13551         // This is a modification of an existing AST node. Notify listeners.
13552         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13553           L->StaticDataMemberInstantiated(Var);
13554       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13555         // Don't bother trying to instantiate it again, unless we might need
13556         // its initializer before we get to the end of the TU.
13557         TryInstantiating = false;
13558     }
13559
13560     if (Var->getPointOfInstantiation().isInvalid())
13561       Var->setTemplateSpecializationKind(TSK, Loc);
13562
13563     if (TryInstantiating) {
13564       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13565       bool InstantiationDependent = false;
13566       bool IsNonDependent =
13567           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13568                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13569                   : true;
13570
13571       // Do not instantiate specializations that are still type-dependent.
13572       if (IsNonDependent) {
13573         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13574           // Do not defer instantiations of variables which could be used in a
13575           // constant expression.
13576           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13577         } else {
13578           SemaRef.PendingInstantiations
13579               .push_back(std::make_pair(Var, PointOfInstantiation));
13580         }
13581       }
13582     }
13583   }
13584
13585   if(!MarkODRUsed) return;
13586
13587   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13588   // the requirements for appearing in a constant expression (5.19) and, if
13589   // it is an object, the lvalue-to-rvalue conversion (4.1)
13590   // is immediately applied."  We check the first part here, and
13591   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13592   // Note that we use the C++11 definition everywhere because nothing in
13593   // C++03 depends on whether we get the C++03 version correct. The second
13594   // part does not apply to references, since they are not objects.
13595   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13596     // A reference initialized by a constant expression can never be
13597     // odr-used, so simply ignore it.
13598     if (!Var->getType()->isReferenceType())
13599       SemaRef.MaybeODRUseExprs.insert(E);
13600   } else
13601     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13602                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13603 }
13604
13605 /// \brief Mark a variable referenced, and check whether it is odr-used
13606 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13607 /// used directly for normal expressions referring to VarDecl.
13608 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13609   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13610 }
13611
13612 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13613                                Decl *D, Expr *E, bool OdrUse) {
13614   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13615     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13616     return;
13617   }
13618
13619   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
13620
13621   // If this is a call to a method via a cast, also mark the method in the
13622   // derived class used in case codegen can devirtualize the call.
13623   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13624   if (!ME)
13625     return;
13626   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13627   if (!MD)
13628     return;
13629   // Only attempt to devirtualize if this is truly a virtual call.
13630   bool IsVirtualCall = MD->isVirtual() &&
13631                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
13632   if (!IsVirtualCall)
13633     return;
13634   const Expr *Base = ME->getBase();
13635   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13636   if (!MostDerivedClassDecl)
13637     return;
13638   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13639   if (!DM || DM->isPure())
13640     return;
13641   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
13642
13643
13644 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13645 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13646   // TODO: update this with DR# once a defect report is filed.
13647   // C++11 defect. The address of a pure member should not be an ODR use, even
13648   // if it's a qualified reference.
13649   bool OdrUse = true;
13650   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13651     if (Method->isVirtual())
13652       OdrUse = false;
13653   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
13654 }
13655
13656 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
13657 void Sema::MarkMemberReferenced(MemberExpr *E) {
13658   // C++11 [basic.def.odr]p2:
13659   //   A non-overloaded function whose name appears as a potentially-evaluated
13660   //   expression or a member of a set of candidate functions, if selected by
13661   //   overload resolution when referred to from a potentially-evaluated
13662   //   expression, is odr-used, unless it is a pure virtual function and its
13663   //   name is not explicitly qualified.
13664   bool OdrUse = true;
13665   if (E->performsVirtualDispatch(getLangOpts())) {
13666     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13667       if (Method->isPure())
13668         OdrUse = false;
13669   }
13670   SourceLocation Loc = E->getMemberLoc().isValid() ?
13671                             E->getMemberLoc() : E->getLocStart();
13672   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
13673 }
13674
13675 /// \brief Perform marking for a reference to an arbitrary declaration.  It
13676 /// marks the declaration referenced, and performs odr-use checking for
13677 /// functions and variables. This method should not be used when building a
13678 /// normal expression which refers to a variable.
13679 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13680   if (OdrUse) {
13681     if (auto *VD = dyn_cast<VarDecl>(D)) {
13682       MarkVariableReferenced(Loc, VD);
13683       return;
13684     }
13685   }
13686   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13687     MarkFunctionReferenced(Loc, FD, OdrUse);
13688     return;
13689   }
13690   D->setReferenced();
13691 }
13692
13693 namespace {
13694   // Mark all of the declarations referenced
13695   // FIXME: Not fully implemented yet! We need to have a better understanding
13696   // of when we're entering
13697   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13698     Sema &S;
13699     SourceLocation Loc;
13700
13701   public:
13702     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
13703
13704     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
13705
13706     bool TraverseTemplateArgument(const TemplateArgument &Arg);
13707     bool TraverseRecordType(RecordType *T);
13708   };
13709 }
13710
13711 bool MarkReferencedDecls::TraverseTemplateArgument(
13712     const TemplateArgument &Arg) {
13713   if (Arg.getKind() == TemplateArgument::Declaration) {
13714     if (Decl *D = Arg.getAsDecl())
13715       S.MarkAnyDeclReferenced(Loc, D, true);
13716   }
13717
13718   return Inherited::TraverseTemplateArgument(Arg);
13719 }
13720
13721 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
13722   if (ClassTemplateSpecializationDecl *Spec
13723                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13724     const TemplateArgumentList &Args = Spec->getTemplateArgs();
13725     return TraverseTemplateArguments(Args.data(), Args.size());
13726   }
13727
13728   return true;
13729 }
13730
13731 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13732   MarkReferencedDecls Marker(*this, Loc);
13733   Marker.TraverseType(Context.getCanonicalType(T));
13734 }
13735
13736 namespace {
13737   /// \brief Helper class that marks all of the declarations referenced by
13738   /// potentially-evaluated subexpressions as "referenced".
13739   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13740     Sema &S;
13741     bool SkipLocalVariables;
13742     
13743   public:
13744     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13745     
13746     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
13747       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
13748     
13749     void VisitDeclRefExpr(DeclRefExpr *E) {
13750       // If we were asked not to visit local variables, don't.
13751       if (SkipLocalVariables) {
13752         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13753           if (VD->hasLocalStorage())
13754             return;
13755       }
13756       
13757       S.MarkDeclRefReferenced(E);
13758     }
13759
13760     void VisitMemberExpr(MemberExpr *E) {
13761       S.MarkMemberReferenced(E);
13762       Inherited::VisitMemberExpr(E);
13763     }
13764     
13765     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13766       S.MarkFunctionReferenced(E->getLocStart(),
13767             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13768       Visit(E->getSubExpr());
13769     }
13770     
13771     void VisitCXXNewExpr(CXXNewExpr *E) {
13772       if (E->getOperatorNew())
13773         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
13774       if (E->getOperatorDelete())
13775         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13776       Inherited::VisitCXXNewExpr(E);
13777     }
13778
13779     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13780       if (E->getOperatorDelete())
13781         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13782       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13783       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13784         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
13785         S.MarkFunctionReferenced(E->getLocStart(), 
13786                                     S.LookupDestructor(Record));
13787       }
13788       
13789       Inherited::VisitCXXDeleteExpr(E);
13790     }
13791     
13792     void VisitCXXConstructExpr(CXXConstructExpr *E) {
13793       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
13794       Inherited::VisitCXXConstructExpr(E);
13795     }
13796     
13797     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13798       Visit(E->getExpr());
13799     }
13800
13801     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13802       Inherited::VisitImplicitCastExpr(E);
13803
13804       if (E->getCastKind() == CK_LValueToRValue)
13805         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13806     }
13807   };
13808 }
13809
13810 /// \brief Mark any declarations that appear within this expression or any
13811 /// potentially-evaluated subexpressions as "referenced".
13812 ///
13813 /// \param SkipLocalVariables If true, don't mark local variables as 
13814 /// 'referenced'.
13815 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
13816                                             bool SkipLocalVariables) {
13817   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
13818 }
13819
13820 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
13821 /// of the program being compiled.
13822 ///
13823 /// This routine emits the given diagnostic when the code currently being
13824 /// type-checked is "potentially evaluated", meaning that there is a
13825 /// possibility that the code will actually be executable. Code in sizeof()
13826 /// expressions, code used only during overload resolution, etc., are not
13827 /// potentially evaluated. This routine will suppress such diagnostics or,
13828 /// in the absolutely nutty case of potentially potentially evaluated
13829 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
13830 /// later.
13831 ///
13832 /// This routine should be used for all diagnostics that describe the run-time
13833 /// behavior of a program, such as passing a non-POD value through an ellipsis.
13834 /// Failure to do so will likely result in spurious diagnostics or failures
13835 /// during overload resolution or within sizeof/alignof/typeof/typeid.
13836 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
13837                                const PartialDiagnostic &PD) {
13838   switch (ExprEvalContexts.back().Context) {
13839   case Unevaluated:
13840   case UnevaluatedAbstract:
13841     // The argument will never be evaluated, so don't complain.
13842     break;
13843
13844   case ConstantEvaluated:
13845     // Relevant diagnostics should be produced by constant evaluation.
13846     break;
13847
13848   case PotentiallyEvaluated:
13849   case PotentiallyEvaluatedIfUsed:
13850     if (Statement && getCurFunctionOrMethodDecl()) {
13851       FunctionScopes.back()->PossiblyUnreachableDiags.
13852         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
13853     }
13854     else
13855       Diag(Loc, PD);
13856       
13857     return true;
13858   }
13859
13860   return false;
13861 }
13862
13863 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13864                                CallExpr *CE, FunctionDecl *FD) {
13865   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13866     return false;
13867
13868   // If we're inside a decltype's expression, don't check for a valid return
13869   // type or construct temporaries until we know whether this is the last call.
13870   if (ExprEvalContexts.back().IsDecltype) {
13871     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13872     return false;
13873   }
13874
13875   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
13876     FunctionDecl *FD;
13877     CallExpr *CE;
13878     
13879   public:
13880     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13881       : FD(FD), CE(CE) { }
13882
13883     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
13884       if (!FD) {
13885         S.Diag(Loc, diag::err_call_incomplete_return)
13886           << T << CE->getSourceRange();
13887         return;
13888       }
13889       
13890       S.Diag(Loc, diag::err_call_function_incomplete_return)
13891         << CE->getSourceRange() << FD->getDeclName() << T;
13892       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13893           << FD->getDeclName();
13894     }
13895   } Diagnoser(FD, CE);
13896   
13897   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
13898     return true;
13899
13900   return false;
13901 }
13902
13903 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
13904 // will prevent this condition from triggering, which is what we want.
13905 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13906   SourceLocation Loc;
13907
13908   unsigned diagnostic = diag::warn_condition_is_assignment;
13909   bool IsOrAssign = false;
13910
13911   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
13912     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
13913       return;
13914
13915     IsOrAssign = Op->getOpcode() == BO_OrAssign;
13916
13917     // Greylist some idioms by putting them into a warning subcategory.
13918     if (ObjCMessageExpr *ME
13919           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13920       Selector Sel = ME->getSelector();
13921
13922       // self = [<foo> init...]
13923       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13924         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13925
13926       // <foo> = [<bar> nextObject]
13927       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13928         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13929     }
13930
13931     Loc = Op->getOperatorLoc();
13932   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13933     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13934       return;
13935
13936     IsOrAssign = Op->getOperator() == OO_PipeEqual;
13937     Loc = Op->getOperatorLoc();
13938   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13939     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13940   else {
13941     // Not an assignment.
13942     return;
13943   }
13944
13945   Diag(Loc, diagnostic) << E->getSourceRange();
13946
13947   SourceLocation Open = E->getLocStart();
13948   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
13949   Diag(Loc, diag::note_condition_assign_silence)
13950         << FixItHint::CreateInsertion(Open, "(")
13951         << FixItHint::CreateInsertion(Close, ")");
13952
13953   if (IsOrAssign)
13954     Diag(Loc, diag::note_condition_or_assign_to_comparison)
13955       << FixItHint::CreateReplacement(Loc, "!=");
13956   else
13957     Diag(Loc, diag::note_condition_assign_to_comparison)
13958       << FixItHint::CreateReplacement(Loc, "==");
13959 }
13960
13961 /// \brief Redundant parentheses over an equality comparison can indicate
13962 /// that the user intended an assignment used as condition.
13963 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13964   // Don't warn if the parens came from a macro.
13965   SourceLocation parenLoc = ParenE->getLocStart();
13966   if (parenLoc.isInvalid() || parenLoc.isMacroID())
13967     return;
13968   // Don't warn for dependent expressions.
13969   if (ParenE->isTypeDependent())
13970     return;
13971
13972   Expr *E = ParenE->IgnoreParens();
13973
13974   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13975     if (opE->getOpcode() == BO_EQ &&
13976         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13977                                                            == Expr::MLV_Valid) {
13978       SourceLocation Loc = opE->getOperatorLoc();
13979       
13980       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13981       SourceRange ParenERange = ParenE->getSourceRange();
13982       Diag(Loc, diag::note_equality_comparison_silence)
13983         << FixItHint::CreateRemoval(ParenERange.getBegin())
13984         << FixItHint::CreateRemoval(ParenERange.getEnd());
13985       Diag(Loc, diag::note_equality_comparison_to_assign)
13986         << FixItHint::CreateReplacement(Loc, "=");
13987     }
13988 }
13989
13990 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13991   DiagnoseAssignmentAsCondition(E);
13992   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13993     DiagnoseEqualityWithExtraParens(parenE);
13994
13995   ExprResult result = CheckPlaceholderExpr(E);
13996   if (result.isInvalid()) return ExprError();
13997   E = result.get();
13998
13999   if (!E->isTypeDependent()) {
14000     if (getLangOpts().CPlusPlus)
14001       return CheckCXXBooleanCondition(E); // C++ 6.4p4
14002
14003     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14004     if (ERes.isInvalid())
14005       return ExprError();
14006     E = ERes.get();
14007
14008     QualType T = E->getType();
14009     if (!T->isScalarType()) { // C99 6.8.4.1p1
14010       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14011         << T << E->getSourceRange();
14012       return ExprError();
14013     }
14014     CheckBoolLikeConversion(E, Loc);
14015   }
14016
14017   return E;
14018 }
14019
14020 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
14021                                        Expr *SubExpr) {
14022   if (!SubExpr)
14023     return ExprError();
14024
14025   return CheckBooleanCondition(SubExpr, Loc);
14026 }
14027
14028 namespace {
14029   /// A visitor for rebuilding a call to an __unknown_any expression
14030   /// to have an appropriate type.
14031   struct RebuildUnknownAnyFunction
14032     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14033
14034     Sema &S;
14035
14036     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14037
14038     ExprResult VisitStmt(Stmt *S) {
14039       llvm_unreachable("unexpected statement!");
14040     }
14041
14042     ExprResult VisitExpr(Expr *E) {
14043       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14044         << E->getSourceRange();
14045       return ExprError();
14046     }
14047
14048     /// Rebuild an expression which simply semantically wraps another
14049     /// expression which it shares the type and value kind of.
14050     template <class T> ExprResult rebuildSugarExpr(T *E) {
14051       ExprResult SubResult = Visit(E->getSubExpr());
14052       if (SubResult.isInvalid()) return ExprError();
14053
14054       Expr *SubExpr = SubResult.get();
14055       E->setSubExpr(SubExpr);
14056       E->setType(SubExpr->getType());
14057       E->setValueKind(SubExpr->getValueKind());
14058       assert(E->getObjectKind() == OK_Ordinary);
14059       return E;
14060     }
14061
14062     ExprResult VisitParenExpr(ParenExpr *E) {
14063       return rebuildSugarExpr(E);
14064     }
14065
14066     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14067       return rebuildSugarExpr(E);
14068     }
14069
14070     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14071       ExprResult SubResult = Visit(E->getSubExpr());
14072       if (SubResult.isInvalid()) return ExprError();
14073
14074       Expr *SubExpr = SubResult.get();
14075       E->setSubExpr(SubExpr);
14076       E->setType(S.Context.getPointerType(SubExpr->getType()));
14077       assert(E->getValueKind() == VK_RValue);
14078       assert(E->getObjectKind() == OK_Ordinary);
14079       return E;
14080     }
14081
14082     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14083       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14084
14085       E->setType(VD->getType());
14086
14087       assert(E->getValueKind() == VK_RValue);
14088       if (S.getLangOpts().CPlusPlus &&
14089           !(isa<CXXMethodDecl>(VD) &&
14090             cast<CXXMethodDecl>(VD)->isInstance()))
14091         E->setValueKind(VK_LValue);
14092
14093       return E;
14094     }
14095
14096     ExprResult VisitMemberExpr(MemberExpr *E) {
14097       return resolveDecl(E, E->getMemberDecl());
14098     }
14099
14100     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14101       return resolveDecl(E, E->getDecl());
14102     }
14103   };
14104 }
14105
14106 /// Given a function expression of unknown-any type, try to rebuild it
14107 /// to have a function type.
14108 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14109   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14110   if (Result.isInvalid()) return ExprError();
14111   return S.DefaultFunctionArrayConversion(Result.get());
14112 }
14113
14114 namespace {
14115   /// A visitor for rebuilding an expression of type __unknown_anytype
14116   /// into one which resolves the type directly on the referring
14117   /// expression.  Strict preservation of the original source
14118   /// structure is not a goal.
14119   struct RebuildUnknownAnyExpr
14120     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14121
14122     Sema &S;
14123
14124     /// The current destination type.
14125     QualType DestType;
14126
14127     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14128       : S(S), DestType(CastType) {}
14129
14130     ExprResult VisitStmt(Stmt *S) {
14131       llvm_unreachable("unexpected statement!");
14132     }
14133
14134     ExprResult VisitExpr(Expr *E) {
14135       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14136         << E->getSourceRange();
14137       return ExprError();
14138     }
14139
14140     ExprResult VisitCallExpr(CallExpr *E);
14141     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14142
14143     /// Rebuild an expression which simply semantically wraps another
14144     /// expression which it shares the type and value kind of.
14145     template <class T> ExprResult rebuildSugarExpr(T *E) {
14146       ExprResult SubResult = Visit(E->getSubExpr());
14147       if (SubResult.isInvalid()) return ExprError();
14148       Expr *SubExpr = SubResult.get();
14149       E->setSubExpr(SubExpr);
14150       E->setType(SubExpr->getType());
14151       E->setValueKind(SubExpr->getValueKind());
14152       assert(E->getObjectKind() == OK_Ordinary);
14153       return E;
14154     }
14155
14156     ExprResult VisitParenExpr(ParenExpr *E) {
14157       return rebuildSugarExpr(E);
14158     }
14159
14160     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14161       return rebuildSugarExpr(E);
14162     }
14163
14164     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14165       const PointerType *Ptr = DestType->getAs<PointerType>();
14166       if (!Ptr) {
14167         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14168           << E->getSourceRange();
14169         return ExprError();
14170       }
14171       assert(E->getValueKind() == VK_RValue);
14172       assert(E->getObjectKind() == OK_Ordinary);
14173       E->setType(DestType);
14174
14175       // Build the sub-expression as if it were an object of the pointee type.
14176       DestType = Ptr->getPointeeType();
14177       ExprResult SubResult = Visit(E->getSubExpr());
14178       if (SubResult.isInvalid()) return ExprError();
14179       E->setSubExpr(SubResult.get());
14180       return E;
14181     }
14182
14183     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14184
14185     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14186
14187     ExprResult VisitMemberExpr(MemberExpr *E) {
14188       return resolveDecl(E, E->getMemberDecl());
14189     }
14190
14191     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14192       return resolveDecl(E, E->getDecl());
14193     }
14194   };
14195 }
14196
14197 /// Rebuilds a call expression which yielded __unknown_anytype.
14198 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14199   Expr *CalleeExpr = E->getCallee();
14200
14201   enum FnKind {
14202     FK_MemberFunction,
14203     FK_FunctionPointer,
14204     FK_BlockPointer
14205   };
14206
14207   FnKind Kind;
14208   QualType CalleeType = CalleeExpr->getType();
14209   if (CalleeType == S.Context.BoundMemberTy) {
14210     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14211     Kind = FK_MemberFunction;
14212     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14213   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14214     CalleeType = Ptr->getPointeeType();
14215     Kind = FK_FunctionPointer;
14216   } else {
14217     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14218     Kind = FK_BlockPointer;
14219   }
14220   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14221
14222   // Verify that this is a legal result type of a function.
14223   if (DestType->isArrayType() || DestType->isFunctionType()) {
14224     unsigned diagID = diag::err_func_returning_array_function;
14225     if (Kind == FK_BlockPointer)
14226       diagID = diag::err_block_returning_array_function;
14227
14228     S.Diag(E->getExprLoc(), diagID)
14229       << DestType->isFunctionType() << DestType;
14230     return ExprError();
14231   }
14232
14233   // Otherwise, go ahead and set DestType as the call's result.
14234   E->setType(DestType.getNonLValueExprType(S.Context));
14235   E->setValueKind(Expr::getValueKindForType(DestType));
14236   assert(E->getObjectKind() == OK_Ordinary);
14237
14238   // Rebuild the function type, replacing the result type with DestType.
14239   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14240   if (Proto) {
14241     // __unknown_anytype(...) is a special case used by the debugger when
14242     // it has no idea what a function's signature is.
14243     //
14244     // We want to build this call essentially under the K&R
14245     // unprototyped rules, but making a FunctionNoProtoType in C++
14246     // would foul up all sorts of assumptions.  However, we cannot
14247     // simply pass all arguments as variadic arguments, nor can we
14248     // portably just call the function under a non-variadic type; see
14249     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14250     // However, it turns out that in practice it is generally safe to
14251     // call a function declared as "A foo(B,C,D);" under the prototype
14252     // "A foo(B,C,D,...);".  The only known exception is with the
14253     // Windows ABI, where any variadic function is implicitly cdecl
14254     // regardless of its normal CC.  Therefore we change the parameter
14255     // types to match the types of the arguments.
14256     //
14257     // This is a hack, but it is far superior to moving the
14258     // corresponding target-specific code from IR-gen to Sema/AST.
14259
14260     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14261     SmallVector<QualType, 8> ArgTypes;
14262     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14263       ArgTypes.reserve(E->getNumArgs());
14264       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14265         Expr *Arg = E->getArg(i);
14266         QualType ArgType = Arg->getType();
14267         if (E->isLValue()) {
14268           ArgType = S.Context.getLValueReferenceType(ArgType);
14269         } else if (E->isXValue()) {
14270           ArgType = S.Context.getRValueReferenceType(ArgType);
14271         }
14272         ArgTypes.push_back(ArgType);
14273       }
14274       ParamTypes = ArgTypes;
14275     }
14276     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14277                                          Proto->getExtProtoInfo());
14278   } else {
14279     DestType = S.Context.getFunctionNoProtoType(DestType,
14280                                                 FnType->getExtInfo());
14281   }
14282
14283   // Rebuild the appropriate pointer-to-function type.
14284   switch (Kind) { 
14285   case FK_MemberFunction:
14286     // Nothing to do.
14287     break;
14288
14289   case FK_FunctionPointer:
14290     DestType = S.Context.getPointerType(DestType);
14291     break;
14292
14293   case FK_BlockPointer:
14294     DestType = S.Context.getBlockPointerType(DestType);
14295     break;
14296   }
14297
14298   // Finally, we can recurse.
14299   ExprResult CalleeResult = Visit(CalleeExpr);
14300   if (!CalleeResult.isUsable()) return ExprError();
14301   E->setCallee(CalleeResult.get());
14302
14303   // Bind a temporary if necessary.
14304   return S.MaybeBindToTemporary(E);
14305 }
14306
14307 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14308   // Verify that this is a legal result type of a call.
14309   if (DestType->isArrayType() || DestType->isFunctionType()) {
14310     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14311       << DestType->isFunctionType() << DestType;
14312     return ExprError();
14313   }
14314
14315   // Rewrite the method result type if available.
14316   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14317     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14318     Method->setReturnType(DestType);
14319   }
14320
14321   // Change the type of the message.
14322   E->setType(DestType.getNonReferenceType());
14323   E->setValueKind(Expr::getValueKindForType(DestType));
14324
14325   return S.MaybeBindToTemporary(E);
14326 }
14327
14328 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14329   // The only case we should ever see here is a function-to-pointer decay.
14330   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14331     assert(E->getValueKind() == VK_RValue);
14332     assert(E->getObjectKind() == OK_Ordinary);
14333   
14334     E->setType(DestType);
14335   
14336     // Rebuild the sub-expression as the pointee (function) type.
14337     DestType = DestType->castAs<PointerType>()->getPointeeType();
14338   
14339     ExprResult Result = Visit(E->getSubExpr());
14340     if (!Result.isUsable()) return ExprError();
14341   
14342     E->setSubExpr(Result.get());
14343     return E;
14344   } else if (E->getCastKind() == CK_LValueToRValue) {
14345     assert(E->getValueKind() == VK_RValue);
14346     assert(E->getObjectKind() == OK_Ordinary);
14347
14348     assert(isa<BlockPointerType>(E->getType()));
14349
14350     E->setType(DestType);
14351
14352     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14353     DestType = S.Context.getLValueReferenceType(DestType);
14354
14355     ExprResult Result = Visit(E->getSubExpr());
14356     if (!Result.isUsable()) return ExprError();
14357
14358     E->setSubExpr(Result.get());
14359     return E;
14360   } else {
14361     llvm_unreachable("Unhandled cast type!");
14362   }
14363 }
14364
14365 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14366   ExprValueKind ValueKind = VK_LValue;
14367   QualType Type = DestType;
14368
14369   // We know how to make this work for certain kinds of decls:
14370
14371   //  - functions
14372   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14373     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14374       DestType = Ptr->getPointeeType();
14375       ExprResult Result = resolveDecl(E, VD);
14376       if (Result.isInvalid()) return ExprError();
14377       return S.ImpCastExprToType(Result.get(), Type,
14378                                  CK_FunctionToPointerDecay, VK_RValue);
14379     }
14380
14381     if (!Type->isFunctionType()) {
14382       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14383         << VD << E->getSourceRange();
14384       return ExprError();
14385     }
14386     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14387       // We must match the FunctionDecl's type to the hack introduced in
14388       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14389       // type. See the lengthy commentary in that routine.
14390       QualType FDT = FD->getType();
14391       const FunctionType *FnType = FDT->castAs<FunctionType>();
14392       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14393       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14394       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14395         SourceLocation Loc = FD->getLocation();
14396         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14397                                       FD->getDeclContext(),
14398                                       Loc, Loc, FD->getNameInfo().getName(),
14399                                       DestType, FD->getTypeSourceInfo(),
14400                                       SC_None, false/*isInlineSpecified*/,
14401                                       FD->hasPrototype(),
14402                                       false/*isConstexprSpecified*/);
14403           
14404         if (FD->getQualifier())
14405           NewFD->setQualifierInfo(FD->getQualifierLoc());
14406
14407         SmallVector<ParmVarDecl*, 16> Params;
14408         for (const auto &AI : FT->param_types()) {
14409           ParmVarDecl *Param =
14410             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14411           Param->setScopeInfo(0, Params.size());
14412           Params.push_back(Param);
14413         }
14414         NewFD->setParams(Params);
14415         DRE->setDecl(NewFD);
14416         VD = DRE->getDecl();
14417       }
14418     }
14419
14420     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14421       if (MD->isInstance()) {
14422         ValueKind = VK_RValue;
14423         Type = S.Context.BoundMemberTy;
14424       }
14425
14426     // Function references aren't l-values in C.
14427     if (!S.getLangOpts().CPlusPlus)
14428       ValueKind = VK_RValue;
14429
14430   //  - variables
14431   } else if (isa<VarDecl>(VD)) {
14432     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14433       Type = RefTy->getPointeeType();
14434     } else if (Type->isFunctionType()) {
14435       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14436         << VD << E->getSourceRange();
14437       return ExprError();
14438     }
14439
14440   //  - nothing else
14441   } else {
14442     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14443       << VD << E->getSourceRange();
14444     return ExprError();
14445   }
14446
14447   // Modifying the declaration like this is friendly to IR-gen but
14448   // also really dangerous.
14449   VD->setType(DestType);
14450   E->setType(Type);
14451   E->setValueKind(ValueKind);
14452   return E;
14453 }
14454
14455 /// Check a cast of an unknown-any type.  We intentionally only
14456 /// trigger this for C-style casts.
14457 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14458                                      Expr *CastExpr, CastKind &CastKind,
14459                                      ExprValueKind &VK, CXXCastPath &Path) {
14460   // Rewrite the casted expression from scratch.
14461   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14462   if (!result.isUsable()) return ExprError();
14463
14464   CastExpr = result.get();
14465   VK = CastExpr->getValueKind();
14466   CastKind = CK_NoOp;
14467
14468   return CastExpr;
14469 }
14470
14471 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14472   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14473 }
14474
14475 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14476                                     Expr *arg, QualType &paramType) {
14477   // If the syntactic form of the argument is not an explicit cast of
14478   // any sort, just do default argument promotion.
14479   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14480   if (!castArg) {
14481     ExprResult result = DefaultArgumentPromotion(arg);
14482     if (result.isInvalid()) return ExprError();
14483     paramType = result.get()->getType();
14484     return result;
14485   }
14486
14487   // Otherwise, use the type that was written in the explicit cast.
14488   assert(!arg->hasPlaceholderType());
14489   paramType = castArg->getTypeAsWritten();
14490
14491   // Copy-initialize a parameter of that type.
14492   InitializedEntity entity =
14493     InitializedEntity::InitializeParameter(Context, paramType,
14494                                            /*consumed*/ false);
14495   return PerformCopyInitialization(entity, callLoc, arg);
14496 }
14497
14498 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14499   Expr *orig = E;
14500   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14501   while (true) {
14502     E = E->IgnoreParenImpCasts();
14503     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14504       E = call->getCallee();
14505       diagID = diag::err_uncasted_call_of_unknown_any;
14506     } else {
14507       break;
14508     }
14509   }
14510
14511   SourceLocation loc;
14512   NamedDecl *d;
14513   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14514     loc = ref->getLocation();
14515     d = ref->getDecl();
14516   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14517     loc = mem->getMemberLoc();
14518     d = mem->getMemberDecl();
14519   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14520     diagID = diag::err_uncasted_call_of_unknown_any;
14521     loc = msg->getSelectorStartLoc();
14522     d = msg->getMethodDecl();
14523     if (!d) {
14524       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14525         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14526         << orig->getSourceRange();
14527       return ExprError();
14528     }
14529   } else {
14530     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14531       << E->getSourceRange();
14532     return ExprError();
14533   }
14534
14535   S.Diag(loc, diagID) << d << orig->getSourceRange();
14536
14537   // Never recoverable.
14538   return ExprError();
14539 }
14540
14541 /// Check for operands with placeholder types and complain if found.
14542 /// Returns true if there was an error and no recovery was possible.
14543 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14544   if (!getLangOpts().CPlusPlus) {
14545     // C cannot handle TypoExpr nodes on either side of a binop because it
14546     // doesn't handle dependent types properly, so make sure any TypoExprs have
14547     // been dealt with before checking the operands.
14548     ExprResult Result = CorrectDelayedTyposInExpr(E);
14549     if (!Result.isUsable()) return ExprError();
14550     E = Result.get();
14551   }
14552
14553   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14554   if (!placeholderType) return E;
14555
14556   switch (placeholderType->getKind()) {
14557
14558   // Overloaded expressions.
14559   case BuiltinType::Overload: {
14560     // Try to resolve a single function template specialization.
14561     // This is obligatory.
14562     ExprResult result = E;
14563     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14564       return result;
14565
14566     // If that failed, try to recover with a call.
14567     } else {
14568       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14569                            /*complain*/ true);
14570       return result;
14571     }
14572   }
14573
14574   // Bound member functions.
14575   case BuiltinType::BoundMember: {
14576     ExprResult result = E;
14577     const Expr *BME = E->IgnoreParens();
14578     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14579     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14580     if (isa<CXXPseudoDestructorExpr>(BME)) {
14581       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14582     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14583       if (ME->getMemberNameInfo().getName().getNameKind() ==
14584           DeclarationName::CXXDestructorName)
14585         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14586     }
14587     tryToRecoverWithCall(result, PD,
14588                          /*complain*/ true);
14589     return result;
14590   }
14591
14592   // ARC unbridged casts.
14593   case BuiltinType::ARCUnbridgedCast: {
14594     Expr *realCast = stripARCUnbridgedCast(E);
14595     diagnoseARCUnbridgedCast(realCast);
14596     return realCast;
14597   }
14598
14599   // Expressions of unknown type.
14600   case BuiltinType::UnknownAny:
14601     return diagnoseUnknownAnyExpr(*this, E);
14602
14603   // Pseudo-objects.
14604   case BuiltinType::PseudoObject:
14605     return checkPseudoObjectRValue(E);
14606
14607   case BuiltinType::BuiltinFn: {
14608     // Accept __noop without parens by implicitly converting it to a call expr.
14609     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14610     if (DRE) {
14611       auto *FD = cast<FunctionDecl>(DRE->getDecl());
14612       if (FD->getBuiltinID() == Builtin::BI__noop) {
14613         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14614                               CK_BuiltinFnToFnPtr).get();
14615         return new (Context) CallExpr(Context, E, None, Context.IntTy,
14616                                       VK_RValue, SourceLocation());
14617       }
14618     }
14619
14620     Diag(E->getLocStart(), diag::err_builtin_fn_use);
14621     return ExprError();
14622   }
14623
14624   // Expressions of unknown type.
14625   case BuiltinType::OMPArraySection:
14626     Diag(E->getLocStart(), diag::err_omp_array_section_use);
14627     return ExprError();
14628
14629   // Everything else should be impossible.
14630 #define BUILTIN_TYPE(Id, SingletonId) \
14631   case BuiltinType::Id:
14632 #define PLACEHOLDER_TYPE(Id, SingletonId)
14633 #include "clang/AST/BuiltinTypes.def"
14634     break;
14635   }
14636
14637   llvm_unreachable("invalid placeholder type!");
14638 }
14639
14640 bool Sema::CheckCaseExpression(Expr *E) {
14641   if (E->isTypeDependent())
14642     return true;
14643   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14644     return E->getType()->isIntegralOrEnumerationType();
14645   return false;
14646 }
14647
14648 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14649 ExprResult
14650 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14651   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14652          "Unknown Objective-C Boolean value!");
14653   QualType BoolT = Context.ObjCBuiltinBoolTy;
14654   if (!Context.getBOOLDecl()) {
14655     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
14656                         Sema::LookupOrdinaryName);
14657     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
14658       NamedDecl *ND = Result.getFoundDecl();
14659       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
14660         Context.setBOOLDecl(TD);
14661     }
14662   }
14663   if (Context.getBOOLDecl())
14664     BoolT = Context.getBOOLType();
14665   return new (Context)
14666       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
14667 }