]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302069, and update
[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 "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.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, bool TreatUnavailableAsInvalid) {
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 (TreatUnavailableAsInvalid && 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 (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, 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   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161
162   return Result;
163 }
164
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173
174     if (Result == AR_NotYetIntroduced) {
175       if (S.getCurFunctionOrMethodDecl()) {
176         S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
177         return;
178       } else if (S.getCurBlock() || S.getCurLambda()) {
179         S.getCurFunction()->HasPotentialAvailabilityViolations = true;
180         return;
181       }
182     }
183
184     const ObjCPropertyDecl *ObjCPDecl = nullptr;
185     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
186       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
187         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
188         if (PDeclResult == Result)
189           ObjCPDecl = PD;
190       }
191     }
192
193     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
194                               ObjCPDecl, ObjCPropertyAccess);
195   }
196 }
197
198 /// \brief Emit a note explaining that this function is deleted.
199 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
200   assert(Decl->isDeleted());
201
202   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
203
204   if (Method && Method->isDeleted() && Method->isDefaulted()) {
205     // If the method was explicitly defaulted, point at that declaration.
206     if (!Method->isImplicit())
207       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
208
209     // Try to diagnose why this special member function was implicitly
210     // deleted. This might fail, if that reason no longer applies.
211     CXXSpecialMember CSM = getSpecialMember(Method);
212     if (CSM != CXXInvalid)
213       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
214
215     return;
216   }
217
218   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
219   if (Ctor && Ctor->isInheritingConstructor())
220     return NoteDeletedInheritingConstructor(Ctor);
221
222   Diag(Decl->getLocation(), diag::note_availability_specified_here)
223     << Decl << true;
224 }
225
226 /// \brief Determine whether a FunctionDecl was ever declared with an
227 /// explicit storage class.
228 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
229   for (auto I : D->redecls()) {
230     if (I->getStorageClass() != SC_None)
231       return true;
232   }
233   return false;
234 }
235
236 /// \brief Check whether we're in an extern inline function and referring to a
237 /// variable or function with internal linkage (C11 6.7.4p3).
238 ///
239 /// This is only a warning because we used to silently accept this code, but
240 /// in many cases it will not behave correctly. This is not enabled in C++ mode
241 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
242 /// and so while there may still be user mistakes, most of the time we can't
243 /// prove that there are errors.
244 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
245                                                       const NamedDecl *D,
246                                                       SourceLocation Loc) {
247   // This is disabled under C++; there are too many ways for this to fire in
248   // contexts where the warning is a false positive, or where it is technically
249   // correct but benign.
250   if (S.getLangOpts().CPlusPlus)
251     return;
252
253   // Check if this is an inlined function or method.
254   FunctionDecl *Current = S.getCurFunctionDecl();
255   if (!Current)
256     return;
257   if (!Current->isInlined())
258     return;
259   if (!Current->isExternallyVisible())
260     return;
261
262   // Check if the decl has internal linkage.
263   if (D->getFormalLinkage() != InternalLinkage)
264     return;
265
266   // Downgrade from ExtWarn to Extension if
267   //  (1) the supposedly external inline function is in the main file,
268   //      and probably won't be included anywhere else.
269   //  (2) the thing we're referencing is a pure function.
270   //  (3) the thing we're referencing is another inline function.
271   // This last can give us false negatives, but it's better than warning on
272   // wrappers for simple C library functions.
273   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
274   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
275   if (!DowngradeWarning && UsedFn)
276     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
277
278   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
279                                : diag::ext_internal_in_extern_inline)
280     << /*IsVar=*/!UsedFn << D;
281
282   S.MaybeSuggestAddingStaticToDecl(Current);
283
284   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
285       << D;
286 }
287
288 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
289   const FunctionDecl *First = Cur->getFirstDecl();
290
291   // Suggest "static" on the function, if possible.
292   if (!hasAnyExplicitStorageClass(First)) {
293     SourceLocation DeclBegin = First->getSourceRange().getBegin();
294     Diag(DeclBegin, diag::note_convert_inline_to_static)
295       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
296   }
297 }
298
299 /// \brief Determine whether the use of this declaration is valid, and
300 /// emit any corresponding diagnostics.
301 ///
302 /// This routine diagnoses various problems with referencing
303 /// declarations that can occur when using a declaration. For example,
304 /// it might warn if a deprecated or unavailable declaration is being
305 /// used, or produce an error (and return true) if a C++0x deleted
306 /// function is being used.
307 ///
308 /// \returns true if there was an error (this declaration cannot be
309 /// referenced), false otherwise.
310 ///
311 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
312                              const ObjCInterfaceDecl *UnknownObjCClass,
313                              bool ObjCPropertyAccess) {
314   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
315     // If there were any diagnostics suppressed by template argument deduction,
316     // emit them now.
317     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
318     if (Pos != SuppressedDiagnostics.end()) {
319       for (const PartialDiagnosticAt &Suppressed : Pos->second)
320         Diag(Suppressed.first, Suppressed.second);
321
322       // Clear out the list of suppressed diagnostics, so that we don't emit
323       // them again for this specialization. However, we don't obsolete this
324       // entry from the table, because we want to avoid ever emitting these
325       // diagnostics again.
326       Pos->second.clear();
327     }
328
329     // C++ [basic.start.main]p3:
330     //   The function 'main' shall not be used within a program.
331     if (cast<FunctionDecl>(D)->isMain())
332       Diag(Loc, diag::ext_main_used);
333   }
334
335   // See if this is an auto-typed variable whose initializer we are parsing.
336   if (ParsingInitForAutoVars.count(D)) {
337     if (isa<BindingDecl>(D)) {
338       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
339         << D->getDeclName();
340     } else {
341       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
342         << D->getDeclName() << cast<VarDecl>(D)->getType();
343     }
344     return true;
345   }
346
347   // See if this is a deleted function.
348   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
349     if (FD->isDeleted()) {
350       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
351       if (Ctor && Ctor->isInheritingConstructor())
352         Diag(Loc, diag::err_deleted_inherited_ctor_use)
353             << Ctor->getParent()
354             << Ctor->getInheritedConstructor().getConstructor()->getParent();
355       else 
356         Diag(Loc, diag::err_deleted_function_use);
357       NoteDeletedFunction(FD);
358       return true;
359     }
360
361     // If the function has a deduced return type, and we can't deduce it,
362     // then we can't use it either.
363     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
364         DeduceReturnType(FD, Loc))
365       return true;
366
367     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
368       return true;
369
370     if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
371       return true;
372   }
373
374   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
375   // Only the variables omp_in and omp_out are allowed in the combiner.
376   // Only the variables omp_priv and omp_orig are allowed in the
377   // initializer-clause.
378   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
379   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
380       isa<VarDecl>(D)) {
381     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
382         << getCurFunction()->HasOMPDeclareReductionCombiner;
383     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
384     return true;
385   }
386
387   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
388                              ObjCPropertyAccess);
389
390   DiagnoseUnusedOfDecl(*this, D, Loc);
391
392   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
393
394   return false;
395 }
396
397 /// \brief Retrieve the message suffix that should be added to a
398 /// diagnostic complaining about the given function being deleted or
399 /// unavailable.
400 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
401   std::string Message;
402   if (FD->getAvailability(&Message))
403     return ": " + Message;
404
405   return std::string();
406 }
407
408 /// DiagnoseSentinelCalls - This routine checks whether a call or
409 /// message-send is to a declaration with the sentinel attribute, and
410 /// if so, it checks that the requirements of the sentinel are
411 /// satisfied.
412 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
413                                  ArrayRef<Expr *> Args) {
414   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
415   if (!attr)
416     return;
417
418   // The number of formal parameters of the declaration.
419   unsigned numFormalParams;
420
421   // The kind of declaration.  This is also an index into a %select in
422   // the diagnostic.
423   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
424
425   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
426     numFormalParams = MD->param_size();
427     calleeType = CT_Method;
428   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
429     numFormalParams = FD->param_size();
430     calleeType = CT_Function;
431   } else if (isa<VarDecl>(D)) {
432     QualType type = cast<ValueDecl>(D)->getType();
433     const FunctionType *fn = nullptr;
434     if (const PointerType *ptr = type->getAs<PointerType>()) {
435       fn = ptr->getPointeeType()->getAs<FunctionType>();
436       if (!fn) return;
437       calleeType = CT_Function;
438     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
439       fn = ptr->getPointeeType()->castAs<FunctionType>();
440       calleeType = CT_Block;
441     } else {
442       return;
443     }
444
445     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
446       numFormalParams = proto->getNumParams();
447     } else {
448       numFormalParams = 0;
449     }
450   } else {
451     return;
452   }
453
454   // "nullPos" is the number of formal parameters at the end which
455   // effectively count as part of the variadic arguments.  This is
456   // useful if you would prefer to not have *any* formal parameters,
457   // but the language forces you to have at least one.
458   unsigned nullPos = attr->getNullPos();
459   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
460   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
461
462   // The number of arguments which should follow the sentinel.
463   unsigned numArgsAfterSentinel = attr->getSentinel();
464
465   // If there aren't enough arguments for all the formal parameters,
466   // the sentinel, and the args after the sentinel, complain.
467   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
468     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
470     return;
471   }
472
473   // Otherwise, find the sentinel expression.
474   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
475   if (!sentinelExpr) return;
476   if (sentinelExpr->isValueDependent()) return;
477   if (Context.isSentinelNullExpr(sentinelExpr)) return;
478
479   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
480   // or 'NULL' if those are actually defined in the context.  Only use
481   // 'nil' for ObjC methods, where it's much more likely that the
482   // variadic arguments form a list of object pointers.
483   SourceLocation MissingNilLoc
484     = getLocForEndOfToken(sentinelExpr->getLocEnd());
485   std::string NullValue;
486   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
487     NullValue = "nil";
488   else if (getLangOpts().CPlusPlus11)
489     NullValue = "nullptr";
490   else if (PP.isMacroDefined("NULL"))
491     NullValue = "NULL";
492   else
493     NullValue = "(void*) 0";
494
495   if (MissingNilLoc.isInvalid())
496     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
497   else
498     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
499       << int(calleeType)
500       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
501   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
502 }
503
504 SourceRange Sema::getExprRange(Expr *E) const {
505   return E ? E->getSourceRange() : SourceRange();
506 }
507
508 //===----------------------------------------------------------------------===//
509 //  Standard Promotions and Conversions
510 //===----------------------------------------------------------------------===//
511
512 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
513 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
514   // Handle any placeholder expressions which made it here.
515   if (E->getType()->isPlaceholderType()) {
516     ExprResult result = CheckPlaceholderExpr(E);
517     if (result.isInvalid()) return ExprError();
518     E = result.get();
519   }
520   
521   QualType Ty = E->getType();
522   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
523
524   if (Ty->isFunctionType()) {
525     // If we are here, we are not calling a function but taking
526     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
527     if (getLangOpts().OpenCL) {
528       if (Diagnose)
529         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
530       return ExprError();
531     }
532
533     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
534       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
536           return ExprError();
537
538     E = ImpCastExprToType(E, Context.getPointerType(Ty),
539                           CK_FunctionToPointerDecay).get();
540   } else if (Ty->isArrayType()) {
541     // In C90 mode, arrays only promote to pointers if the array expression is
542     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543     // type 'array of type' is converted to an expression that has type 'pointer
544     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
545     // that has type 'array of type' ...".  The relevant change is "an lvalue"
546     // (C90) to "an expression" (C99).
547     //
548     // C++ 4.2p1:
549     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550     // T" can be converted to an rvalue of type "pointer to T".
551     //
552     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
553       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
554                             CK_ArrayToPointerDecay).get();
555   }
556   return E;
557 }
558
559 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
560   // Check to see if we are dereferencing a null pointer.  If so,
561   // and if not volatile-qualified, this is undefined behavior that the
562   // optimizer will delete, so warn about it.  People sometimes try to use this
563   // to get a deterministic trap and are surprised by clang's behavior.  This
564   // only handles the pattern "*null", which is a very syntactic check.
565   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
566     if (UO->getOpcode() == UO_Deref &&
567         UO->getSubExpr()->IgnoreParenCasts()->
568           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
569         !UO->getType().isVolatileQualified()) {
570     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571                           S.PDiag(diag::warn_indirection_through_null)
572                             << UO->getSubExpr()->getSourceRange());
573     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
574                         S.PDiag(diag::note_indirection_through_null));
575   }
576 }
577
578 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
579                                     SourceLocation AssignLoc,
580                                     const Expr* RHS) {
581   const ObjCIvarDecl *IV = OIRE->getDecl();
582   if (!IV)
583     return;
584   
585   DeclarationName MemberName = IV->getDeclName();
586   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
587   if (!Member || !Member->isStr("isa"))
588     return;
589   
590   const Expr *Base = OIRE->getBase();
591   QualType BaseType = Base->getType();
592   if (OIRE->isArrow())
593     BaseType = BaseType->getPointeeType();
594   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
595     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
596       ObjCInterfaceDecl *ClassDeclared = nullptr;
597       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
598       if (!ClassDeclared->getSuperClass()
599           && (*ClassDeclared->ivar_begin()) == IV) {
600         if (RHS) {
601           NamedDecl *ObjectSetClass =
602             S.LookupSingleName(S.TUScope,
603                                &S.Context.Idents.get("object_setClass"),
604                                SourceLocation(), S.LookupOrdinaryName);
605           if (ObjectSetClass) {
606             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
607             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
608             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
609             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
610                                                      AssignLoc), ",") <<
611             FixItHint::CreateInsertion(RHSLocEnd, ")");
612           }
613           else
614             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
615         } else {
616           NamedDecl *ObjectGetClass =
617             S.LookupSingleName(S.TUScope,
618                                &S.Context.Idents.get("object_getClass"),
619                                SourceLocation(), S.LookupOrdinaryName);
620           if (ObjectGetClass)
621             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
622             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
623             FixItHint::CreateReplacement(
624                                          SourceRange(OIRE->getOpLoc(),
625                                                      OIRE->getLocEnd()), ")");
626           else
627             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
628         }
629         S.Diag(IV->getLocation(), diag::note_ivar_decl);
630       }
631     }
632 }
633
634 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
635   // Handle any placeholder expressions which made it here.
636   if (E->getType()->isPlaceholderType()) {
637     ExprResult result = CheckPlaceholderExpr(E);
638     if (result.isInvalid()) return ExprError();
639     E = result.get();
640   }
641   
642   // C++ [conv.lval]p1:
643   //   A glvalue of a non-function, non-array type T can be
644   //   converted to a prvalue.
645   if (!E->isGLValue()) return E;
646
647   QualType T = E->getType();
648   assert(!T.isNull() && "r-value conversion on typeless expression?");
649
650   // We don't want to throw lvalue-to-rvalue casts on top of
651   // expressions of certain types in C++.
652   if (getLangOpts().CPlusPlus &&
653       (E->getType() == Context.OverloadTy ||
654        T->isDependentType() ||
655        T->isRecordType()))
656     return E;
657
658   // The C standard is actually really unclear on this point, and
659   // DR106 tells us what the result should be but not why.  It's
660   // generally best to say that void types just doesn't undergo
661   // lvalue-to-rvalue at all.  Note that expressions of unqualified
662   // 'void' type are never l-values, but qualified void can be.
663   if (T->isVoidType())
664     return E;
665
666   // OpenCL usually rejects direct accesses to values of 'half' type.
667   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
668       T->isHalfType()) {
669     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
670       << 0 << T;
671     return ExprError();
672   }
673
674   CheckForNullPointerDereference(*this, E);
675   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
676     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
677                                      &Context.Idents.get("object_getClass"),
678                                      SourceLocation(), LookupOrdinaryName);
679     if (ObjectGetClass)
680       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
681         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
682         FixItHint::CreateReplacement(
683                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
684     else
685       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
686   }
687   else if (const ObjCIvarRefExpr *OIRE =
688             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
689     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
690
691   // C++ [conv.lval]p1:
692   //   [...] If T is a non-class type, the type of the prvalue is the
693   //   cv-unqualified version of T. Otherwise, the type of the
694   //   rvalue is T.
695   //
696   // C99 6.3.2.1p2:
697   //   If the lvalue has qualified type, the value has the unqualified
698   //   version of the type of the lvalue; otherwise, the value has the
699   //   type of the lvalue.
700   if (T.hasQualifiers())
701     T = T.getUnqualifiedType();
702
703   // Under the MS ABI, lock down the inheritance model now.
704   if (T->isMemberPointerType() &&
705       Context.getTargetInfo().getCXXABI().isMicrosoft())
706     (void)isCompleteType(E->getExprLoc(), T);
707
708   UpdateMarkingForLValueToRValue(E);
709   
710   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
711   // balance that.
712   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713     Cleanup.setExprNeedsCleanups(true);
714
715   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
716                                             nullptr, VK_RValue);
717
718   // C11 6.3.2.1p2:
719   //   ... if the lvalue has atomic type, the value has the non-atomic version 
720   //   of the type of the lvalue ...
721   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
722     T = Atomic->getValueType().getUnqualifiedType();
723     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
724                                    nullptr, VK_RValue);
725   }
726   
727   return Res;
728 }
729
730 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
731   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
732   if (Res.isInvalid())
733     return ExprError();
734   Res = DefaultLvalueConversion(Res.get());
735   if (Res.isInvalid())
736     return ExprError();
737   return Res;
738 }
739
740 /// CallExprUnaryConversions - a special case of an unary conversion
741 /// performed on a function designator of a call expression.
742 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
743   QualType Ty = E->getType();
744   ExprResult Res = E;
745   // Only do implicit cast for a function type, but not for a pointer
746   // to function type.
747   if (Ty->isFunctionType()) {
748     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
749                             CK_FunctionToPointerDecay).get();
750     if (Res.isInvalid())
751       return ExprError();
752   }
753   Res = DefaultLvalueConversion(Res.get());
754   if (Res.isInvalid())
755     return ExprError();
756   return Res.get();
757 }
758
759 /// UsualUnaryConversions - Performs various conversions that are common to most
760 /// operators (C99 6.3). The conversions of array and function types are
761 /// sometimes suppressed. For example, the array->pointer conversion doesn't
762 /// apply if the array is an argument to the sizeof or address (&) operators.
763 /// In these instances, this routine should *not* be called.
764 ExprResult Sema::UsualUnaryConversions(Expr *E) {
765   // First, convert to an r-value.
766   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
767   if (Res.isInvalid())
768     return ExprError();
769   E = Res.get();
770
771   QualType Ty = E->getType();
772   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
773
774   // Half FP have to be promoted to float unless it is natively supported
775   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
776     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
777
778   // Try to perform integral promotions if the object has a theoretically
779   // promotable type.
780   if (Ty->isIntegralOrUnscopedEnumerationType()) {
781     // C99 6.3.1.1p2:
782     //
783     //   The following may be used in an expression wherever an int or
784     //   unsigned int may be used:
785     //     - an object or expression with an integer type whose integer
786     //       conversion rank is less than or equal to the rank of int
787     //       and unsigned int.
788     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
789     //
790     //   If an int can represent all values of the original type, the
791     //   value is converted to an int; otherwise, it is converted to an
792     //   unsigned int. These are called the integer promotions. All
793     //   other types are unchanged by the integer promotions.
794
795     QualType PTy = Context.isPromotableBitField(E);
796     if (!PTy.isNull()) {
797       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
798       return E;
799     }
800     if (Ty->isPromotableIntegerType()) {
801       QualType PT = Context.getPromotedIntegerType(Ty);
802       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
803       return E;
804     }
805   }
806   return E;
807 }
808
809 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
810 /// do not have a prototype. Arguments that have type float or __fp16
811 /// are promoted to double. All other argument types are converted by
812 /// UsualUnaryConversions().
813 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
814   QualType Ty = E->getType();
815   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
816
817   ExprResult Res = UsualUnaryConversions(E);
818   if (Res.isInvalid())
819     return ExprError();
820   E = Res.get();
821
822   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
823   // double.
824   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
825   if (BTy && (BTy->getKind() == BuiltinType::Half ||
826               BTy->getKind() == BuiltinType::Float)) {
827     if (getLangOpts().OpenCL &&
828         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
829         if (BTy->getKind() == BuiltinType::Half) {
830             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
831         }
832     } else {
833       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
834     }
835   }
836
837   // C++ performs lvalue-to-rvalue conversion as a default argument
838   // promotion, even on class types, but note:
839   //   C++11 [conv.lval]p2:
840   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
841   //     operand or a subexpression thereof the value contained in the
842   //     referenced object is not accessed. Otherwise, if the glvalue
843   //     has a class type, the conversion copy-initializes a temporary
844   //     of type T from the glvalue and the result of the conversion
845   //     is a prvalue for the temporary.
846   // FIXME: add some way to gate this entire thing for correctness in
847   // potentially potentially evaluated contexts.
848   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
849     ExprResult Temp = PerformCopyInitialization(
850                        InitializedEntity::InitializeTemporary(E->getType()),
851                                                 E->getExprLoc(), E);
852     if (Temp.isInvalid())
853       return ExprError();
854     E = Temp.get();
855   }
856
857   return E;
858 }
859
860 /// Determine the degree of POD-ness for an expression.
861 /// Incomplete types are considered POD, since this check can be performed
862 /// when we're in an unevaluated context.
863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
864   if (Ty->isIncompleteType()) {
865     // C++11 [expr.call]p7:
866     //   After these conversions, if the argument does not have arithmetic,
867     //   enumeration, pointer, pointer to member, or class type, the program
868     //   is ill-formed.
869     //
870     // Since we've already performed array-to-pointer and function-to-pointer
871     // decay, the only such type in C++ is cv void. This also handles
872     // initializer lists as variadic arguments.
873     if (Ty->isVoidType())
874       return VAK_Invalid;
875
876     if (Ty->isObjCObjectType())
877       return VAK_Invalid;
878     return VAK_Valid;
879   }
880
881   if (Ty.isCXX98PODType(Context))
882     return VAK_Valid;
883
884   // C++11 [expr.call]p7:
885   //   Passing a potentially-evaluated argument of class type (Clause 9)
886   //   having a non-trivial copy constructor, a non-trivial move constructor,
887   //   or a non-trivial destructor, with no corresponding parameter,
888   //   is conditionally-supported with implementation-defined semantics.
889   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
890     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
891       if (!Record->hasNonTrivialCopyConstructor() &&
892           !Record->hasNonTrivialMoveConstructor() &&
893           !Record->hasNonTrivialDestructor())
894         return VAK_ValidInCXX11;
895
896   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
897     return VAK_Valid;
898
899   if (Ty->isObjCObjectType())
900     return VAK_Invalid;
901
902   if (getLangOpts().MSVCCompat)
903     return VAK_MSVCUndefined;
904
905   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
906   // permitted to reject them. We should consider doing so.
907   return VAK_Undefined;
908 }
909
910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
911   // Don't allow one to pass an Objective-C interface to a vararg.
912   const QualType &Ty = E->getType();
913   VarArgKind VAK = isValidVarArgType(Ty);
914
915   // Complain about passing non-POD types through varargs.
916   switch (VAK) {
917   case VAK_ValidInCXX11:
918     DiagRuntimeBehavior(
919         E->getLocStart(), nullptr,
920         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
921           << Ty << CT);
922     // Fall through.
923   case VAK_Valid:
924     if (Ty->isRecordType()) {
925       // This is unlikely to be what the user intended. If the class has a
926       // 'c_str' member function, the user probably meant to call that.
927       DiagRuntimeBehavior(E->getLocStart(), nullptr,
928                           PDiag(diag::warn_pass_class_arg_to_vararg)
929                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
930     }
931     break;
932
933   case VAK_Undefined:
934   case VAK_MSVCUndefined:
935     DiagRuntimeBehavior(
936         E->getLocStart(), nullptr,
937         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
938           << getLangOpts().CPlusPlus11 << Ty << CT);
939     break;
940
941   case VAK_Invalid:
942     if (Ty->isObjCObjectType())
943       DiagRuntimeBehavior(
944           E->getLocStart(), nullptr,
945           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
946             << Ty << CT);
947     else
948       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
949         << isa<InitListExpr>(E) << Ty << CT;
950     break;
951   }
952 }
953
954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
955 /// will create a trap if the resulting type is not a POD type.
956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
957                                                   FunctionDecl *FDecl) {
958   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
959     // Strip the unbridged-cast placeholder expression off, if applicable.
960     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
961         (CT == VariadicMethod ||
962          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
963       E = stripARCUnbridgedCast(E);
964
965     // Otherwise, do normal placeholder checking.
966     } else {
967       ExprResult ExprRes = CheckPlaceholderExpr(E);
968       if (ExprRes.isInvalid())
969         return ExprError();
970       E = ExprRes.get();
971     }
972   }
973   
974   ExprResult ExprRes = DefaultArgumentPromotion(E);
975   if (ExprRes.isInvalid())
976     return ExprError();
977   E = ExprRes.get();
978
979   // Diagnostics regarding non-POD argument types are
980   // emitted along with format string checking in Sema::CheckFunctionCall().
981   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
982     // Turn this into a trap.
983     CXXScopeSpec SS;
984     SourceLocation TemplateKWLoc;
985     UnqualifiedId Name;
986     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
987                        E->getLocStart());
988     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
989                                           Name, true, false);
990     if (TrapFn.isInvalid())
991       return ExprError();
992
993     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
994                                     E->getLocStart(), None,
995                                     E->getLocEnd());
996     if (Call.isInvalid())
997       return ExprError();
998
999     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1000                                   Call.get(), E);
1001     if (Comma.isInvalid())
1002       return ExprError();
1003     return Comma.get();
1004   }
1005
1006   if (!getLangOpts().CPlusPlus &&
1007       RequireCompleteType(E->getExprLoc(), E->getType(),
1008                           diag::err_call_incomplete_argument))
1009     return ExprError();
1010
1011   return E;
1012 }
1013
1014 /// \brief Converts an integer to complex float type.  Helper function of
1015 /// UsualArithmeticConversions()
1016 ///
1017 /// \return false if the integer expression is an integer type and is
1018 /// successfully converted to the complex type.
1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1020                                                   ExprResult &ComplexExpr,
1021                                                   QualType IntTy,
1022                                                   QualType ComplexTy,
1023                                                   bool SkipCast) {
1024   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1025   if (SkipCast) return false;
1026   if (IntTy->isIntegerType()) {
1027     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1029     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1030                                   CK_FloatingRealToComplex);
1031   } else {
1032     assert(IntTy->isComplexIntegerType());
1033     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1034                                   CK_IntegralComplexToFloatingComplex);
1035   }
1036   return false;
1037 }
1038
1039 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1040 /// UsualArithmeticConversions()
1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1042                                              ExprResult &RHS, QualType LHSType,
1043                                              QualType RHSType,
1044                                              bool IsCompAssign) {
1045   // if we have an integer operand, the result is the complex type.
1046   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1047                                              /*skipCast*/false))
1048     return LHSType;
1049   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1050                                              /*skipCast*/IsCompAssign))
1051     return RHSType;
1052
1053   // This handles complex/complex, complex/float, or float/complex.
1054   // When both operands are complex, the shorter operand is converted to the
1055   // type of the longer, and that is the type of the result. This corresponds
1056   // to what is done when combining two real floating-point operands.
1057   // The fun begins when size promotion occur across type domains.
1058   // From H&S 6.3.4: When one operand is complex and the other is a real
1059   // floating-point type, the less precise type is converted, within it's
1060   // real or complex domain, to the precision of the other type. For example,
1061   // when combining a "long double" with a "double _Complex", the
1062   // "double _Complex" is promoted to "long double _Complex".
1063
1064   // Compute the rank of the two types, regardless of whether they are complex.
1065   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1066
1067   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1068   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1069   QualType LHSElementType =
1070       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1071   QualType RHSElementType =
1072       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1073
1074   QualType ResultType = S.Context.getComplexType(LHSElementType);
1075   if (Order < 0) {
1076     // Promote the precision of the LHS if not an assignment.
1077     ResultType = S.Context.getComplexType(RHSElementType);
1078     if (!IsCompAssign) {
1079       if (LHSComplexType)
1080         LHS =
1081             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1082       else
1083         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1084     }
1085   } else if (Order > 0) {
1086     // Promote the precision of the RHS.
1087     if (RHSComplexType)
1088       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1089     else
1090       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1091   }
1092   return ResultType;
1093 }
1094
1095 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1096 /// of UsualArithmeticConversions()
1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1098                                            ExprResult &IntExpr,
1099                                            QualType FloatTy, QualType IntTy,
1100                                            bool ConvertFloat, bool ConvertInt) {
1101   if (IntTy->isIntegerType()) {
1102     if (ConvertInt)
1103       // Convert intExpr to the lhs floating point type.
1104       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1105                                     CK_IntegralToFloating);
1106     return FloatTy;
1107   }
1108      
1109   // Convert both sides to the appropriate complex float.
1110   assert(IntTy->isComplexIntegerType());
1111   QualType result = S.Context.getComplexType(FloatTy);
1112
1113   // _Complex int -> _Complex float
1114   if (ConvertInt)
1115     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1116                                   CK_IntegralComplexToFloatingComplex);
1117
1118   // float -> _Complex float
1119   if (ConvertFloat)
1120     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1121                                     CK_FloatingRealToComplex);
1122
1123   return result;
1124 }
1125
1126 /// \brief Handle arithmethic conversion with floating point types.  Helper
1127 /// function of UsualArithmeticConversions()
1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1129                                       ExprResult &RHS, QualType LHSType,
1130                                       QualType RHSType, bool IsCompAssign) {
1131   bool LHSFloat = LHSType->isRealFloatingType();
1132   bool RHSFloat = RHSType->isRealFloatingType();
1133
1134   // If we have two real floating types, convert the smaller operand
1135   // to the bigger result.
1136   if (LHSFloat && RHSFloat) {
1137     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1138     if (order > 0) {
1139       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1140       return LHSType;
1141     }
1142
1143     assert(order < 0 && "illegal float comparison");
1144     if (!IsCompAssign)
1145       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1146     return RHSType;
1147   }
1148
1149   if (LHSFloat) {
1150     // Half FP has to be promoted to float unless it is natively supported
1151     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1152       LHSType = S.Context.FloatTy;
1153
1154     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1155                                       /*convertFloat=*/!IsCompAssign,
1156                                       /*convertInt=*/ true);
1157   }
1158   assert(RHSFloat);
1159   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1160                                     /*convertInt=*/ true,
1161                                     /*convertFloat=*/!IsCompAssign);
1162 }
1163
1164 /// \brief Diagnose attempts to convert between __float128 and long double if
1165 /// there is no support for such conversion. Helper function of
1166 /// UsualArithmeticConversions().
1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1168                                       QualType RHSType) {
1169   /*  No issue converting if at least one of the types is not a floating point
1170       type or the two types have the same rank.
1171   */
1172   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1173       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1174     return false;
1175
1176   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1177          "The remaining types must be floating point types.");
1178
1179   auto *LHSComplex = LHSType->getAs<ComplexType>();
1180   auto *RHSComplex = RHSType->getAs<ComplexType>();
1181
1182   QualType LHSElemType = LHSComplex ?
1183     LHSComplex->getElementType() : LHSType;
1184   QualType RHSElemType = RHSComplex ?
1185     RHSComplex->getElementType() : RHSType;
1186
1187   // No issue if the two types have the same representation
1188   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1189       &S.Context.getFloatTypeSemantics(RHSElemType))
1190     return false;
1191
1192   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1193                                 RHSElemType == S.Context.LongDoubleTy);
1194   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1195                             RHSElemType == S.Context.Float128Ty);
1196
1197   /* We've handled the situation where __float128 and long double have the same
1198      representation. The only other allowable conversion is if long double is
1199      really just double.
1200   */
1201   return Float128AndLongDouble &&
1202     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1203      &llvm::APFloat::IEEEdouble());
1204 }
1205
1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1207
1208 namespace {
1209 /// These helper callbacks are placed in an anonymous namespace to
1210 /// permit their use as function template parameters.
1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1212   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1213 }
1214
1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1216   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1217                              CK_IntegralComplexCast);
1218 }
1219 }
1220
1221 /// \brief Handle integer arithmetic conversions.  Helper function of
1222 /// UsualArithmeticConversions()
1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1225                                         ExprResult &RHS, QualType LHSType,
1226                                         QualType RHSType, bool IsCompAssign) {
1227   // The rules for this case are in C99 6.3.1.8
1228   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1229   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1230   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1231   if (LHSSigned == RHSSigned) {
1232     // Same signedness; use the higher-ranked type
1233     if (order >= 0) {
1234       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1235       return LHSType;
1236     } else if (!IsCompAssign)
1237       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1238     return RHSType;
1239   } else if (order != (LHSSigned ? 1 : -1)) {
1240     // The unsigned type has greater than or equal rank to the
1241     // signed type, so use the unsigned type
1242     if (RHSSigned) {
1243       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1244       return LHSType;
1245     } else if (!IsCompAssign)
1246       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1247     return RHSType;
1248   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1249     // The two types are different widths; if we are here, that
1250     // means the signed type is larger than the unsigned type, so
1251     // use the signed type.
1252     if (LHSSigned) {
1253       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1254       return LHSType;
1255     } else if (!IsCompAssign)
1256       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1257     return RHSType;
1258   } else {
1259     // The signed type is higher-ranked than the unsigned type,
1260     // but isn't actually any bigger (like unsigned int and long
1261     // on most 32-bit systems).  Use the unsigned type corresponding
1262     // to the signed type.
1263     QualType result =
1264       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1265     RHS = (*doRHSCast)(S, RHS.get(), result);
1266     if (!IsCompAssign)
1267       LHS = (*doLHSCast)(S, LHS.get(), result);
1268     return result;
1269   }
1270 }
1271
1272 /// \brief Handle conversions with GCC complex int extension.  Helper function
1273 /// of UsualArithmeticConversions()
1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1275                                            ExprResult &RHS, QualType LHSType,
1276                                            QualType RHSType,
1277                                            bool IsCompAssign) {
1278   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1279   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1280
1281   if (LHSComplexInt && RHSComplexInt) {
1282     QualType LHSEltType = LHSComplexInt->getElementType();
1283     QualType RHSEltType = RHSComplexInt->getElementType();
1284     QualType ScalarType =
1285       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1286         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1287
1288     return S.Context.getComplexType(ScalarType);
1289   }
1290
1291   if (LHSComplexInt) {
1292     QualType LHSEltType = LHSComplexInt->getElementType();
1293     QualType ScalarType =
1294       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1295         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1296     QualType ComplexType = S.Context.getComplexType(ScalarType);
1297     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1298                               CK_IntegralRealToComplex);
1299  
1300     return ComplexType;
1301   }
1302
1303   assert(RHSComplexInt);
1304
1305   QualType RHSEltType = RHSComplexInt->getElementType();
1306   QualType ScalarType =
1307     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1308       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1309   QualType ComplexType = S.Context.getComplexType(ScalarType);
1310   
1311   if (!IsCompAssign)
1312     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1313                               CK_IntegralRealToComplex);
1314   return ComplexType;
1315 }
1316
1317 /// UsualArithmeticConversions - Performs various conversions that are common to
1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1319 /// routine returns the first non-arithmetic type found. The client is
1320 /// responsible for emitting appropriate error diagnostics.
1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1322                                           bool IsCompAssign) {
1323   if (!IsCompAssign) {
1324     LHS = UsualUnaryConversions(LHS.get());
1325     if (LHS.isInvalid())
1326       return QualType();
1327   }
1328
1329   RHS = UsualUnaryConversions(RHS.get());
1330   if (RHS.isInvalid())
1331     return QualType();
1332
1333   // For conversion purposes, we ignore any qualifiers.
1334   // For example, "const float" and "float" are equivalent.
1335   QualType LHSType =
1336     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1337   QualType RHSType =
1338     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1339
1340   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1341   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1342     LHSType = AtomicLHS->getValueType();
1343
1344   // If both types are identical, no conversion is needed.
1345   if (LHSType == RHSType)
1346     return LHSType;
1347
1348   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1349   // The caller can deal with this (e.g. pointer + int).
1350   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1351     return QualType();
1352
1353   // Apply unary and bitfield promotions to the LHS's type.
1354   QualType LHSUnpromotedType = LHSType;
1355   if (LHSType->isPromotableIntegerType())
1356     LHSType = Context.getPromotedIntegerType(LHSType);
1357   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1358   if (!LHSBitfieldPromoteTy.isNull())
1359     LHSType = LHSBitfieldPromoteTy;
1360   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1361     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1362
1363   // If both types are identical, no conversion is needed.
1364   if (LHSType == RHSType)
1365     return LHSType;
1366
1367   // At this point, we have two different arithmetic types.
1368
1369   // Diagnose attempts to convert between __float128 and long double where
1370   // such conversions currently can't be handled.
1371   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1372     return QualType();
1373
1374   // Handle complex types first (C99 6.3.1.8p1).
1375   if (LHSType->isComplexType() || RHSType->isComplexType())
1376     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1377                                         IsCompAssign);
1378
1379   // Now handle "real" floating types (i.e. float, double, long double).
1380   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1381     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1382                                  IsCompAssign);
1383
1384   // Handle GCC complex int extension.
1385   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1386     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1387                                       IsCompAssign);
1388
1389   // Finally, we have two differing integer types.
1390   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1391            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1392 }
1393
1394
1395 //===----------------------------------------------------------------------===//
1396 //  Semantic Analysis for various Expression Types
1397 //===----------------------------------------------------------------------===//
1398
1399
1400 ExprResult
1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1402                                 SourceLocation DefaultLoc,
1403                                 SourceLocation RParenLoc,
1404                                 Expr *ControllingExpr,
1405                                 ArrayRef<ParsedType> ArgTypes,
1406                                 ArrayRef<Expr *> ArgExprs) {
1407   unsigned NumAssocs = ArgTypes.size();
1408   assert(NumAssocs == ArgExprs.size());
1409
1410   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1411   for (unsigned i = 0; i < NumAssocs; ++i) {
1412     if (ArgTypes[i])
1413       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1414     else
1415       Types[i] = nullptr;
1416   }
1417
1418   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1419                                              ControllingExpr,
1420                                              llvm::makeArrayRef(Types, NumAssocs),
1421                                              ArgExprs);
1422   delete [] Types;
1423   return ER;
1424 }
1425
1426 ExprResult
1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1428                                  SourceLocation DefaultLoc,
1429                                  SourceLocation RParenLoc,
1430                                  Expr *ControllingExpr,
1431                                  ArrayRef<TypeSourceInfo *> Types,
1432                                  ArrayRef<Expr *> Exprs) {
1433   unsigned NumAssocs = Types.size();
1434   assert(NumAssocs == Exprs.size());
1435
1436   // Decay and strip qualifiers for the controlling expression type, and handle
1437   // placeholder type replacement. See committee discussion from WG14 DR423.
1438   {
1439     EnterExpressionEvaluationContext Unevaluated(
1440         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1441     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1442     if (R.isInvalid())
1443       return ExprError();
1444     ControllingExpr = R.get();
1445   }
1446
1447   // The controlling expression is an unevaluated operand, so side effects are
1448   // likely unintended.
1449   if (!inTemplateInstantiation() &&
1450       ControllingExpr->HasSideEffects(Context, false))
1451     Diag(ControllingExpr->getExprLoc(),
1452          diag::warn_side_effects_unevaluated_context);
1453
1454   bool TypeErrorFound = false,
1455        IsResultDependent = ControllingExpr->isTypeDependent(),
1456        ContainsUnexpandedParameterPack
1457          = ControllingExpr->containsUnexpandedParameterPack();
1458
1459   for (unsigned i = 0; i < NumAssocs; ++i) {
1460     if (Exprs[i]->containsUnexpandedParameterPack())
1461       ContainsUnexpandedParameterPack = true;
1462
1463     if (Types[i]) {
1464       if (Types[i]->getType()->containsUnexpandedParameterPack())
1465         ContainsUnexpandedParameterPack = true;
1466
1467       if (Types[i]->getType()->isDependentType()) {
1468         IsResultDependent = true;
1469       } else {
1470         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1471         // complete object type other than a variably modified type."
1472         unsigned D = 0;
1473         if (Types[i]->getType()->isIncompleteType())
1474           D = diag::err_assoc_type_incomplete;
1475         else if (!Types[i]->getType()->isObjectType())
1476           D = diag::err_assoc_type_nonobject;
1477         else if (Types[i]->getType()->isVariablyModifiedType())
1478           D = diag::err_assoc_type_variably_modified;
1479
1480         if (D != 0) {
1481           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1482             << Types[i]->getTypeLoc().getSourceRange()
1483             << Types[i]->getType();
1484           TypeErrorFound = true;
1485         }
1486
1487         // C11 6.5.1.1p2 "No two generic associations in the same generic
1488         // selection shall specify compatible types."
1489         for (unsigned j = i+1; j < NumAssocs; ++j)
1490           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1491               Context.typesAreCompatible(Types[i]->getType(),
1492                                          Types[j]->getType())) {
1493             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1494                  diag::err_assoc_compatible_types)
1495               << Types[j]->getTypeLoc().getSourceRange()
1496               << Types[j]->getType()
1497               << Types[i]->getType();
1498             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1499                  diag::note_compat_assoc)
1500               << Types[i]->getTypeLoc().getSourceRange()
1501               << Types[i]->getType();
1502             TypeErrorFound = true;
1503           }
1504       }
1505     }
1506   }
1507   if (TypeErrorFound)
1508     return ExprError();
1509
1510   // If we determined that the generic selection is result-dependent, don't
1511   // try to compute the result expression.
1512   if (IsResultDependent)
1513     return new (Context) GenericSelectionExpr(
1514         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1515         ContainsUnexpandedParameterPack);
1516
1517   SmallVector<unsigned, 1> CompatIndices;
1518   unsigned DefaultIndex = -1U;
1519   for (unsigned i = 0; i < NumAssocs; ++i) {
1520     if (!Types[i])
1521       DefaultIndex = i;
1522     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1523                                         Types[i]->getType()))
1524       CompatIndices.push_back(i);
1525   }
1526
1527   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1528   // type compatible with at most one of the types named in its generic
1529   // association list."
1530   if (CompatIndices.size() > 1) {
1531     // We strip parens here because the controlling expression is typically
1532     // parenthesized in macro definitions.
1533     ControllingExpr = ControllingExpr->IgnoreParens();
1534     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1535       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1536       << (unsigned) CompatIndices.size();
1537     for (unsigned I : CompatIndices) {
1538       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1539            diag::note_compat_assoc)
1540         << Types[I]->getTypeLoc().getSourceRange()
1541         << Types[I]->getType();
1542     }
1543     return ExprError();
1544   }
1545
1546   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1547   // its controlling expression shall have type compatible with exactly one of
1548   // the types named in its generic association list."
1549   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1550     // We strip parens here because the controlling expression is typically
1551     // parenthesized in macro definitions.
1552     ControllingExpr = ControllingExpr->IgnoreParens();
1553     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1554       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1555     return ExprError();
1556   }
1557
1558   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1559   // type name that is compatible with the type of the controlling expression,
1560   // then the result expression of the generic selection is the expression
1561   // in that generic association. Otherwise, the result expression of the
1562   // generic selection is the expression in the default generic association."
1563   unsigned ResultIndex =
1564     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1565
1566   return new (Context) GenericSelectionExpr(
1567       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1568       ContainsUnexpandedParameterPack, ResultIndex);
1569 }
1570
1571 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1572 /// location of the token and the offset of the ud-suffix within it.
1573 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1574                                      unsigned Offset) {
1575   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1576                                         S.getLangOpts());
1577 }
1578
1579 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1580 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1581 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1582                                                  IdentifierInfo *UDSuffix,
1583                                                  SourceLocation UDSuffixLoc,
1584                                                  ArrayRef<Expr*> Args,
1585                                                  SourceLocation LitEndLoc) {
1586   assert(Args.size() <= 2 && "too many arguments for literal operator");
1587
1588   QualType ArgTy[2];
1589   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1590     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1591     if (ArgTy[ArgIdx]->isArrayType())
1592       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1593   }
1594
1595   DeclarationName OpName =
1596     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1597   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1598   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1599
1600   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1601   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1602                               /*AllowRaw*/false, /*AllowTemplate*/false,
1603                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1604     return ExprError();
1605
1606   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1607 }
1608
1609 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1610 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1611 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1612 /// multiple tokens.  However, the common case is that StringToks points to one
1613 /// string.
1614 ///
1615 ExprResult
1616 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1617   assert(!StringToks.empty() && "Must have at least one string!");
1618
1619   StringLiteralParser Literal(StringToks, PP);
1620   if (Literal.hadError)
1621     return ExprError();
1622
1623   SmallVector<SourceLocation, 4> StringTokLocs;
1624   for (const Token &Tok : StringToks)
1625     StringTokLocs.push_back(Tok.getLocation());
1626
1627   QualType CharTy = Context.CharTy;
1628   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1629   if (Literal.isWide()) {
1630     CharTy = Context.getWideCharType();
1631     Kind = StringLiteral::Wide;
1632   } else if (Literal.isUTF8()) {
1633     Kind = StringLiteral::UTF8;
1634   } else if (Literal.isUTF16()) {
1635     CharTy = Context.Char16Ty;
1636     Kind = StringLiteral::UTF16;
1637   } else if (Literal.isUTF32()) {
1638     CharTy = Context.Char32Ty;
1639     Kind = StringLiteral::UTF32;
1640   } else if (Literal.isPascal()) {
1641     CharTy = Context.UnsignedCharTy;
1642   }
1643
1644   QualType CharTyConst = CharTy;
1645   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1646   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1647     CharTyConst.addConst();
1648
1649   // Get an array type for the string, according to C99 6.4.5.  This includes
1650   // the nul terminator character as well as the string length for pascal
1651   // strings.
1652   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1653                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1654                                  ArrayType::Normal, 0);
1655
1656   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1657   if (getLangOpts().OpenCL) {
1658     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1659   }
1660
1661   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1662   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1663                                              Kind, Literal.Pascal, StrTy,
1664                                              &StringTokLocs[0],
1665                                              StringTokLocs.size());
1666   if (Literal.getUDSuffix().empty())
1667     return Lit;
1668
1669   // We're building a user-defined literal.
1670   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1671   SourceLocation UDSuffixLoc =
1672     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1673                    Literal.getUDSuffixOffset());
1674
1675   // Make sure we're allowed user-defined literals here.
1676   if (!UDLScope)
1677     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1678
1679   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1680   //   operator "" X (str, len)
1681   QualType SizeType = Context.getSizeType();
1682
1683   DeclarationName OpName =
1684     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1685   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1686   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1687
1688   QualType ArgTy[] = {
1689     Context.getArrayDecayedType(StrTy), SizeType
1690   };
1691
1692   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1693   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1694                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1695                                 /*AllowStringTemplate*/true)) {
1696
1697   case LOLR_Cooked: {
1698     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1699     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1700                                                     StringTokLocs[0]);
1701     Expr *Args[] = { Lit, LenArg };
1702
1703     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1704   }
1705
1706   case LOLR_StringTemplate: {
1707     TemplateArgumentListInfo ExplicitArgs;
1708
1709     unsigned CharBits = Context.getIntWidth(CharTy);
1710     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1711     llvm::APSInt Value(CharBits, CharIsUnsigned);
1712
1713     TemplateArgument TypeArg(CharTy);
1714     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1715     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1716
1717     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1718       Value = Lit->getCodeUnit(I);
1719       TemplateArgument Arg(Context, Value, CharTy);
1720       TemplateArgumentLocInfo ArgInfo;
1721       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1722     }
1723     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1724                                     &ExplicitArgs);
1725   }
1726   case LOLR_Raw:
1727   case LOLR_Template:
1728     llvm_unreachable("unexpected literal operator lookup result");
1729   case LOLR_Error:
1730     return ExprError();
1731   }
1732   llvm_unreachable("unexpected literal operator lookup result");
1733 }
1734
1735 ExprResult
1736 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1737                        SourceLocation Loc,
1738                        const CXXScopeSpec *SS) {
1739   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1740   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1741 }
1742
1743 /// BuildDeclRefExpr - Build an expression that references a
1744 /// declaration that does not require a closure capture.
1745 ExprResult
1746 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1747                        const DeclarationNameInfo &NameInfo,
1748                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1749                        const TemplateArgumentListInfo *TemplateArgs) {
1750   bool RefersToCapturedVariable =
1751       isa<VarDecl>(D) &&
1752       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1753
1754   DeclRefExpr *E;
1755   if (isa<VarTemplateSpecializationDecl>(D)) {
1756     VarTemplateSpecializationDecl *VarSpec =
1757         cast<VarTemplateSpecializationDecl>(D);
1758
1759     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1760                                         : NestedNameSpecifierLoc(),
1761                             VarSpec->getTemplateKeywordLoc(), D,
1762                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1763                             FoundD, TemplateArgs);
1764   } else {
1765     assert(!TemplateArgs && "No template arguments for non-variable"
1766                             " template specialization references");
1767     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1768                                         : NestedNameSpecifierLoc(),
1769                             SourceLocation(), D, RefersToCapturedVariable,
1770                             NameInfo, Ty, VK, FoundD);
1771   }
1772
1773   MarkDeclRefReferenced(E);
1774
1775   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1776       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1777       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1778       recordUseOfEvaluatedWeak(E);
1779
1780   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1781   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1782     FD = IFD->getAnonField();
1783   if (FD) {
1784     UnusedPrivateFields.remove(FD);
1785     // Just in case we're building an illegal pointer-to-member.
1786     if (FD->isBitField())
1787       E->setObjectKind(OK_BitField);
1788   }
1789
1790   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1791   // designates a bit-field.
1792   if (auto *BD = dyn_cast<BindingDecl>(D))
1793     if (auto *BE = BD->getBinding())
1794       E->setObjectKind(BE->getObjectKind());
1795
1796   return E;
1797 }
1798
1799 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1800 /// possibly a list of template arguments.
1801 ///
1802 /// If this produces template arguments, it is permitted to call
1803 /// DecomposeTemplateName.
1804 ///
1805 /// This actually loses a lot of source location information for
1806 /// non-standard name kinds; we should consider preserving that in
1807 /// some way.
1808 void
1809 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1810                              TemplateArgumentListInfo &Buffer,
1811                              DeclarationNameInfo &NameInfo,
1812                              const TemplateArgumentListInfo *&TemplateArgs) {
1813   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1814     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1815     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1816
1817     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1818                                        Id.TemplateId->NumArgs);
1819     translateTemplateArguments(TemplateArgsPtr, Buffer);
1820
1821     TemplateName TName = Id.TemplateId->Template.get();
1822     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1823     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1824     TemplateArgs = &Buffer;
1825   } else {
1826     NameInfo = GetNameFromUnqualifiedId(Id);
1827     TemplateArgs = nullptr;
1828   }
1829 }
1830
1831 static void emitEmptyLookupTypoDiagnostic(
1832     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1833     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1834     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1835   DeclContext *Ctx =
1836       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1837   if (!TC) {
1838     // Emit a special diagnostic for failed member lookups.
1839     // FIXME: computing the declaration context might fail here (?)
1840     if (Ctx)
1841       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1842                                                  << SS.getRange();
1843     else
1844       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1845     return;
1846   }
1847
1848   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1849   bool DroppedSpecifier =
1850       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1851   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1852                         ? diag::note_implicit_param_decl
1853                         : diag::note_previous_decl;
1854   if (!Ctx)
1855     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1856                          SemaRef.PDiag(NoteID));
1857   else
1858     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1859                                  << Typo << Ctx << DroppedSpecifier
1860                                  << SS.getRange(),
1861                          SemaRef.PDiag(NoteID));
1862 }
1863
1864 /// Diagnose an empty lookup.
1865 ///
1866 /// \return false if new lookup candidates were found
1867 bool
1868 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1869                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1870                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1871                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1872   DeclarationName Name = R.getLookupName();
1873
1874   unsigned diagnostic = diag::err_undeclared_var_use;
1875   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1876   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1877       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1878       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1879     diagnostic = diag::err_undeclared_use;
1880     diagnostic_suggest = diag::err_undeclared_use_suggest;
1881   }
1882
1883   // If the original lookup was an unqualified lookup, fake an
1884   // unqualified lookup.  This is useful when (for example) the
1885   // original lookup would not have found something because it was a
1886   // dependent name.
1887   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1888   while (DC) {
1889     if (isa<CXXRecordDecl>(DC)) {
1890       LookupQualifiedName(R, DC);
1891
1892       if (!R.empty()) {
1893         // Don't give errors about ambiguities in this lookup.
1894         R.suppressDiagnostics();
1895
1896         // During a default argument instantiation the CurContext points
1897         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1898         // function parameter list, hence add an explicit check.
1899         bool isDefaultArgument =
1900             !CodeSynthesisContexts.empty() &&
1901             CodeSynthesisContexts.back().Kind ==
1902                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1903         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1904         bool isInstance = CurMethod &&
1905                           CurMethod->isInstance() &&
1906                           DC == CurMethod->getParent() && !isDefaultArgument;
1907
1908         // Give a code modification hint to insert 'this->'.
1909         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1910         // Actually quite difficult!
1911         if (getLangOpts().MSVCCompat)
1912           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1913         if (isInstance) {
1914           Diag(R.getNameLoc(), diagnostic) << Name
1915             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1916           CheckCXXThisCapture(R.getNameLoc());
1917         } else {
1918           Diag(R.getNameLoc(), diagnostic) << Name;
1919         }
1920
1921         // Do we really want to note all of these?
1922         for (NamedDecl *D : R)
1923           Diag(D->getLocation(), diag::note_dependent_var_use);
1924
1925         // Return true if we are inside a default argument instantiation
1926         // and the found name refers to an instance member function, otherwise
1927         // the function calling DiagnoseEmptyLookup will try to create an
1928         // implicit member call and this is wrong for default argument.
1929         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1930           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1931           return true;
1932         }
1933
1934         // Tell the callee to try to recover.
1935         return false;
1936       }
1937
1938       R.clear();
1939     }
1940
1941     // In Microsoft mode, if we are performing lookup from within a friend
1942     // function definition declared at class scope then we must set
1943     // DC to the lexical parent to be able to search into the parent
1944     // class.
1945     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1946         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1947         DC->getLexicalParent()->isRecord())
1948       DC = DC->getLexicalParent();
1949     else
1950       DC = DC->getParent();
1951   }
1952
1953   // We didn't find anything, so try to correct for a typo.
1954   TypoCorrection Corrected;
1955   if (S && Out) {
1956     SourceLocation TypoLoc = R.getNameLoc();
1957     assert(!ExplicitTemplateArgs &&
1958            "Diagnosing an empty lookup with explicit template args!");
1959     *Out = CorrectTypoDelayed(
1960         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1961         [=](const TypoCorrection &TC) {
1962           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1963                                         diagnostic, diagnostic_suggest);
1964         },
1965         nullptr, CTK_ErrorRecovery);
1966     if (*Out)
1967       return true;
1968   } else if (S && (Corrected =
1969                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1970                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1971     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1972     bool DroppedSpecifier =
1973         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1974     R.setLookupName(Corrected.getCorrection());
1975
1976     bool AcceptableWithRecovery = false;
1977     bool AcceptableWithoutRecovery = false;
1978     NamedDecl *ND = Corrected.getFoundDecl();
1979     if (ND) {
1980       if (Corrected.isOverloaded()) {
1981         OverloadCandidateSet OCS(R.getNameLoc(),
1982                                  OverloadCandidateSet::CSK_Normal);
1983         OverloadCandidateSet::iterator Best;
1984         for (NamedDecl *CD : Corrected) {
1985           if (FunctionTemplateDecl *FTD =
1986                    dyn_cast<FunctionTemplateDecl>(CD))
1987             AddTemplateOverloadCandidate(
1988                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1989                 Args, OCS);
1990           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1991             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1992               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1993                                    Args, OCS);
1994         }
1995         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1996         case OR_Success:
1997           ND = Best->FoundDecl;
1998           Corrected.setCorrectionDecl(ND);
1999           break;
2000         default:
2001           // FIXME: Arbitrarily pick the first declaration for the note.
2002           Corrected.setCorrectionDecl(ND);
2003           break;
2004         }
2005       }
2006       R.addDecl(ND);
2007       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2008         CXXRecordDecl *Record = nullptr;
2009         if (Corrected.getCorrectionSpecifier()) {
2010           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2011           Record = Ty->getAsCXXRecordDecl();
2012         }
2013         if (!Record)
2014           Record = cast<CXXRecordDecl>(
2015               ND->getDeclContext()->getRedeclContext());
2016         R.setNamingClass(Record);
2017       }
2018
2019       auto *UnderlyingND = ND->getUnderlyingDecl();
2020       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2021                                isa<FunctionTemplateDecl>(UnderlyingND);
2022       // FIXME: If we ended up with a typo for a type name or
2023       // Objective-C class name, we're in trouble because the parser
2024       // is in the wrong place to recover. Suggest the typo
2025       // correction, but don't make it a fix-it since we're not going
2026       // to recover well anyway.
2027       AcceptableWithoutRecovery =
2028           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2029     } else {
2030       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2031       // because we aren't able to recover.
2032       AcceptableWithoutRecovery = true;
2033     }
2034
2035     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2036       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2037                             ? diag::note_implicit_param_decl
2038                             : diag::note_previous_decl;
2039       if (SS.isEmpty())
2040         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2041                      PDiag(NoteID), AcceptableWithRecovery);
2042       else
2043         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2044                                   << Name << computeDeclContext(SS, false)
2045                                   << DroppedSpecifier << SS.getRange(),
2046                      PDiag(NoteID), AcceptableWithRecovery);
2047
2048       // Tell the callee whether to try to recover.
2049       return !AcceptableWithRecovery;
2050     }
2051   }
2052   R.clear();
2053
2054   // Emit a special diagnostic for failed member lookups.
2055   // FIXME: computing the declaration context might fail here (?)
2056   if (!SS.isEmpty()) {
2057     Diag(R.getNameLoc(), diag::err_no_member)
2058       << Name << computeDeclContext(SS, false)
2059       << SS.getRange();
2060     return true;
2061   }
2062
2063   // Give up, we can't recover.
2064   Diag(R.getNameLoc(), diagnostic) << Name;
2065   return true;
2066 }
2067
2068 /// In Microsoft mode, if we are inside a template class whose parent class has
2069 /// dependent base classes, and we can't resolve an unqualified identifier, then
2070 /// assume the identifier is a member of a dependent base class.  We can only
2071 /// recover successfully in static methods, instance methods, and other contexts
2072 /// where 'this' is available.  This doesn't precisely match MSVC's
2073 /// instantiation model, but it's close enough.
2074 static Expr *
2075 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2076                                DeclarationNameInfo &NameInfo,
2077                                SourceLocation TemplateKWLoc,
2078                                const TemplateArgumentListInfo *TemplateArgs) {
2079   // Only try to recover from lookup into dependent bases in static methods or
2080   // contexts where 'this' is available.
2081   QualType ThisType = S.getCurrentThisType();
2082   const CXXRecordDecl *RD = nullptr;
2083   if (!ThisType.isNull())
2084     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2085   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2086     RD = MD->getParent();
2087   if (!RD || !RD->hasAnyDependentBases())
2088     return nullptr;
2089
2090   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2091   // is available, suggest inserting 'this->' as a fixit.
2092   SourceLocation Loc = NameInfo.getLoc();
2093   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2094   DB << NameInfo.getName() << RD;
2095
2096   if (!ThisType.isNull()) {
2097     DB << FixItHint::CreateInsertion(Loc, "this->");
2098     return CXXDependentScopeMemberExpr::Create(
2099         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2100         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2101         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2102   }
2103
2104   // Synthesize a fake NNS that points to the derived class.  This will
2105   // perform name lookup during template instantiation.
2106   CXXScopeSpec SS;
2107   auto *NNS =
2108       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2109   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2110   return DependentScopeDeclRefExpr::Create(
2111       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2112       TemplateArgs);
2113 }
2114
2115 ExprResult
2116 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2117                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2118                         bool HasTrailingLParen, bool IsAddressOfOperand,
2119                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2120                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2121   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2122          "cannot be direct & operand and have a trailing lparen");
2123   if (SS.isInvalid())
2124     return ExprError();
2125
2126   TemplateArgumentListInfo TemplateArgsBuffer;
2127
2128   // Decompose the UnqualifiedId into the following data.
2129   DeclarationNameInfo NameInfo;
2130   const TemplateArgumentListInfo *TemplateArgs;
2131   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2132
2133   DeclarationName Name = NameInfo.getName();
2134   IdentifierInfo *II = Name.getAsIdentifierInfo();
2135   SourceLocation NameLoc = NameInfo.getLoc();
2136
2137   if (II && II->isEditorPlaceholder()) {
2138     // FIXME: When typed placeholders are supported we can create a typed
2139     // placeholder expression node.
2140     return ExprError();
2141   }
2142
2143   // C++ [temp.dep.expr]p3:
2144   //   An id-expression is type-dependent if it contains:
2145   //     -- an identifier that was declared with a dependent type,
2146   //        (note: handled after lookup)
2147   //     -- a template-id that is dependent,
2148   //        (note: handled in BuildTemplateIdExpr)
2149   //     -- a conversion-function-id that specifies a dependent type,
2150   //     -- a nested-name-specifier that contains a class-name that
2151   //        names a dependent type.
2152   // Determine whether this is a member of an unknown specialization;
2153   // we need to handle these differently.
2154   bool DependentID = false;
2155   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2156       Name.getCXXNameType()->isDependentType()) {
2157     DependentID = true;
2158   } else if (SS.isSet()) {
2159     if (DeclContext *DC = computeDeclContext(SS, false)) {
2160       if (RequireCompleteDeclContext(SS, DC))
2161         return ExprError();
2162     } else {
2163       DependentID = true;
2164     }
2165   }
2166
2167   if (DependentID)
2168     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2169                                       IsAddressOfOperand, TemplateArgs);
2170
2171   // Perform the required lookup.
2172   LookupResult R(*this, NameInfo, 
2173                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2174                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2175   if (TemplateArgs) {
2176     // Lookup the template name again to correctly establish the context in
2177     // which it was found. This is really unfortunate as we already did the
2178     // lookup to determine that it was a template name in the first place. If
2179     // this becomes a performance hit, we can work harder to preserve those
2180     // results until we get here but it's likely not worth it.
2181     bool MemberOfUnknownSpecialization;
2182     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2183                        MemberOfUnknownSpecialization);
2184     
2185     if (MemberOfUnknownSpecialization ||
2186         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2187       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2188                                         IsAddressOfOperand, TemplateArgs);
2189   } else {
2190     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2191     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2192
2193     // If the result might be in a dependent base class, this is a dependent 
2194     // id-expression.
2195     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2196       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2197                                         IsAddressOfOperand, TemplateArgs);
2198
2199     // If this reference is in an Objective-C method, then we need to do
2200     // some special Objective-C lookup, too.
2201     if (IvarLookupFollowUp) {
2202       ExprResult E(LookupInObjCMethod(R, S, II, true));
2203       if (E.isInvalid())
2204         return ExprError();
2205
2206       if (Expr *Ex = E.getAs<Expr>())
2207         return Ex;
2208     }
2209   }
2210
2211   if (R.isAmbiguous())
2212     return ExprError();
2213
2214   // This could be an implicitly declared function reference (legal in C90,
2215   // extension in C99, forbidden in C++).
2216   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2217     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2218     if (D) R.addDecl(D);
2219   }
2220
2221   // Determine whether this name might be a candidate for
2222   // argument-dependent lookup.
2223   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2224
2225   if (R.empty() && !ADL) {
2226     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2227       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2228                                                    TemplateKWLoc, TemplateArgs))
2229         return E;
2230     }
2231
2232     // Don't diagnose an empty lookup for inline assembly.
2233     if (IsInlineAsmIdentifier)
2234       return ExprError();
2235
2236     // If this name wasn't predeclared and if this is not a function
2237     // call, diagnose the problem.
2238     TypoExpr *TE = nullptr;
2239     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2240         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2241     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2242     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2243            "Typo correction callback misconfigured");
2244     if (CCC) {
2245       // Make sure the callback knows what the typo being diagnosed is.
2246       CCC->setTypoName(II);
2247       if (SS.isValid())
2248         CCC->setTypoNNS(SS.getScopeRep());
2249     }
2250     if (DiagnoseEmptyLookup(S, SS, R,
2251                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2252                             nullptr, None, &TE)) {
2253       if (TE && KeywordReplacement) {
2254         auto &State = getTypoExprState(TE);
2255         auto BestTC = State.Consumer->getNextCorrection();
2256         if (BestTC.isKeyword()) {
2257           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2258           if (State.DiagHandler)
2259             State.DiagHandler(BestTC);
2260           KeywordReplacement->startToken();
2261           KeywordReplacement->setKind(II->getTokenID());
2262           KeywordReplacement->setIdentifierInfo(II);
2263           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2264           // Clean up the state associated with the TypoExpr, since it has
2265           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2266           clearDelayedTypo(TE);
2267           // Signal that a correction to a keyword was performed by returning a
2268           // valid-but-null ExprResult.
2269           return (Expr*)nullptr;
2270         }
2271         State.Consumer->resetCorrectionStream();
2272       }
2273       return TE ? TE : ExprError();
2274     }
2275
2276     assert(!R.empty() &&
2277            "DiagnoseEmptyLookup returned false but added no results");
2278
2279     // If we found an Objective-C instance variable, let
2280     // LookupInObjCMethod build the appropriate expression to
2281     // reference the ivar.
2282     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2283       R.clear();
2284       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2285       // In a hopelessly buggy code, Objective-C instance variable
2286       // lookup fails and no expression will be built to reference it.
2287       if (!E.isInvalid() && !E.get())
2288         return ExprError();
2289       return E;
2290     }
2291   }
2292
2293   // This is guaranteed from this point on.
2294   assert(!R.empty() || ADL);
2295
2296   // Check whether this might be a C++ implicit instance member access.
2297   // C++ [class.mfct.non-static]p3:
2298   //   When an id-expression that is not part of a class member access
2299   //   syntax and not used to form a pointer to member is used in the
2300   //   body of a non-static member function of class X, if name lookup
2301   //   resolves the name in the id-expression to a non-static non-type
2302   //   member of some class C, the id-expression is transformed into a
2303   //   class member access expression using (*this) as the
2304   //   postfix-expression to the left of the . operator.
2305   //
2306   // But we don't actually need to do this for '&' operands if R
2307   // resolved to a function or overloaded function set, because the
2308   // expression is ill-formed if it actually works out to be a
2309   // non-static member function:
2310   //
2311   // C++ [expr.ref]p4:
2312   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2313   //   [t]he expression can be used only as the left-hand operand of a
2314   //   member function call.
2315   //
2316   // There are other safeguards against such uses, but it's important
2317   // to get this right here so that we don't end up making a
2318   // spuriously dependent expression if we're inside a dependent
2319   // instance method.
2320   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2321     bool MightBeImplicitMember;
2322     if (!IsAddressOfOperand)
2323       MightBeImplicitMember = true;
2324     else if (!SS.isEmpty())
2325       MightBeImplicitMember = false;
2326     else if (R.isOverloadedResult())
2327       MightBeImplicitMember = false;
2328     else if (R.isUnresolvableResult())
2329       MightBeImplicitMember = true;
2330     else
2331       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2332                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2333                               isa<MSPropertyDecl>(R.getFoundDecl());
2334
2335     if (MightBeImplicitMember)
2336       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2337                                              R, TemplateArgs, S);
2338   }
2339
2340   if (TemplateArgs || TemplateKWLoc.isValid()) {
2341
2342     // In C++1y, if this is a variable template id, then check it
2343     // in BuildTemplateIdExpr().
2344     // The single lookup result must be a variable template declaration.
2345     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2346         Id.TemplateId->Kind == TNK_Var_template) {
2347       assert(R.getAsSingle<VarTemplateDecl>() &&
2348              "There should only be one declaration found.");
2349     }
2350
2351     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2352   }
2353
2354   return BuildDeclarationNameExpr(SS, R, ADL);
2355 }
2356
2357 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2358 /// declaration name, generally during template instantiation.
2359 /// There's a large number of things which don't need to be done along
2360 /// this path.
2361 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2362     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2363     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2364   DeclContext *DC = computeDeclContext(SS, false);
2365   if (!DC)
2366     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2367                                      NameInfo, /*TemplateArgs=*/nullptr);
2368
2369   if (RequireCompleteDeclContext(SS, DC))
2370     return ExprError();
2371
2372   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2373   LookupQualifiedName(R, DC);
2374
2375   if (R.isAmbiguous())
2376     return ExprError();
2377
2378   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2379     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2380                                      NameInfo, /*TemplateArgs=*/nullptr);
2381
2382   if (R.empty()) {
2383     Diag(NameInfo.getLoc(), diag::err_no_member)
2384       << NameInfo.getName() << DC << SS.getRange();
2385     return ExprError();
2386   }
2387
2388   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2389     // Diagnose a missing typename if this resolved unambiguously to a type in
2390     // a dependent context.  If we can recover with a type, downgrade this to
2391     // a warning in Microsoft compatibility mode.
2392     unsigned DiagID = diag::err_typename_missing;
2393     if (RecoveryTSI && getLangOpts().MSVCCompat)
2394       DiagID = diag::ext_typename_missing;
2395     SourceLocation Loc = SS.getBeginLoc();
2396     auto D = Diag(Loc, DiagID);
2397     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2398       << SourceRange(Loc, NameInfo.getEndLoc());
2399
2400     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2401     // context.
2402     if (!RecoveryTSI)
2403       return ExprError();
2404
2405     // Only issue the fixit if we're prepared to recover.
2406     D << FixItHint::CreateInsertion(Loc, "typename ");
2407
2408     // Recover by pretending this was an elaborated type.
2409     QualType Ty = Context.getTypeDeclType(TD);
2410     TypeLocBuilder TLB;
2411     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2412
2413     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2414     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2415     QTL.setElaboratedKeywordLoc(SourceLocation());
2416     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2417
2418     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2419
2420     return ExprEmpty();
2421   }
2422
2423   // Defend against this resolving to an implicit member access. We usually
2424   // won't get here if this might be a legitimate a class member (we end up in
2425   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2426   // a pointer-to-member or in an unevaluated context in C++11.
2427   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2428     return BuildPossibleImplicitMemberExpr(SS,
2429                                            /*TemplateKWLoc=*/SourceLocation(),
2430                                            R, /*TemplateArgs=*/nullptr, S);
2431
2432   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2433 }
2434
2435 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2436 /// detected that we're currently inside an ObjC method.  Perform some
2437 /// additional lookup.
2438 ///
2439 /// Ideally, most of this would be done by lookup, but there's
2440 /// actually quite a lot of extra work involved.
2441 ///
2442 /// Returns a null sentinel to indicate trivial success.
2443 ExprResult
2444 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2445                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2446   SourceLocation Loc = Lookup.getNameLoc();
2447   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2448   
2449   // Check for error condition which is already reported.
2450   if (!CurMethod)
2451     return ExprError();
2452
2453   // There are two cases to handle here.  1) scoped lookup could have failed,
2454   // in which case we should look for an ivar.  2) scoped lookup could have
2455   // found a decl, but that decl is outside the current instance method (i.e.
2456   // a global variable).  In these two cases, we do a lookup for an ivar with
2457   // this name, if the lookup sucedes, we replace it our current decl.
2458
2459   // If we're in a class method, we don't normally want to look for
2460   // ivars.  But if we don't find anything else, and there's an
2461   // ivar, that's an error.
2462   bool IsClassMethod = CurMethod->isClassMethod();
2463
2464   bool LookForIvars;
2465   if (Lookup.empty())
2466     LookForIvars = true;
2467   else if (IsClassMethod)
2468     LookForIvars = false;
2469   else
2470     LookForIvars = (Lookup.isSingleResult() &&
2471                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2472   ObjCInterfaceDecl *IFace = nullptr;
2473   if (LookForIvars) {
2474     IFace = CurMethod->getClassInterface();
2475     ObjCInterfaceDecl *ClassDeclared;
2476     ObjCIvarDecl *IV = nullptr;
2477     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2478       // Diagnose using an ivar in a class method.
2479       if (IsClassMethod)
2480         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2481                          << IV->getDeclName());
2482
2483       // If we're referencing an invalid decl, just return this as a silent
2484       // error node.  The error diagnostic was already emitted on the decl.
2485       if (IV->isInvalidDecl())
2486         return ExprError();
2487
2488       // Check if referencing a field with __attribute__((deprecated)).
2489       if (DiagnoseUseOfDecl(IV, Loc))
2490         return ExprError();
2491
2492       // Diagnose the use of an ivar outside of the declaring class.
2493       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2494           !declaresSameEntity(ClassDeclared, IFace) &&
2495           !getLangOpts().DebuggerSupport)
2496         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2497
2498       // FIXME: This should use a new expr for a direct reference, don't
2499       // turn this into Self->ivar, just return a BareIVarExpr or something.
2500       IdentifierInfo &II = Context.Idents.get("self");
2501       UnqualifiedId SelfName;
2502       SelfName.setIdentifier(&II, SourceLocation());
2503       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2504       CXXScopeSpec SelfScopeSpec;
2505       SourceLocation TemplateKWLoc;
2506       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2507                                               SelfName, false, false);
2508       if (SelfExpr.isInvalid())
2509         return ExprError();
2510
2511       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2512       if (SelfExpr.isInvalid())
2513         return ExprError();
2514
2515       MarkAnyDeclReferenced(Loc, IV, true);
2516
2517       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2518       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2519           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2520         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2521
2522       ObjCIvarRefExpr *Result = new (Context)
2523           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2524                           IV->getLocation(), SelfExpr.get(), true, true);
2525
2526       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2527         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2528           recordUseOfEvaluatedWeak(Result);
2529       }
2530       if (getLangOpts().ObjCAutoRefCount) {
2531         if (CurContext->isClosure())
2532           Diag(Loc, diag::warn_implicitly_retains_self)
2533             << FixItHint::CreateInsertion(Loc, "self->");
2534       }
2535       
2536       return Result;
2537     }
2538   } else if (CurMethod->isInstanceMethod()) {
2539     // We should warn if a local variable hides an ivar.
2540     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2541       ObjCInterfaceDecl *ClassDeclared;
2542       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2543         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2544             declaresSameEntity(IFace, ClassDeclared))
2545           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2546       }
2547     }
2548   } else if (Lookup.isSingleResult() &&
2549              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2550     // If accessing a stand-alone ivar in a class method, this is an error.
2551     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2552       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2553                        << IV->getDeclName());
2554   }
2555
2556   if (Lookup.empty() && II && AllowBuiltinCreation) {
2557     // FIXME. Consolidate this with similar code in LookupName.
2558     if (unsigned BuiltinID = II->getBuiltinID()) {
2559       if (!(getLangOpts().CPlusPlus &&
2560             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2561         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2562                                            S, Lookup.isForRedeclaration(),
2563                                            Lookup.getNameLoc());
2564         if (D) Lookup.addDecl(D);
2565       }
2566     }
2567   }
2568   // Sentinel value saying that we didn't do anything special.
2569   return ExprResult((Expr *)nullptr);
2570 }
2571
2572 /// \brief Cast a base object to a member's actual type.
2573 ///
2574 /// Logically this happens in three phases:
2575 ///
2576 /// * First we cast from the base type to the naming class.
2577 ///   The naming class is the class into which we were looking
2578 ///   when we found the member;  it's the qualifier type if a
2579 ///   qualifier was provided, and otherwise it's the base type.
2580 ///
2581 /// * Next we cast from the naming class to the declaring class.
2582 ///   If the member we found was brought into a class's scope by
2583 ///   a using declaration, this is that class;  otherwise it's
2584 ///   the class declaring the member.
2585 ///
2586 /// * Finally we cast from the declaring class to the "true"
2587 ///   declaring class of the member.  This conversion does not
2588 ///   obey access control.
2589 ExprResult
2590 Sema::PerformObjectMemberConversion(Expr *From,
2591                                     NestedNameSpecifier *Qualifier,
2592                                     NamedDecl *FoundDecl,
2593                                     NamedDecl *Member) {
2594   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2595   if (!RD)
2596     return From;
2597
2598   QualType DestRecordType;
2599   QualType DestType;
2600   QualType FromRecordType;
2601   QualType FromType = From->getType();
2602   bool PointerConversions = false;
2603   if (isa<FieldDecl>(Member)) {
2604     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2605
2606     if (FromType->getAs<PointerType>()) {
2607       DestType = Context.getPointerType(DestRecordType);
2608       FromRecordType = FromType->getPointeeType();
2609       PointerConversions = true;
2610     } else {
2611       DestType = DestRecordType;
2612       FromRecordType = FromType;
2613     }
2614   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2615     if (Method->isStatic())
2616       return From;
2617
2618     DestType = Method->getThisType(Context);
2619     DestRecordType = DestType->getPointeeType();
2620
2621     if (FromType->getAs<PointerType>()) {
2622       FromRecordType = FromType->getPointeeType();
2623       PointerConversions = true;
2624     } else {
2625       FromRecordType = FromType;
2626       DestType = DestRecordType;
2627     }
2628   } else {
2629     // No conversion necessary.
2630     return From;
2631   }
2632
2633   if (DestType->isDependentType() || FromType->isDependentType())
2634     return From;
2635
2636   // If the unqualified types are the same, no conversion is necessary.
2637   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2638     return From;
2639
2640   SourceRange FromRange = From->getSourceRange();
2641   SourceLocation FromLoc = FromRange.getBegin();
2642
2643   ExprValueKind VK = From->getValueKind();
2644
2645   // C++ [class.member.lookup]p8:
2646   //   [...] Ambiguities can often be resolved by qualifying a name with its
2647   //   class name.
2648   //
2649   // If the member was a qualified name and the qualified referred to a
2650   // specific base subobject type, we'll cast to that intermediate type
2651   // first and then to the object in which the member is declared. That allows
2652   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2653   //
2654   //   class Base { public: int x; };
2655   //   class Derived1 : public Base { };
2656   //   class Derived2 : public Base { };
2657   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2658   //
2659   //   void VeryDerived::f() {
2660   //     x = 17; // error: ambiguous base subobjects
2661   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2662   //   }
2663   if (Qualifier && Qualifier->getAsType()) {
2664     QualType QType = QualType(Qualifier->getAsType(), 0);
2665     assert(QType->isRecordType() && "lookup done with non-record type");
2666
2667     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2668
2669     // In C++98, the qualifier type doesn't actually have to be a base
2670     // type of the object type, in which case we just ignore it.
2671     // Otherwise build the appropriate casts.
2672     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2673       CXXCastPath BasePath;
2674       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2675                                        FromLoc, FromRange, &BasePath))
2676         return ExprError();
2677
2678       if (PointerConversions)
2679         QType = Context.getPointerType(QType);
2680       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2681                                VK, &BasePath).get();
2682
2683       FromType = QType;
2684       FromRecordType = QRecordType;
2685
2686       // If the qualifier type was the same as the destination type,
2687       // we're done.
2688       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2689         return From;
2690     }
2691   }
2692
2693   bool IgnoreAccess = false;
2694
2695   // If we actually found the member through a using declaration, cast
2696   // down to the using declaration's type.
2697   //
2698   // Pointer equality is fine here because only one declaration of a
2699   // class ever has member declarations.
2700   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2701     assert(isa<UsingShadowDecl>(FoundDecl));
2702     QualType URecordType = Context.getTypeDeclType(
2703                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2704
2705     // We only need to do this if the naming-class to declaring-class
2706     // conversion is non-trivial.
2707     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2708       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2709       CXXCastPath BasePath;
2710       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2711                                        FromLoc, FromRange, &BasePath))
2712         return ExprError();
2713
2714       QualType UType = URecordType;
2715       if (PointerConversions)
2716         UType = Context.getPointerType(UType);
2717       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2718                                VK, &BasePath).get();
2719       FromType = UType;
2720       FromRecordType = URecordType;
2721     }
2722
2723     // We don't do access control for the conversion from the
2724     // declaring class to the true declaring class.
2725     IgnoreAccess = true;
2726   }
2727
2728   CXXCastPath BasePath;
2729   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2730                                    FromLoc, FromRange, &BasePath,
2731                                    IgnoreAccess))
2732     return ExprError();
2733
2734   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2735                            VK, &BasePath);
2736 }
2737
2738 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2739                                       const LookupResult &R,
2740                                       bool HasTrailingLParen) {
2741   // Only when used directly as the postfix-expression of a call.
2742   if (!HasTrailingLParen)
2743     return false;
2744
2745   // Never if a scope specifier was provided.
2746   if (SS.isSet())
2747     return false;
2748
2749   // Only in C++ or ObjC++.
2750   if (!getLangOpts().CPlusPlus)
2751     return false;
2752
2753   // Turn off ADL when we find certain kinds of declarations during
2754   // normal lookup:
2755   for (NamedDecl *D : R) {
2756     // C++0x [basic.lookup.argdep]p3:
2757     //     -- a declaration of a class member
2758     // Since using decls preserve this property, we check this on the
2759     // original decl.
2760     if (D->isCXXClassMember())
2761       return false;
2762
2763     // C++0x [basic.lookup.argdep]p3:
2764     //     -- a block-scope function declaration that is not a
2765     //        using-declaration
2766     // NOTE: we also trigger this for function templates (in fact, we
2767     // don't check the decl type at all, since all other decl types
2768     // turn off ADL anyway).
2769     if (isa<UsingShadowDecl>(D))
2770       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2771     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2772       return false;
2773
2774     // C++0x [basic.lookup.argdep]p3:
2775     //     -- a declaration that is neither a function or a function
2776     //        template
2777     // And also for builtin functions.
2778     if (isa<FunctionDecl>(D)) {
2779       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2780
2781       // But also builtin functions.
2782       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2783         return false;
2784     } else if (!isa<FunctionTemplateDecl>(D))
2785       return false;
2786   }
2787
2788   return true;
2789 }
2790
2791
2792 /// Diagnoses obvious problems with the use of the given declaration
2793 /// as an expression.  This is only actually called for lookups that
2794 /// were not overloaded, and it doesn't promise that the declaration
2795 /// will in fact be used.
2796 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2797   if (D->isInvalidDecl())
2798     return true;
2799
2800   if (isa<TypedefNameDecl>(D)) {
2801     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2802     return true;
2803   }
2804
2805   if (isa<ObjCInterfaceDecl>(D)) {
2806     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2807     return true;
2808   }
2809
2810   if (isa<NamespaceDecl>(D)) {
2811     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2812     return true;
2813   }
2814
2815   return false;
2816 }
2817
2818 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2819                                           LookupResult &R, bool NeedsADL,
2820                                           bool AcceptInvalidDecl) {
2821   // If this is a single, fully-resolved result and we don't need ADL,
2822   // just build an ordinary singleton decl ref.
2823   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2824     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2825                                     R.getRepresentativeDecl(), nullptr,
2826                                     AcceptInvalidDecl);
2827
2828   // We only need to check the declaration if there's exactly one
2829   // result, because in the overloaded case the results can only be
2830   // functions and function templates.
2831   if (R.isSingleResult() &&
2832       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2833     return ExprError();
2834
2835   // Otherwise, just build an unresolved lookup expression.  Suppress
2836   // any lookup-related diagnostics; we'll hash these out later, when
2837   // we've picked a target.
2838   R.suppressDiagnostics();
2839
2840   UnresolvedLookupExpr *ULE
2841     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2842                                    SS.getWithLocInContext(Context),
2843                                    R.getLookupNameInfo(),
2844                                    NeedsADL, R.isOverloadedResult(),
2845                                    R.begin(), R.end());
2846
2847   return ULE;
2848 }
2849
2850 static void
2851 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2852                                    ValueDecl *var, DeclContext *DC);
2853
2854 /// \brief Complete semantic analysis for a reference to the given declaration.
2855 ExprResult Sema::BuildDeclarationNameExpr(
2856     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2857     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2858     bool AcceptInvalidDecl) {
2859   assert(D && "Cannot refer to a NULL declaration");
2860   assert(!isa<FunctionTemplateDecl>(D) &&
2861          "Cannot refer unambiguously to a function template");
2862
2863   SourceLocation Loc = NameInfo.getLoc();
2864   if (CheckDeclInExpr(*this, Loc, D))
2865     return ExprError();
2866
2867   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2868     // Specifically diagnose references to class templates that are missing
2869     // a template argument list.
2870     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2871                                            << Template << SS.getRange();
2872     Diag(Template->getLocation(), diag::note_template_decl_here);
2873     return ExprError();
2874   }
2875
2876   // Make sure that we're referring to a value.
2877   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2878   if (!VD) {
2879     Diag(Loc, diag::err_ref_non_value)
2880       << D << SS.getRange();
2881     Diag(D->getLocation(), diag::note_declared_at);
2882     return ExprError();
2883   }
2884
2885   // Check whether this declaration can be used. Note that we suppress
2886   // this check when we're going to perform argument-dependent lookup
2887   // on this function name, because this might not be the function
2888   // that overload resolution actually selects.
2889   if (DiagnoseUseOfDecl(VD, Loc))
2890     return ExprError();
2891
2892   // Only create DeclRefExpr's for valid Decl's.
2893   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2894     return ExprError();
2895
2896   // Handle members of anonymous structs and unions.  If we got here,
2897   // and the reference is to a class member indirect field, then this
2898   // must be the subject of a pointer-to-member expression.
2899   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2900     if (!indirectField->isCXXClassMember())
2901       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2902                                                       indirectField);
2903
2904   {
2905     QualType type = VD->getType();
2906     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2907       // C++ [except.spec]p17:
2908       //   An exception-specification is considered to be needed when:
2909       //   - in an expression, the function is the unique lookup result or
2910       //     the selected member of a set of overloaded functions.
2911       ResolveExceptionSpec(Loc, FPT);
2912       type = VD->getType();
2913     }
2914     ExprValueKind valueKind = VK_RValue;
2915
2916     switch (D->getKind()) {
2917     // Ignore all the non-ValueDecl kinds.
2918 #define ABSTRACT_DECL(kind)
2919 #define VALUE(type, base)
2920 #define DECL(type, base) \
2921     case Decl::type:
2922 #include "clang/AST/DeclNodes.inc"
2923       llvm_unreachable("invalid value decl kind");
2924
2925     // These shouldn't make it here.
2926     case Decl::ObjCAtDefsField:
2927     case Decl::ObjCIvar:
2928       llvm_unreachable("forming non-member reference to ivar?");
2929
2930     // Enum constants are always r-values and never references.
2931     // Unresolved using declarations are dependent.
2932     case Decl::EnumConstant:
2933     case Decl::UnresolvedUsingValue:
2934     case Decl::OMPDeclareReduction:
2935       valueKind = VK_RValue;
2936       break;
2937
2938     // Fields and indirect fields that got here must be for
2939     // pointer-to-member expressions; we just call them l-values for
2940     // internal consistency, because this subexpression doesn't really
2941     // exist in the high-level semantics.
2942     case Decl::Field:
2943     case Decl::IndirectField:
2944       assert(getLangOpts().CPlusPlus &&
2945              "building reference to field in C?");
2946
2947       // These can't have reference type in well-formed programs, but
2948       // for internal consistency we do this anyway.
2949       type = type.getNonReferenceType();
2950       valueKind = VK_LValue;
2951       break;
2952
2953     // Non-type template parameters are either l-values or r-values
2954     // depending on the type.
2955     case Decl::NonTypeTemplateParm: {
2956       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2957         type = reftype->getPointeeType();
2958         valueKind = VK_LValue; // even if the parameter is an r-value reference
2959         break;
2960       }
2961
2962       // For non-references, we need to strip qualifiers just in case
2963       // the template parameter was declared as 'const int' or whatever.
2964       valueKind = VK_RValue;
2965       type = type.getUnqualifiedType();
2966       break;
2967     }
2968
2969     case Decl::Var:
2970     case Decl::VarTemplateSpecialization:
2971     case Decl::VarTemplatePartialSpecialization:
2972     case Decl::Decomposition:
2973     case Decl::OMPCapturedExpr:
2974       // In C, "extern void blah;" is valid and is an r-value.
2975       if (!getLangOpts().CPlusPlus &&
2976           !type.hasQualifiers() &&
2977           type->isVoidType()) {
2978         valueKind = VK_RValue;
2979         break;
2980       }
2981       // fallthrough
2982
2983     case Decl::ImplicitParam:
2984     case Decl::ParmVar: {
2985       // These are always l-values.
2986       valueKind = VK_LValue;
2987       type = type.getNonReferenceType();
2988
2989       // FIXME: Does the addition of const really only apply in
2990       // potentially-evaluated contexts? Since the variable isn't actually
2991       // captured in an unevaluated context, it seems that the answer is no.
2992       if (!isUnevaluatedContext()) {
2993         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2994         if (!CapturedType.isNull())
2995           type = CapturedType;
2996       }
2997       
2998       break;
2999     }
3000
3001     case Decl::Binding: {
3002       // These are always lvalues.
3003       valueKind = VK_LValue;
3004       type = type.getNonReferenceType();
3005       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3006       // decides how that's supposed to work.
3007       auto *BD = cast<BindingDecl>(VD);
3008       if (BD->getDeclContext()->isFunctionOrMethod() &&
3009           BD->getDeclContext() != CurContext)
3010         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3011       break;
3012     }
3013         
3014     case Decl::Function: {
3015       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3016         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3017           type = Context.BuiltinFnTy;
3018           valueKind = VK_RValue;
3019           break;
3020         }
3021       }
3022
3023       const FunctionType *fty = type->castAs<FunctionType>();
3024
3025       // If we're referring to a function with an __unknown_anytype
3026       // result type, make the entire expression __unknown_anytype.
3027       if (fty->getReturnType() == Context.UnknownAnyTy) {
3028         type = Context.UnknownAnyTy;
3029         valueKind = VK_RValue;
3030         break;
3031       }
3032
3033       // Functions are l-values in C++.
3034       if (getLangOpts().CPlusPlus) {
3035         valueKind = VK_LValue;
3036         break;
3037       }
3038       
3039       // C99 DR 316 says that, if a function type comes from a
3040       // function definition (without a prototype), that type is only
3041       // used for checking compatibility. Therefore, when referencing
3042       // the function, we pretend that we don't have the full function
3043       // type.
3044       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3045           isa<FunctionProtoType>(fty))
3046         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3047                                               fty->getExtInfo());
3048
3049       // Functions are r-values in C.
3050       valueKind = VK_RValue;
3051       break;
3052     }
3053
3054     case Decl::CXXDeductionGuide:
3055       llvm_unreachable("building reference to deduction guide");
3056
3057     case Decl::MSProperty:
3058       valueKind = VK_LValue;
3059       break;
3060
3061     case Decl::CXXMethod:
3062       // If we're referring to a method with an __unknown_anytype
3063       // result type, make the entire expression __unknown_anytype.
3064       // This should only be possible with a type written directly.
3065       if (const FunctionProtoType *proto
3066             = dyn_cast<FunctionProtoType>(VD->getType()))
3067         if (proto->getReturnType() == Context.UnknownAnyTy) {
3068           type = Context.UnknownAnyTy;
3069           valueKind = VK_RValue;
3070           break;
3071         }
3072
3073       // C++ methods are l-values if static, r-values if non-static.
3074       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3075         valueKind = VK_LValue;
3076         break;
3077       }
3078       // fallthrough
3079
3080     case Decl::CXXConversion:
3081     case Decl::CXXDestructor:
3082     case Decl::CXXConstructor:
3083       valueKind = VK_RValue;
3084       break;
3085     }
3086
3087     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3088                             TemplateArgs);
3089   }
3090 }
3091
3092 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3093                                     SmallString<32> &Target) {
3094   Target.resize(CharByteWidth * (Source.size() + 1));
3095   char *ResultPtr = &Target[0];
3096   const llvm::UTF8 *ErrorPtr;
3097   bool success =
3098       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3099   (void)success;
3100   assert(success);
3101   Target.resize(ResultPtr - &Target[0]);
3102 }
3103
3104 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3105                                      PredefinedExpr::IdentType IT) {
3106   // Pick the current block, lambda, captured statement or function.
3107   Decl *currentDecl = nullptr;
3108   if (const BlockScopeInfo *BSI = getCurBlock())
3109     currentDecl = BSI->TheDecl;
3110   else if (const LambdaScopeInfo *LSI = getCurLambda())
3111     currentDecl = LSI->CallOperator;
3112   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3113     currentDecl = CSI->TheCapturedDecl;
3114   else
3115     currentDecl = getCurFunctionOrMethodDecl();
3116
3117   if (!currentDecl) {
3118     Diag(Loc, diag::ext_predef_outside_function);
3119     currentDecl = Context.getTranslationUnitDecl();
3120   }
3121
3122   QualType ResTy;
3123   StringLiteral *SL = nullptr;
3124   if (cast<DeclContext>(currentDecl)->isDependentContext())
3125     ResTy = Context.DependentTy;
3126   else {
3127     // Pre-defined identifiers are of type char[x], where x is the length of
3128     // the string.
3129     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3130     unsigned Length = Str.length();
3131
3132     llvm::APInt LengthI(32, Length + 1);
3133     if (IT == PredefinedExpr::LFunction) {
3134       ResTy = Context.WideCharTy.withConst();
3135       SmallString<32> RawChars;
3136       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3137                               Str, RawChars);
3138       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3139                                            /*IndexTypeQuals*/ 0);
3140       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3141                                  /*Pascal*/ false, ResTy, Loc);
3142     } else {
3143       ResTy = Context.CharTy.withConst();
3144       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3145                                            /*IndexTypeQuals*/ 0);
3146       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3147                                  /*Pascal*/ false, ResTy, Loc);
3148     }
3149   }
3150
3151   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3152 }
3153
3154 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3155   PredefinedExpr::IdentType IT;
3156
3157   switch (Kind) {
3158   default: llvm_unreachable("Unknown simple primary expr!");
3159   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3160   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3161   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3162   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3163   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3164   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3165   }
3166
3167   return BuildPredefinedExpr(Loc, IT);
3168 }
3169
3170 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3171   SmallString<16> CharBuffer;
3172   bool Invalid = false;
3173   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3174   if (Invalid)
3175     return ExprError();
3176
3177   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3178                             PP, Tok.getKind());
3179   if (Literal.hadError())
3180     return ExprError();
3181
3182   QualType Ty;
3183   if (Literal.isWide())
3184     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3185   else if (Literal.isUTF16())
3186     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3187   else if (Literal.isUTF32())
3188     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3189   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3190     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3191   else
3192     Ty = Context.CharTy;  // 'x' -> char in C++
3193
3194   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3195   if (Literal.isWide())
3196     Kind = CharacterLiteral::Wide;
3197   else if (Literal.isUTF16())
3198     Kind = CharacterLiteral::UTF16;
3199   else if (Literal.isUTF32())
3200     Kind = CharacterLiteral::UTF32;
3201   else if (Literal.isUTF8())
3202     Kind = CharacterLiteral::UTF8;
3203
3204   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3205                                              Tok.getLocation());
3206
3207   if (Literal.getUDSuffix().empty())
3208     return Lit;
3209
3210   // We're building a user-defined literal.
3211   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3212   SourceLocation UDSuffixLoc =
3213     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3214
3215   // Make sure we're allowed user-defined literals here.
3216   if (!UDLScope)
3217     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3218
3219   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3220   //   operator "" X (ch)
3221   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3222                                         Lit, Tok.getLocation());
3223 }
3224
3225 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3226   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3227   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3228                                 Context.IntTy, Loc);
3229 }
3230
3231 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3232                                   QualType Ty, SourceLocation Loc) {
3233   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3234
3235   using llvm::APFloat;
3236   APFloat Val(Format);
3237
3238   APFloat::opStatus result = Literal.GetFloatValue(Val);
3239
3240   // Overflow is always an error, but underflow is only an error if
3241   // we underflowed to zero (APFloat reports denormals as underflow).
3242   if ((result & APFloat::opOverflow) ||
3243       ((result & APFloat::opUnderflow) && Val.isZero())) {
3244     unsigned diagnostic;
3245     SmallString<20> buffer;
3246     if (result & APFloat::opOverflow) {
3247       diagnostic = diag::warn_float_overflow;
3248       APFloat::getLargest(Format).toString(buffer);
3249     } else {
3250       diagnostic = diag::warn_float_underflow;
3251       APFloat::getSmallest(Format).toString(buffer);
3252     }
3253
3254     S.Diag(Loc, diagnostic)
3255       << Ty
3256       << StringRef(buffer.data(), buffer.size());
3257   }
3258
3259   bool isExact = (result == APFloat::opOK);
3260   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3261 }
3262
3263 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3264   assert(E && "Invalid expression");
3265
3266   if (E->isValueDependent())
3267     return false;
3268
3269   QualType QT = E->getType();
3270   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3271     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3272     return true;
3273   }
3274
3275   llvm::APSInt ValueAPS;
3276   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3277
3278   if (R.isInvalid())
3279     return true;
3280
3281   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3282   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3283     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3284         << ValueAPS.toString(10) << ValueIsPositive;
3285     return true;
3286   }
3287
3288   return false;
3289 }
3290
3291 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3292   // Fast path for a single digit (which is quite common).  A single digit
3293   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3294   if (Tok.getLength() == 1) {
3295     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3296     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3297   }
3298
3299   SmallString<128> SpellingBuffer;
3300   // NumericLiteralParser wants to overread by one character.  Add padding to
3301   // the buffer in case the token is copied to the buffer.  If getSpelling()
3302   // returns a StringRef to the memory buffer, it should have a null char at
3303   // the EOF, so it is also safe.
3304   SpellingBuffer.resize(Tok.getLength() + 1);
3305
3306   // Get the spelling of the token, which eliminates trigraphs, etc.
3307   bool Invalid = false;
3308   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3309   if (Invalid)
3310     return ExprError();
3311
3312   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3313   if (Literal.hadError)
3314     return ExprError();
3315
3316   if (Literal.hasUDSuffix()) {
3317     // We're building a user-defined literal.
3318     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3319     SourceLocation UDSuffixLoc =
3320       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3321
3322     // Make sure we're allowed user-defined literals here.
3323     if (!UDLScope)
3324       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3325
3326     QualType CookedTy;
3327     if (Literal.isFloatingLiteral()) {
3328       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3329       // long double, the literal is treated as a call of the form
3330       //   operator "" X (f L)
3331       CookedTy = Context.LongDoubleTy;
3332     } else {
3333       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3334       // unsigned long long, the literal is treated as a call of the form
3335       //   operator "" X (n ULL)
3336       CookedTy = Context.UnsignedLongLongTy;
3337     }
3338
3339     DeclarationName OpName =
3340       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3341     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3342     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3343
3344     SourceLocation TokLoc = Tok.getLocation();
3345
3346     // Perform literal operator lookup to determine if we're building a raw
3347     // literal or a cooked one.
3348     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3349     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3350                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3351                                   /*AllowStringTemplate*/false)) {
3352     case LOLR_Error:
3353       return ExprError();
3354
3355     case LOLR_Cooked: {
3356       Expr *Lit;
3357       if (Literal.isFloatingLiteral()) {
3358         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3359       } else {
3360         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3361         if (Literal.GetIntegerValue(ResultVal))
3362           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3363               << /* Unsigned */ 1;
3364         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3365                                      Tok.getLocation());
3366       }
3367       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3368     }
3369
3370     case LOLR_Raw: {
3371       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3372       // literal is treated as a call of the form
3373       //   operator "" X ("n")
3374       unsigned Length = Literal.getUDSuffixOffset();
3375       QualType StrTy = Context.getConstantArrayType(
3376           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3377           ArrayType::Normal, 0);
3378       Expr *Lit = StringLiteral::Create(
3379           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3380           /*Pascal*/false, StrTy, &TokLoc, 1);
3381       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3382     }
3383
3384     case LOLR_Template: {
3385       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3386       // template), L is treated as a call fo the form
3387       //   operator "" X <'c1', 'c2', ... 'ck'>()
3388       // where n is the source character sequence c1 c2 ... ck.
3389       TemplateArgumentListInfo ExplicitArgs;
3390       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3391       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3392       llvm::APSInt Value(CharBits, CharIsUnsigned);
3393       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3394         Value = TokSpelling[I];
3395         TemplateArgument Arg(Context, Value, Context.CharTy);
3396         TemplateArgumentLocInfo ArgInfo;
3397         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3398       }
3399       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3400                                       &ExplicitArgs);
3401     }
3402     case LOLR_StringTemplate:
3403       llvm_unreachable("unexpected literal operator lookup result");
3404     }
3405   }
3406
3407   Expr *Res;
3408
3409   if (Literal.isFloatingLiteral()) {
3410     QualType Ty;
3411     if (Literal.isHalf){
3412       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3413         Ty = Context.HalfTy;
3414       else {
3415         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3416         return ExprError();
3417       }
3418     } else if (Literal.isFloat)
3419       Ty = Context.FloatTy;
3420     else if (Literal.isLong)
3421       Ty = Context.LongDoubleTy;
3422     else if (Literal.isFloat128)
3423       Ty = Context.Float128Ty;
3424     else
3425       Ty = Context.DoubleTy;
3426
3427     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3428
3429     if (Ty == Context.DoubleTy) {
3430       if (getLangOpts().SinglePrecisionConstants) {
3431         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3432         if (BTy->getKind() != BuiltinType::Float) {
3433           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3434         }
3435       } else if (getLangOpts().OpenCL &&
3436                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3437         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3438         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3439         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3440       }
3441     }
3442   } else if (!Literal.isIntegerLiteral()) {
3443     return ExprError();
3444   } else {
3445     QualType Ty;
3446
3447     // 'long long' is a C99 or C++11 feature.
3448     if (!getLangOpts().C99 && Literal.isLongLong) {
3449       if (getLangOpts().CPlusPlus)
3450         Diag(Tok.getLocation(),
3451              getLangOpts().CPlusPlus11 ?
3452              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3453       else
3454         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3455     }
3456
3457     // Get the value in the widest-possible width.
3458     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3459     llvm::APInt ResultVal(MaxWidth, 0);
3460
3461     if (Literal.GetIntegerValue(ResultVal)) {
3462       // If this value didn't fit into uintmax_t, error and force to ull.
3463       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3464           << /* Unsigned */ 1;
3465       Ty = Context.UnsignedLongLongTy;
3466       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3467              "long long is not intmax_t?");
3468     } else {
3469       // If this value fits into a ULL, try to figure out what else it fits into
3470       // according to the rules of C99 6.4.4.1p5.
3471
3472       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3473       // be an unsigned int.
3474       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3475
3476       // Check from smallest to largest, picking the smallest type we can.
3477       unsigned Width = 0;
3478
3479       // Microsoft specific integer suffixes are explicitly sized.
3480       if (Literal.MicrosoftInteger) {
3481         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3482           Width = 8;
3483           Ty = Context.CharTy;
3484         } else {
3485           Width = Literal.MicrosoftInteger;
3486           Ty = Context.getIntTypeForBitwidth(Width,
3487                                              /*Signed=*/!Literal.isUnsigned);
3488         }
3489       }
3490
3491       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3492         // Are int/unsigned possibilities?
3493         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3494
3495         // Does it fit in a unsigned int?
3496         if (ResultVal.isIntN(IntSize)) {
3497           // Does it fit in a signed int?
3498           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3499             Ty = Context.IntTy;
3500           else if (AllowUnsigned)
3501             Ty = Context.UnsignedIntTy;
3502           Width = IntSize;
3503         }
3504       }
3505
3506       // Are long/unsigned long possibilities?
3507       if (Ty.isNull() && !Literal.isLongLong) {
3508         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3509
3510         // Does it fit in a unsigned long?
3511         if (ResultVal.isIntN(LongSize)) {
3512           // Does it fit in a signed long?
3513           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3514             Ty = Context.LongTy;
3515           else if (AllowUnsigned)
3516             Ty = Context.UnsignedLongTy;
3517           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3518           // is compatible.
3519           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3520             const unsigned LongLongSize =
3521                 Context.getTargetInfo().getLongLongWidth();
3522             Diag(Tok.getLocation(),
3523                  getLangOpts().CPlusPlus
3524                      ? Literal.isLong
3525                            ? diag::warn_old_implicitly_unsigned_long_cxx
3526                            : /*C++98 UB*/ diag::
3527                                  ext_old_implicitly_unsigned_long_cxx
3528                      : diag::warn_old_implicitly_unsigned_long)
3529                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3530                                             : /*will be ill-formed*/ 1);
3531             Ty = Context.UnsignedLongTy;
3532           }
3533           Width = LongSize;
3534         }
3535       }
3536
3537       // Check long long if needed.
3538       if (Ty.isNull()) {
3539         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3540
3541         // Does it fit in a unsigned long long?
3542         if (ResultVal.isIntN(LongLongSize)) {
3543           // Does it fit in a signed long long?
3544           // To be compatible with MSVC, hex integer literals ending with the
3545           // LL or i64 suffix are always signed in Microsoft mode.
3546           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3547               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3548             Ty = Context.LongLongTy;
3549           else if (AllowUnsigned)
3550             Ty = Context.UnsignedLongLongTy;
3551           Width = LongLongSize;
3552         }
3553       }
3554
3555       // If we still couldn't decide a type, we probably have something that
3556       // does not fit in a signed long long, but has no U suffix.
3557       if (Ty.isNull()) {
3558         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3559         Ty = Context.UnsignedLongLongTy;
3560         Width = Context.getTargetInfo().getLongLongWidth();
3561       }
3562
3563       if (ResultVal.getBitWidth() != Width)
3564         ResultVal = ResultVal.trunc(Width);
3565     }
3566     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3567   }
3568
3569   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3570   if (Literal.isImaginary)
3571     Res = new (Context) ImaginaryLiteral(Res,
3572                                         Context.getComplexType(Res->getType()));
3573
3574   return Res;
3575 }
3576
3577 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3578   assert(E && "ActOnParenExpr() missing expr");
3579   return new (Context) ParenExpr(L, R, E);
3580 }
3581
3582 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3583                                          SourceLocation Loc,
3584                                          SourceRange ArgRange) {
3585   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3586   // scalar or vector data type argument..."
3587   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3588   // type (C99 6.2.5p18) or void.
3589   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3590     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3591       << T << ArgRange;
3592     return true;
3593   }
3594
3595   assert((T->isVoidType() || !T->isIncompleteType()) &&
3596          "Scalar types should always be complete");
3597   return false;
3598 }
3599
3600 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3601                                            SourceLocation Loc,
3602                                            SourceRange ArgRange,
3603                                            UnaryExprOrTypeTrait TraitKind) {
3604   // Invalid types must be hard errors for SFINAE in C++.
3605   if (S.LangOpts.CPlusPlus)
3606     return true;
3607
3608   // C99 6.5.3.4p1:
3609   if (T->isFunctionType() &&
3610       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3611     // sizeof(function)/alignof(function) is allowed as an extension.
3612     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3613       << TraitKind << ArgRange;
3614     return false;
3615   }
3616
3617   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3618   // this is an error (OpenCL v1.1 s6.3.k)
3619   if (T->isVoidType()) {
3620     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3621                                         : diag::ext_sizeof_alignof_void_type;
3622     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3623     return false;
3624   }
3625
3626   return true;
3627 }
3628
3629 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3630                                              SourceLocation Loc,
3631                                              SourceRange ArgRange,
3632                                              UnaryExprOrTypeTrait TraitKind) {
3633   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3634   // runtime doesn't allow it.
3635   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3636     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3637       << T << (TraitKind == UETT_SizeOf)
3638       << ArgRange;
3639     return true;
3640   }
3641
3642   return false;
3643 }
3644
3645 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3646 /// pointer type is equal to T) and emit a warning if it is.
3647 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3648                                      Expr *E) {
3649   // Don't warn if the operation changed the type.
3650   if (T != E->getType())
3651     return;
3652
3653   // Now look for array decays.
3654   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3655   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3656     return;
3657
3658   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3659                                              << ICE->getType()
3660                                              << ICE->getSubExpr()->getType();
3661 }
3662
3663 /// \brief Check the constraints on expression operands to unary type expression
3664 /// and type traits.
3665 ///
3666 /// Completes any types necessary and validates the constraints on the operand
3667 /// expression. The logic mostly mirrors the type-based overload, but may modify
3668 /// the expression as it completes the type for that expression through template
3669 /// instantiation, etc.
3670 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3671                                             UnaryExprOrTypeTrait ExprKind) {
3672   QualType ExprTy = E->getType();
3673   assert(!ExprTy->isReferenceType());
3674
3675   if (ExprKind == UETT_VecStep)
3676     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3677                                         E->getSourceRange());
3678
3679   // Whitelist some types as extensions
3680   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3681                                       E->getSourceRange(), ExprKind))
3682     return false;
3683
3684   // 'alignof' applied to an expression only requires the base element type of
3685   // the expression to be complete. 'sizeof' requires the expression's type to
3686   // be complete (and will attempt to complete it if it's an array of unknown
3687   // bound).
3688   if (ExprKind == UETT_AlignOf) {
3689     if (RequireCompleteType(E->getExprLoc(),
3690                             Context.getBaseElementType(E->getType()),
3691                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3692                             E->getSourceRange()))
3693       return true;
3694   } else {
3695     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3696                                 ExprKind, E->getSourceRange()))
3697       return true;
3698   }
3699
3700   // Completing the expression's type may have changed it.
3701   ExprTy = E->getType();
3702   assert(!ExprTy->isReferenceType());
3703
3704   if (ExprTy->isFunctionType()) {
3705     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3706       << ExprKind << E->getSourceRange();
3707     return true;
3708   }
3709
3710   // The operand for sizeof and alignof is in an unevaluated expression context,
3711   // so side effects could result in unintended consequences.
3712   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3713       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3714     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3715
3716   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3717                                        E->getSourceRange(), ExprKind))
3718     return true;
3719
3720   if (ExprKind == UETT_SizeOf) {
3721     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3722       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3723         QualType OType = PVD->getOriginalType();
3724         QualType Type = PVD->getType();
3725         if (Type->isPointerType() && OType->isArrayType()) {
3726           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3727             << Type << OType;
3728           Diag(PVD->getLocation(), diag::note_declared_at);
3729         }
3730       }
3731     }
3732
3733     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3734     // decays into a pointer and returns an unintended result. This is most
3735     // likely a typo for "sizeof(array) op x".
3736     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3737       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3738                                BO->getLHS());
3739       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3740                                BO->getRHS());
3741     }
3742   }
3743
3744   return false;
3745 }
3746
3747 /// \brief Check the constraints on operands to unary expression and type
3748 /// traits.
3749 ///
3750 /// This will complete any types necessary, and validate the various constraints
3751 /// on those operands.
3752 ///
3753 /// The UsualUnaryConversions() function is *not* called by this routine.
3754 /// C99 6.3.2.1p[2-4] all state:
3755 ///   Except when it is the operand of the sizeof operator ...
3756 ///
3757 /// C++ [expr.sizeof]p4
3758 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3759 ///   standard conversions are not applied to the operand of sizeof.
3760 ///
3761 /// This policy is followed for all of the unary trait expressions.
3762 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3763                                             SourceLocation OpLoc,
3764                                             SourceRange ExprRange,
3765                                             UnaryExprOrTypeTrait ExprKind) {
3766   if (ExprType->isDependentType())
3767     return false;
3768
3769   // C++ [expr.sizeof]p2:
3770   //     When applied to a reference or a reference type, the result
3771   //     is the size of the referenced type.
3772   // C++11 [expr.alignof]p3:
3773   //     When alignof is applied to a reference type, the result
3774   //     shall be the alignment of the referenced type.
3775   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3776     ExprType = Ref->getPointeeType();
3777
3778   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3779   //   When alignof or _Alignof is applied to an array type, the result
3780   //   is the alignment of the element type.
3781   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3782     ExprType = Context.getBaseElementType(ExprType);
3783
3784   if (ExprKind == UETT_VecStep)
3785     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3786
3787   // Whitelist some types as extensions
3788   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3789                                       ExprKind))
3790     return false;
3791
3792   if (RequireCompleteType(OpLoc, ExprType,
3793                           diag::err_sizeof_alignof_incomplete_type,
3794                           ExprKind, ExprRange))
3795     return true;
3796
3797   if (ExprType->isFunctionType()) {
3798     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3799       << ExprKind << ExprRange;
3800     return true;
3801   }
3802
3803   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3804                                        ExprKind))
3805     return true;
3806
3807   return false;
3808 }
3809
3810 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3811   E = E->IgnoreParens();
3812
3813   // Cannot know anything else if the expression is dependent.
3814   if (E->isTypeDependent())
3815     return false;
3816
3817   if (E->getObjectKind() == OK_BitField) {
3818     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3819        << 1 << E->getSourceRange();
3820     return true;
3821   }
3822
3823   ValueDecl *D = nullptr;
3824   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3825     D = DRE->getDecl();
3826   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3827     D = ME->getMemberDecl();
3828   }
3829
3830   // If it's a field, require the containing struct to have a
3831   // complete definition so that we can compute the layout.
3832   //
3833   // This can happen in C++11 onwards, either by naming the member
3834   // in a way that is not transformed into a member access expression
3835   // (in an unevaluated operand, for instance), or by naming the member
3836   // in a trailing-return-type.
3837   //
3838   // For the record, since __alignof__ on expressions is a GCC
3839   // extension, GCC seems to permit this but always gives the
3840   // nonsensical answer 0.
3841   //
3842   // We don't really need the layout here --- we could instead just
3843   // directly check for all the appropriate alignment-lowing
3844   // attributes --- but that would require duplicating a lot of
3845   // logic that just isn't worth duplicating for such a marginal
3846   // use-case.
3847   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3848     // Fast path this check, since we at least know the record has a
3849     // definition if we can find a member of it.
3850     if (!FD->getParent()->isCompleteDefinition()) {
3851       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3852         << E->getSourceRange();
3853       return true;
3854     }
3855
3856     // Otherwise, if it's a field, and the field doesn't have
3857     // reference type, then it must have a complete type (or be a
3858     // flexible array member, which we explicitly want to
3859     // white-list anyway), which makes the following checks trivial.
3860     if (!FD->getType()->isReferenceType())
3861       return false;
3862   }
3863
3864   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3865 }
3866
3867 bool Sema::CheckVecStepExpr(Expr *E) {
3868   E = E->IgnoreParens();
3869
3870   // Cannot know anything else if the expression is dependent.
3871   if (E->isTypeDependent())
3872     return false;
3873
3874   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3875 }
3876
3877 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3878                                         CapturingScopeInfo *CSI) {
3879   assert(T->isVariablyModifiedType());
3880   assert(CSI != nullptr);
3881
3882   // We're going to walk down into the type and look for VLA expressions.
3883   do {
3884     const Type *Ty = T.getTypePtr();
3885     switch (Ty->getTypeClass()) {
3886 #define TYPE(Class, Base)
3887 #define ABSTRACT_TYPE(Class, Base)
3888 #define NON_CANONICAL_TYPE(Class, Base)
3889 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3890 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3891 #include "clang/AST/TypeNodes.def"
3892       T = QualType();
3893       break;
3894     // These types are never variably-modified.
3895     case Type::Builtin:
3896     case Type::Complex:
3897     case Type::Vector:
3898     case Type::ExtVector:
3899     case Type::Record:
3900     case Type::Enum:
3901     case Type::Elaborated:
3902     case Type::TemplateSpecialization:
3903     case Type::ObjCObject:
3904     case Type::ObjCInterface:
3905     case Type::ObjCObjectPointer:
3906     case Type::ObjCTypeParam:
3907     case Type::Pipe:
3908       llvm_unreachable("type class is never variably-modified!");
3909     case Type::Adjusted:
3910       T = cast<AdjustedType>(Ty)->getOriginalType();
3911       break;
3912     case Type::Decayed:
3913       T = cast<DecayedType>(Ty)->getPointeeType();
3914       break;
3915     case Type::Pointer:
3916       T = cast<PointerType>(Ty)->getPointeeType();
3917       break;
3918     case Type::BlockPointer:
3919       T = cast<BlockPointerType>(Ty)->getPointeeType();
3920       break;
3921     case Type::LValueReference:
3922     case Type::RValueReference:
3923       T = cast<ReferenceType>(Ty)->getPointeeType();
3924       break;
3925     case Type::MemberPointer:
3926       T = cast<MemberPointerType>(Ty)->getPointeeType();
3927       break;
3928     case Type::ConstantArray:
3929     case Type::IncompleteArray:
3930       // Losing element qualification here is fine.
3931       T = cast<ArrayType>(Ty)->getElementType();
3932       break;
3933     case Type::VariableArray: {
3934       // Losing element qualification here is fine.
3935       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3936
3937       // Unknown size indication requires no size computation.
3938       // Otherwise, evaluate and record it.
3939       if (auto Size = VAT->getSizeExpr()) {
3940         if (!CSI->isVLATypeCaptured(VAT)) {
3941           RecordDecl *CapRecord = nullptr;
3942           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3943             CapRecord = LSI->Lambda;
3944           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3945             CapRecord = CRSI->TheRecordDecl;
3946           }
3947           if (CapRecord) {
3948             auto ExprLoc = Size->getExprLoc();
3949             auto SizeType = Context.getSizeType();
3950             // Build the non-static data member.
3951             auto Field =
3952                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3953                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3954                                   /*BW*/ nullptr, /*Mutable*/ false,
3955                                   /*InitStyle*/ ICIS_NoInit);
3956             Field->setImplicit(true);
3957             Field->setAccess(AS_private);
3958             Field->setCapturedVLAType(VAT);
3959             CapRecord->addDecl(Field);
3960
3961             CSI->addVLATypeCapture(ExprLoc, SizeType);
3962           }
3963         }
3964       }
3965       T = VAT->getElementType();
3966       break;
3967     }
3968     case Type::FunctionProto:
3969     case Type::FunctionNoProto:
3970       T = cast<FunctionType>(Ty)->getReturnType();
3971       break;
3972     case Type::Paren:
3973     case Type::TypeOf:
3974     case Type::UnaryTransform:
3975     case Type::Attributed:
3976     case Type::SubstTemplateTypeParm:
3977     case Type::PackExpansion:
3978       // Keep walking after single level desugaring.
3979       T = T.getSingleStepDesugaredType(Context);
3980       break;
3981     case Type::Typedef:
3982       T = cast<TypedefType>(Ty)->desugar();
3983       break;
3984     case Type::Decltype:
3985       T = cast<DecltypeType>(Ty)->desugar();
3986       break;
3987     case Type::Auto:
3988     case Type::DeducedTemplateSpecialization:
3989       T = cast<DeducedType>(Ty)->getDeducedType();
3990       break;
3991     case Type::TypeOfExpr:
3992       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3993       break;
3994     case Type::Atomic:
3995       T = cast<AtomicType>(Ty)->getValueType();
3996       break;
3997     }
3998   } while (!T.isNull() && T->isVariablyModifiedType());
3999 }
4000
4001 /// \brief Build a sizeof or alignof expression given a type operand.
4002 ExprResult
4003 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4004                                      SourceLocation OpLoc,
4005                                      UnaryExprOrTypeTrait ExprKind,
4006                                      SourceRange R) {
4007   if (!TInfo)
4008     return ExprError();
4009
4010   QualType T = TInfo->getType();
4011
4012   if (!T->isDependentType() &&
4013       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4014     return ExprError();
4015
4016   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4017     if (auto *TT = T->getAs<TypedefType>()) {
4018       for (auto I = FunctionScopes.rbegin(),
4019                 E = std::prev(FunctionScopes.rend());
4020            I != E; ++I) {
4021         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4022         if (CSI == nullptr)
4023           break;
4024         DeclContext *DC = nullptr;
4025         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4026           DC = LSI->CallOperator;
4027         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4028           DC = CRSI->TheCapturedDecl;
4029         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4030           DC = BSI->TheDecl;
4031         if (DC) {
4032           if (DC->containsDecl(TT->getDecl()))
4033             break;
4034           captureVariablyModifiedType(Context, T, CSI);
4035         }
4036       }
4037     }
4038   }
4039
4040   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4041   return new (Context) UnaryExprOrTypeTraitExpr(
4042       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4043 }
4044
4045 /// \brief Build a sizeof or alignof expression given an expression
4046 /// operand.
4047 ExprResult
4048 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4049                                      UnaryExprOrTypeTrait ExprKind) {
4050   ExprResult PE = CheckPlaceholderExpr(E);
4051   if (PE.isInvalid()) 
4052     return ExprError();
4053
4054   E = PE.get();
4055   
4056   // Verify that the operand is valid.
4057   bool isInvalid = false;
4058   if (E->isTypeDependent()) {
4059     // Delay type-checking for type-dependent expressions.
4060   } else if (ExprKind == UETT_AlignOf) {
4061     isInvalid = CheckAlignOfExpr(*this, E);
4062   } else if (ExprKind == UETT_VecStep) {
4063     isInvalid = CheckVecStepExpr(E);
4064   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4065       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4066       isInvalid = true;
4067   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4068     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4069     isInvalid = true;
4070   } else {
4071     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4072   }
4073
4074   if (isInvalid)
4075     return ExprError();
4076
4077   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4078     PE = TransformToPotentiallyEvaluated(E);
4079     if (PE.isInvalid()) return ExprError();
4080     E = PE.get();
4081   }
4082
4083   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4084   return new (Context) UnaryExprOrTypeTraitExpr(
4085       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4086 }
4087
4088 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4089 /// expr and the same for @c alignof and @c __alignof
4090 /// Note that the ArgRange is invalid if isType is false.
4091 ExprResult
4092 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4093                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4094                                     void *TyOrEx, SourceRange ArgRange) {
4095   // If error parsing type, ignore.
4096   if (!TyOrEx) return ExprError();
4097
4098   if (IsType) {
4099     TypeSourceInfo *TInfo;
4100     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4101     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4102   }
4103
4104   Expr *ArgEx = (Expr *)TyOrEx;
4105   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4106   return Result;
4107 }
4108
4109 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4110                                      bool IsReal) {
4111   if (V.get()->isTypeDependent())
4112     return S.Context.DependentTy;
4113
4114   // _Real and _Imag are only l-values for normal l-values.
4115   if (V.get()->getObjectKind() != OK_Ordinary) {
4116     V = S.DefaultLvalueConversion(V.get());
4117     if (V.isInvalid())
4118       return QualType();
4119   }
4120
4121   // These operators return the element type of a complex type.
4122   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4123     return CT->getElementType();
4124
4125   // Otherwise they pass through real integer and floating point types here.
4126   if (V.get()->getType()->isArithmeticType())
4127     return V.get()->getType();
4128
4129   // Test for placeholders.
4130   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4131   if (PR.isInvalid()) return QualType();
4132   if (PR.get() != V.get()) {
4133     V = PR;
4134     return CheckRealImagOperand(S, V, Loc, IsReal);
4135   }
4136
4137   // Reject anything else.
4138   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4139     << (IsReal ? "__real" : "__imag");
4140   return QualType();
4141 }
4142
4143
4144
4145 ExprResult
4146 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4147                           tok::TokenKind Kind, Expr *Input) {
4148   UnaryOperatorKind Opc;
4149   switch (Kind) {
4150   default: llvm_unreachable("Unknown unary op!");
4151   case tok::plusplus:   Opc = UO_PostInc; break;
4152   case tok::minusminus: Opc = UO_PostDec; break;
4153   }
4154
4155   // Since this might is a postfix expression, get rid of ParenListExprs.
4156   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4157   if (Result.isInvalid()) return ExprError();
4158   Input = Result.get();
4159
4160   return BuildUnaryOp(S, OpLoc, Opc, Input);
4161 }
4162
4163 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4164 ///
4165 /// \return true on error
4166 static bool checkArithmeticOnObjCPointer(Sema &S,
4167                                          SourceLocation opLoc,
4168                                          Expr *op) {
4169   assert(op->getType()->isObjCObjectPointerType());
4170   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4171       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4172     return false;
4173
4174   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4175     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4176     << op->getSourceRange();
4177   return true;
4178 }
4179
4180 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4181   auto *BaseNoParens = Base->IgnoreParens();
4182   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4183     return MSProp->getPropertyDecl()->getType()->isArrayType();
4184   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4185 }
4186
4187 ExprResult
4188 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4189                               Expr *idx, SourceLocation rbLoc) {
4190   if (base && !base->getType().isNull() &&
4191       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4192     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4193                                     /*Length=*/nullptr, rbLoc);
4194
4195   // Since this might be a postfix expression, get rid of ParenListExprs.
4196   if (isa<ParenListExpr>(base)) {
4197     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4198     if (result.isInvalid()) return ExprError();
4199     base = result.get();
4200   }
4201
4202   // Handle any non-overload placeholder types in the base and index
4203   // expressions.  We can't handle overloads here because the other
4204   // operand might be an overloadable type, in which case the overload
4205   // resolution for the operator overload should get the first crack
4206   // at the overload.
4207   bool IsMSPropertySubscript = false;
4208   if (base->getType()->isNonOverloadPlaceholderType()) {
4209     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4210     if (!IsMSPropertySubscript) {
4211       ExprResult result = CheckPlaceholderExpr(base);
4212       if (result.isInvalid())
4213         return ExprError();
4214       base = result.get();
4215     }
4216   }
4217   if (idx->getType()->isNonOverloadPlaceholderType()) {
4218     ExprResult result = CheckPlaceholderExpr(idx);
4219     if (result.isInvalid()) return ExprError();
4220     idx = result.get();
4221   }
4222
4223   // Build an unanalyzed expression if either operand is type-dependent.
4224   if (getLangOpts().CPlusPlus &&
4225       (base->isTypeDependent() || idx->isTypeDependent())) {
4226     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4227                                             VK_LValue, OK_Ordinary, rbLoc);
4228   }
4229
4230   // MSDN, property (C++)
4231   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4232   // This attribute can also be used in the declaration of an empty array in a
4233   // class or structure definition. For example:
4234   // __declspec(property(get=GetX, put=PutX)) int x[];
4235   // The above statement indicates that x[] can be used with one or more array
4236   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4237   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4238   if (IsMSPropertySubscript) {
4239     // Build MS property subscript expression if base is MS property reference
4240     // or MS property subscript.
4241     return new (Context) MSPropertySubscriptExpr(
4242         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4243   }
4244
4245   // Use C++ overloaded-operator rules if either operand has record
4246   // type.  The spec says to do this if either type is *overloadable*,
4247   // but enum types can't declare subscript operators or conversion
4248   // operators, so there's nothing interesting for overload resolution
4249   // to do if there aren't any record types involved.
4250   //
4251   // ObjC pointers have their own subscripting logic that is not tied
4252   // to overload resolution and so should not take this path.
4253   if (getLangOpts().CPlusPlus &&
4254       (base->getType()->isRecordType() ||
4255        (!base->getType()->isObjCObjectPointerType() &&
4256         idx->getType()->isRecordType()))) {
4257     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4258   }
4259
4260   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4261 }
4262
4263 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4264                                           Expr *LowerBound,
4265                                           SourceLocation ColonLoc, Expr *Length,
4266                                           SourceLocation RBLoc) {
4267   if (Base->getType()->isPlaceholderType() &&
4268       !Base->getType()->isSpecificPlaceholderType(
4269           BuiltinType::OMPArraySection)) {
4270     ExprResult Result = CheckPlaceholderExpr(Base);
4271     if (Result.isInvalid())
4272       return ExprError();
4273     Base = Result.get();
4274   }
4275   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4276     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4277     if (Result.isInvalid())
4278       return ExprError();
4279     Result = DefaultLvalueConversion(Result.get());
4280     if (Result.isInvalid())
4281       return ExprError();
4282     LowerBound = Result.get();
4283   }
4284   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4285     ExprResult Result = CheckPlaceholderExpr(Length);
4286     if (Result.isInvalid())
4287       return ExprError();
4288     Result = DefaultLvalueConversion(Result.get());
4289     if (Result.isInvalid())
4290       return ExprError();
4291     Length = Result.get();
4292   }
4293
4294   // Build an unanalyzed expression if either operand is type-dependent.
4295   if (Base->isTypeDependent() ||
4296       (LowerBound &&
4297        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4298       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4299     return new (Context)
4300         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4301                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4302   }
4303
4304   // Perform default conversions.
4305   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4306   QualType ResultTy;
4307   if (OriginalTy->isAnyPointerType()) {
4308     ResultTy = OriginalTy->getPointeeType();
4309   } else if (OriginalTy->isArrayType()) {
4310     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4311   } else {
4312     return ExprError(
4313         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4314         << Base->getSourceRange());
4315   }
4316   // C99 6.5.2.1p1
4317   if (LowerBound) {
4318     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4319                                                       LowerBound);
4320     if (Res.isInvalid())
4321       return ExprError(Diag(LowerBound->getExprLoc(),
4322                             diag::err_omp_typecheck_section_not_integer)
4323                        << 0 << LowerBound->getSourceRange());
4324     LowerBound = Res.get();
4325
4326     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4327         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4328       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4329           << 0 << LowerBound->getSourceRange();
4330   }
4331   if (Length) {
4332     auto Res =
4333         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4334     if (Res.isInvalid())
4335       return ExprError(Diag(Length->getExprLoc(),
4336                             diag::err_omp_typecheck_section_not_integer)
4337                        << 1 << Length->getSourceRange());
4338     Length = Res.get();
4339
4340     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4341         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4342       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4343           << 1 << Length->getSourceRange();
4344   }
4345
4346   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4347   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4348   // type. Note that functions are not objects, and that (in C99 parlance)
4349   // incomplete types are not object types.
4350   if (ResultTy->isFunctionType()) {
4351     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4352         << ResultTy << Base->getSourceRange();
4353     return ExprError();
4354   }
4355
4356   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4357                           diag::err_omp_section_incomplete_type, Base))
4358     return ExprError();
4359
4360   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4361     llvm::APSInt LowerBoundValue;
4362     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4363       // OpenMP 4.5, [2.4 Array Sections]
4364       // The array section must be a subset of the original array.
4365       if (LowerBoundValue.isNegative()) {
4366         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4367             << LowerBound->getSourceRange();
4368         return ExprError();
4369       }
4370     }
4371   }
4372
4373   if (Length) {
4374     llvm::APSInt LengthValue;
4375     if (Length->EvaluateAsInt(LengthValue, Context)) {
4376       // OpenMP 4.5, [2.4 Array Sections]
4377       // The length must evaluate to non-negative integers.
4378       if (LengthValue.isNegative()) {
4379         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4380             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4381             << Length->getSourceRange();
4382         return ExprError();
4383       }
4384     }
4385   } else if (ColonLoc.isValid() &&
4386              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4387                                       !OriginalTy->isVariableArrayType()))) {
4388     // OpenMP 4.5, [2.4 Array Sections]
4389     // When the size of the array dimension is not known, the length must be
4390     // specified explicitly.
4391     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4392         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4393     return ExprError();
4394   }
4395
4396   if (!Base->getType()->isSpecificPlaceholderType(
4397           BuiltinType::OMPArraySection)) {
4398     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4399     if (Result.isInvalid())
4400       return ExprError();
4401     Base = Result.get();
4402   }
4403   return new (Context)
4404       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4405                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4406 }
4407
4408 ExprResult
4409 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4410                                       Expr *Idx, SourceLocation RLoc) {
4411   Expr *LHSExp = Base;
4412   Expr *RHSExp = Idx;
4413
4414   ExprValueKind VK = VK_LValue;
4415   ExprObjectKind OK = OK_Ordinary;
4416
4417   // Per C++ core issue 1213, the result is an xvalue if either operand is
4418   // a non-lvalue array, and an lvalue otherwise.
4419   if (getLangOpts().CPlusPlus11 &&
4420       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4421        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4422     VK = VK_XValue;
4423
4424   // Perform default conversions.
4425   if (!LHSExp->getType()->getAs<VectorType>()) {
4426     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4427     if (Result.isInvalid())
4428       return ExprError();
4429     LHSExp = Result.get();
4430   }
4431   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4432   if (Result.isInvalid())
4433     return ExprError();
4434   RHSExp = Result.get();
4435
4436   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4437
4438   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4439   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4440   // in the subscript position. As a result, we need to derive the array base
4441   // and index from the expression types.
4442   Expr *BaseExpr, *IndexExpr;
4443   QualType ResultType;
4444   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4445     BaseExpr = LHSExp;
4446     IndexExpr = RHSExp;
4447     ResultType = Context.DependentTy;
4448   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4449     BaseExpr = LHSExp;
4450     IndexExpr = RHSExp;
4451     ResultType = PTy->getPointeeType();
4452   } else if (const ObjCObjectPointerType *PTy =
4453                LHSTy->getAs<ObjCObjectPointerType>()) {
4454     BaseExpr = LHSExp;
4455     IndexExpr = RHSExp;
4456
4457     // Use custom logic if this should be the pseudo-object subscript
4458     // expression.
4459     if (!LangOpts.isSubscriptPointerArithmetic())
4460       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4461                                           nullptr);
4462
4463     ResultType = PTy->getPointeeType();
4464   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4465      // Handle the uncommon case of "123[Ptr]".
4466     BaseExpr = RHSExp;
4467     IndexExpr = LHSExp;
4468     ResultType = PTy->getPointeeType();
4469   } else if (const ObjCObjectPointerType *PTy =
4470                RHSTy->getAs<ObjCObjectPointerType>()) {
4471      // Handle the uncommon case of "123[Ptr]".
4472     BaseExpr = RHSExp;
4473     IndexExpr = LHSExp;
4474     ResultType = PTy->getPointeeType();
4475     if (!LangOpts.isSubscriptPointerArithmetic()) {
4476       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4477         << ResultType << BaseExpr->getSourceRange();
4478       return ExprError();
4479     }
4480   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4481     BaseExpr = LHSExp;    // vectors: V[123]
4482     IndexExpr = RHSExp;
4483     VK = LHSExp->getValueKind();
4484     if (VK != VK_RValue)
4485       OK = OK_VectorComponent;
4486
4487     // FIXME: need to deal with const...
4488     ResultType = VTy->getElementType();
4489   } else if (LHSTy->isArrayType()) {
4490     // If we see an array that wasn't promoted by
4491     // DefaultFunctionArrayLvalueConversion, it must be an array that
4492     // wasn't promoted because of the C90 rule that doesn't
4493     // allow promoting non-lvalue arrays.  Warn, then
4494     // force the promotion here.
4495     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4496         LHSExp->getSourceRange();
4497     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4498                                CK_ArrayToPointerDecay).get();
4499     LHSTy = LHSExp->getType();
4500
4501     BaseExpr = LHSExp;
4502     IndexExpr = RHSExp;
4503     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4504   } else if (RHSTy->isArrayType()) {
4505     // Same as previous, except for 123[f().a] case
4506     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4507         RHSExp->getSourceRange();
4508     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4509                                CK_ArrayToPointerDecay).get();
4510     RHSTy = RHSExp->getType();
4511
4512     BaseExpr = RHSExp;
4513     IndexExpr = LHSExp;
4514     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4515   } else {
4516     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4517        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4518   }
4519   // C99 6.5.2.1p1
4520   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4521     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4522                      << IndexExpr->getSourceRange());
4523
4524   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4525        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4526          && !IndexExpr->isTypeDependent())
4527     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4528
4529   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4530   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4531   // type. Note that Functions are not objects, and that (in C99 parlance)
4532   // incomplete types are not object types.
4533   if (ResultType->isFunctionType()) {
4534     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4535       << ResultType << BaseExpr->getSourceRange();
4536     return ExprError();
4537   }
4538
4539   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4540     // GNU extension: subscripting on pointer to void
4541     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4542       << BaseExpr->getSourceRange();
4543
4544     // C forbids expressions of unqualified void type from being l-values.
4545     // See IsCForbiddenLValueType.
4546     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4547   } else if (!ResultType->isDependentType() &&
4548       RequireCompleteType(LLoc, ResultType,
4549                           diag::err_subscript_incomplete_type, BaseExpr))
4550     return ExprError();
4551
4552   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4553          !ResultType.isCForbiddenLValueType());
4554
4555   return new (Context)
4556       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4557 }
4558
4559 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4560                                   ParmVarDecl *Param) {
4561   if (Param->hasUnparsedDefaultArg()) {
4562     Diag(CallLoc,
4563          diag::err_use_of_default_argument_to_function_declared_later) <<
4564       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4565     Diag(UnparsedDefaultArgLocs[Param],
4566          diag::note_default_argument_declared_here);
4567     return true;
4568   }
4569   
4570   if (Param->hasUninstantiatedDefaultArg()) {
4571     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4572
4573     EnterExpressionEvaluationContext EvalContext(
4574         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4575
4576     // Instantiate the expression.
4577     MultiLevelTemplateArgumentList MutiLevelArgList
4578       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4579
4580     InstantiatingTemplate Inst(*this, CallLoc, Param,
4581                                MutiLevelArgList.getInnermost());
4582     if (Inst.isInvalid())
4583       return true;
4584     if (Inst.isAlreadyInstantiating()) {
4585       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4586       Param->setInvalidDecl();
4587       return true;
4588     }
4589
4590     ExprResult Result;
4591     {
4592       // C++ [dcl.fct.default]p5:
4593       //   The names in the [default argument] expression are bound, and
4594       //   the semantic constraints are checked, at the point where the
4595       //   default argument expression appears.
4596       ContextRAII SavedContext(*this, FD);
4597       LocalInstantiationScope Local(*this);
4598       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4599                                 /*DirectInit*/false);
4600     }
4601     if (Result.isInvalid())
4602       return true;
4603
4604     // Check the expression as an initializer for the parameter.
4605     InitializedEntity Entity
4606       = InitializedEntity::InitializeParameter(Context, Param);
4607     InitializationKind Kind
4608       = InitializationKind::CreateCopy(Param->getLocation(),
4609              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4610     Expr *ResultE = Result.getAs<Expr>();
4611
4612     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4613     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4614     if (Result.isInvalid())
4615       return true;
4616
4617     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4618                                  Param->getOuterLocStart());
4619     if (Result.isInvalid())
4620       return true;
4621
4622     // Remember the instantiated default argument.
4623     Param->setDefaultArg(Result.getAs<Expr>());
4624     if (ASTMutationListener *L = getASTMutationListener()) {
4625       L->DefaultArgumentInstantiated(Param);
4626     }
4627   }
4628
4629   // If the default argument expression is not set yet, we are building it now.
4630   if (!Param->hasInit()) {
4631     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4632     Param->setInvalidDecl();
4633     return true;
4634   }
4635
4636   // If the default expression creates temporaries, we need to
4637   // push them to the current stack of expression temporaries so they'll
4638   // be properly destroyed.
4639   // FIXME: We should really be rebuilding the default argument with new
4640   // bound temporaries; see the comment in PR5810.
4641   // We don't need to do that with block decls, though, because
4642   // blocks in default argument expression can never capture anything.
4643   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4644     // Set the "needs cleanups" bit regardless of whether there are
4645     // any explicit objects.
4646     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4647
4648     // Append all the objects to the cleanup list.  Right now, this
4649     // should always be a no-op, because blocks in default argument
4650     // expressions should never be able to capture anything.
4651     assert(!Init->getNumObjects() &&
4652            "default argument expression has capturing blocks?");
4653   }
4654
4655   // We already type-checked the argument, so we know it works. 
4656   // Just mark all of the declarations in this potentially-evaluated expression
4657   // as being "referenced".
4658   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4659                                    /*SkipLocalVariables=*/true);
4660   return false;
4661 }
4662
4663 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4664                                         FunctionDecl *FD, ParmVarDecl *Param) {
4665   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4666     return ExprError();
4667   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4668 }
4669
4670 Sema::VariadicCallType
4671 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4672                           Expr *Fn) {
4673   if (Proto && Proto->isVariadic()) {
4674     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4675       return VariadicConstructor;
4676     else if (Fn && Fn->getType()->isBlockPointerType())
4677       return VariadicBlock;
4678     else if (FDecl) {
4679       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4680         if (Method->isInstance())
4681           return VariadicMethod;
4682     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4683       return VariadicMethod;
4684     return VariadicFunction;
4685   }
4686   return VariadicDoesNotApply;
4687 }
4688
4689 namespace {
4690 class FunctionCallCCC : public FunctionCallFilterCCC {
4691 public:
4692   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4693                   unsigned NumArgs, MemberExpr *ME)
4694       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4695         FunctionName(FuncName) {}
4696
4697   bool ValidateCandidate(const TypoCorrection &candidate) override {
4698     if (!candidate.getCorrectionSpecifier() ||
4699         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4700       return false;
4701     }
4702
4703     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4704   }
4705
4706 private:
4707   const IdentifierInfo *const FunctionName;
4708 };
4709 }
4710
4711 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4712                                                FunctionDecl *FDecl,
4713                                                ArrayRef<Expr *> Args) {
4714   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4715   DeclarationName FuncName = FDecl->getDeclName();
4716   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4717
4718   if (TypoCorrection Corrected = S.CorrectTypo(
4719           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4720           S.getScopeForContext(S.CurContext), nullptr,
4721           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4722                                              Args.size(), ME),
4723           Sema::CTK_ErrorRecovery)) {
4724     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4725       if (Corrected.isOverloaded()) {
4726         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4727         OverloadCandidateSet::iterator Best;
4728         for (NamedDecl *CD : Corrected) {
4729           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4730             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4731                                    OCS);
4732         }
4733         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4734         case OR_Success:
4735           ND = Best->FoundDecl;
4736           Corrected.setCorrectionDecl(ND);
4737           break;
4738         default:
4739           break;
4740         }
4741       }
4742       ND = ND->getUnderlyingDecl();
4743       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4744         return Corrected;
4745     }
4746   }
4747   return TypoCorrection();
4748 }
4749
4750 /// ConvertArgumentsForCall - Converts the arguments specified in
4751 /// Args/NumArgs to the parameter types of the function FDecl with
4752 /// function prototype Proto. Call is the call expression itself, and
4753 /// Fn is the function expression. For a C++ member function, this
4754 /// routine does not attempt to convert the object argument. Returns
4755 /// true if the call is ill-formed.
4756 bool
4757 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4758                               FunctionDecl *FDecl,
4759                               const FunctionProtoType *Proto,
4760                               ArrayRef<Expr *> Args,
4761                               SourceLocation RParenLoc,
4762                               bool IsExecConfig) {
4763   // Bail out early if calling a builtin with custom typechecking.
4764   if (FDecl)
4765     if (unsigned ID = FDecl->getBuiltinID())
4766       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4767         return false;
4768
4769   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4770   // assignment, to the types of the corresponding parameter, ...
4771   unsigned NumParams = Proto->getNumParams();
4772   bool Invalid = false;
4773   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4774   unsigned FnKind = Fn->getType()->isBlockPointerType()
4775                        ? 1 /* block */
4776                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4777                                        : 0 /* function */);
4778
4779   // If too few arguments are available (and we don't have default
4780   // arguments for the remaining parameters), don't make the call.
4781   if (Args.size() < NumParams) {
4782     if (Args.size() < MinArgs) {
4783       TypoCorrection TC;
4784       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4785         unsigned diag_id =
4786             MinArgs == NumParams && !Proto->isVariadic()
4787                 ? diag::err_typecheck_call_too_few_args_suggest
4788                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4789         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4790                                         << static_cast<unsigned>(Args.size())
4791                                         << TC.getCorrectionRange());
4792       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4793         Diag(RParenLoc,
4794              MinArgs == NumParams && !Proto->isVariadic()
4795                  ? diag::err_typecheck_call_too_few_args_one
4796                  : diag::err_typecheck_call_too_few_args_at_least_one)
4797             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4798       else
4799         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4800                             ? diag::err_typecheck_call_too_few_args
4801                             : diag::err_typecheck_call_too_few_args_at_least)
4802             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4803             << Fn->getSourceRange();
4804
4805       // Emit the location of the prototype.
4806       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4807         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4808           << FDecl;
4809
4810       return true;
4811     }
4812     Call->setNumArgs(Context, NumParams);
4813   }
4814
4815   // If too many are passed and not variadic, error on the extras and drop
4816   // them.
4817   if (Args.size() > NumParams) {
4818     if (!Proto->isVariadic()) {
4819       TypoCorrection TC;
4820       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4821         unsigned diag_id =
4822             MinArgs == NumParams && !Proto->isVariadic()
4823                 ? diag::err_typecheck_call_too_many_args_suggest
4824                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4825         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4826                                         << static_cast<unsigned>(Args.size())
4827                                         << TC.getCorrectionRange());
4828       } else if (NumParams == 1 && FDecl &&
4829                  FDecl->getParamDecl(0)->getDeclName())
4830         Diag(Args[NumParams]->getLocStart(),
4831              MinArgs == NumParams
4832                  ? diag::err_typecheck_call_too_many_args_one
4833                  : diag::err_typecheck_call_too_many_args_at_most_one)
4834             << FnKind << FDecl->getParamDecl(0)
4835             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4836             << SourceRange(Args[NumParams]->getLocStart(),
4837                            Args.back()->getLocEnd());
4838       else
4839         Diag(Args[NumParams]->getLocStart(),
4840              MinArgs == NumParams
4841                  ? diag::err_typecheck_call_too_many_args
4842                  : diag::err_typecheck_call_too_many_args_at_most)
4843             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4844             << Fn->getSourceRange()
4845             << SourceRange(Args[NumParams]->getLocStart(),
4846                            Args.back()->getLocEnd());
4847
4848       // Emit the location of the prototype.
4849       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4850         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4851           << FDecl;
4852       
4853       // This deletes the extra arguments.
4854       Call->setNumArgs(Context, NumParams);
4855       return true;
4856     }
4857   }
4858   SmallVector<Expr *, 8> AllArgs;
4859   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4860   
4861   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4862                                    Proto, 0, Args, AllArgs, CallType);
4863   if (Invalid)
4864     return true;
4865   unsigned TotalNumArgs = AllArgs.size();
4866   for (unsigned i = 0; i < TotalNumArgs; ++i)
4867     Call->setArg(i, AllArgs[i]);
4868
4869   return false;
4870 }
4871
4872 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4873                                   const FunctionProtoType *Proto,
4874                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4875                                   SmallVectorImpl<Expr *> &AllArgs,
4876                                   VariadicCallType CallType, bool AllowExplicit,
4877                                   bool IsListInitialization) {
4878   unsigned NumParams = Proto->getNumParams();
4879   bool Invalid = false;
4880   size_t ArgIx = 0;
4881   // Continue to check argument types (even if we have too few/many args).
4882   for (unsigned i = FirstParam; i < NumParams; i++) {
4883     QualType ProtoArgType = Proto->getParamType(i);
4884
4885     Expr *Arg;
4886     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4887     if (ArgIx < Args.size()) {
4888       Arg = Args[ArgIx++];
4889
4890       if (RequireCompleteType(Arg->getLocStart(),
4891                               ProtoArgType,
4892                               diag::err_call_incomplete_argument, Arg))
4893         return true;
4894
4895       // Strip the unbridged-cast placeholder expression off, if applicable.
4896       bool CFAudited = false;
4897       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4898           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4899           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4900         Arg = stripARCUnbridgedCast(Arg);
4901       else if (getLangOpts().ObjCAutoRefCount &&
4902                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4903                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4904         CFAudited = true;
4905
4906       InitializedEntity Entity =
4907           Param ? InitializedEntity::InitializeParameter(Context, Param,
4908                                                          ProtoArgType)
4909                 : InitializedEntity::InitializeParameter(
4910                       Context, ProtoArgType, Proto->isParamConsumed(i));
4911
4912       // Remember that parameter belongs to a CF audited API.
4913       if (CFAudited)
4914         Entity.setParameterCFAudited();
4915
4916       ExprResult ArgE = PerformCopyInitialization(
4917           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4918       if (ArgE.isInvalid())
4919         return true;
4920
4921       Arg = ArgE.getAs<Expr>();
4922     } else {
4923       assert(Param && "can't use default arguments without a known callee");
4924
4925       ExprResult ArgExpr =
4926         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4927       if (ArgExpr.isInvalid())
4928         return true;
4929
4930       Arg = ArgExpr.getAs<Expr>();
4931     }
4932
4933     // Check for array bounds violations for each argument to the call. This
4934     // check only triggers warnings when the argument isn't a more complex Expr
4935     // with its own checking, such as a BinaryOperator.
4936     CheckArrayAccess(Arg);
4937
4938     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4939     CheckStaticArrayArgument(CallLoc, Param, Arg);
4940
4941     AllArgs.push_back(Arg);
4942   }
4943
4944   // If this is a variadic call, handle args passed through "...".
4945   if (CallType != VariadicDoesNotApply) {
4946     // Assume that extern "C" functions with variadic arguments that
4947     // return __unknown_anytype aren't *really* variadic.
4948     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4949         FDecl->isExternC()) {
4950       for (Expr *A : Args.slice(ArgIx)) {
4951         QualType paramType; // ignored
4952         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4953         Invalid |= arg.isInvalid();
4954         AllArgs.push_back(arg.get());
4955       }
4956
4957     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4958     } else {
4959       for (Expr *A : Args.slice(ArgIx)) {
4960         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4961         Invalid |= Arg.isInvalid();
4962         AllArgs.push_back(Arg.get());
4963       }
4964     }
4965
4966     // Check for array bounds violations.
4967     for (Expr *A : Args.slice(ArgIx))
4968       CheckArrayAccess(A);
4969   }
4970   return Invalid;
4971 }
4972
4973 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4974   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4975   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4976     TL = DTL.getOriginalLoc();
4977   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4978     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4979       << ATL.getLocalSourceRange();
4980 }
4981
4982 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4983 /// array parameter, check that it is non-null, and that if it is formed by
4984 /// array-to-pointer decay, the underlying array is sufficiently large.
4985 ///
4986 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4987 /// array type derivation, then for each call to the function, the value of the
4988 /// corresponding actual argument shall provide access to the first element of
4989 /// an array with at least as many elements as specified by the size expression.
4990 void
4991 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4992                                ParmVarDecl *Param,
4993                                const Expr *ArgExpr) {
4994   // Static array parameters are not supported in C++.
4995   if (!Param || getLangOpts().CPlusPlus)
4996     return;
4997
4998   QualType OrigTy = Param->getOriginalType();
4999
5000   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5001   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5002     return;
5003
5004   if (ArgExpr->isNullPointerConstant(Context,
5005                                      Expr::NPC_NeverValueDependent)) {
5006     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5007     DiagnoseCalleeStaticArrayParam(*this, Param);
5008     return;
5009   }
5010
5011   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5012   if (!CAT)
5013     return;
5014
5015   const ConstantArrayType *ArgCAT =
5016     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5017   if (!ArgCAT)
5018     return;
5019
5020   if (ArgCAT->getSize().ult(CAT->getSize())) {
5021     Diag(CallLoc, diag::warn_static_array_too_small)
5022       << ArgExpr->getSourceRange()
5023       << (unsigned) ArgCAT->getSize().getZExtValue()
5024       << (unsigned) CAT->getSize().getZExtValue();
5025     DiagnoseCalleeStaticArrayParam(*this, Param);
5026   }
5027 }
5028
5029 /// Given a function expression of unknown-any type, try to rebuild it
5030 /// to have a function type.
5031 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5032
5033 /// Is the given type a placeholder that we need to lower out
5034 /// immediately during argument processing?
5035 static bool isPlaceholderToRemoveAsArg(QualType type) {
5036   // Placeholders are never sugared.
5037   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5038   if (!placeholder) return false;
5039
5040   switch (placeholder->getKind()) {
5041   // Ignore all the non-placeholder types.
5042 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5043   case BuiltinType::Id:
5044 #include "clang/Basic/OpenCLImageTypes.def"
5045 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5046 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5047 #include "clang/AST/BuiltinTypes.def"
5048     return false;
5049
5050   // We cannot lower out overload sets; they might validly be resolved
5051   // by the call machinery.
5052   case BuiltinType::Overload:
5053     return false;
5054
5055   // Unbridged casts in ARC can be handled in some call positions and
5056   // should be left in place.
5057   case BuiltinType::ARCUnbridgedCast:
5058     return false;
5059
5060   // Pseudo-objects should be converted as soon as possible.
5061   case BuiltinType::PseudoObject:
5062     return true;
5063
5064   // The debugger mode could theoretically but currently does not try
5065   // to resolve unknown-typed arguments based on known parameter types.
5066   case BuiltinType::UnknownAny:
5067     return true;
5068
5069   // These are always invalid as call arguments and should be reported.
5070   case BuiltinType::BoundMember:
5071   case BuiltinType::BuiltinFn:
5072   case BuiltinType::OMPArraySection:
5073     return true;
5074
5075   }
5076   llvm_unreachable("bad builtin type kind");
5077 }
5078
5079 /// Check an argument list for placeholders that we won't try to
5080 /// handle later.
5081 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5082   // Apply this processing to all the arguments at once instead of
5083   // dying at the first failure.
5084   bool hasInvalid = false;
5085   for (size_t i = 0, e = args.size(); i != e; i++) {
5086     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5087       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5088       if (result.isInvalid()) hasInvalid = true;
5089       else args[i] = result.get();
5090     } else if (hasInvalid) {
5091       (void)S.CorrectDelayedTyposInExpr(args[i]);
5092     }
5093   }
5094   return hasInvalid;
5095 }
5096
5097 /// If a builtin function has a pointer argument with no explicit address
5098 /// space, then it should be able to accept a pointer to any address
5099 /// space as input.  In order to do this, we need to replace the
5100 /// standard builtin declaration with one that uses the same address space
5101 /// as the call.
5102 ///
5103 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5104 ///                  it does not contain any pointer arguments without
5105 ///                  an address space qualifer.  Otherwise the rewritten
5106 ///                  FunctionDecl is returned.
5107 /// TODO: Handle pointer return types.
5108 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5109                                                 const FunctionDecl *FDecl,
5110                                                 MultiExprArg ArgExprs) {
5111
5112   QualType DeclType = FDecl->getType();
5113   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5114
5115   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5116       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5117     return nullptr;
5118
5119   bool NeedsNewDecl = false;
5120   unsigned i = 0;
5121   SmallVector<QualType, 8> OverloadParams;
5122
5123   for (QualType ParamType : FT->param_types()) {
5124
5125     // Convert array arguments to pointer to simplify type lookup.
5126     ExprResult ArgRes =
5127         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5128     if (ArgRes.isInvalid())
5129       return nullptr;
5130     Expr *Arg = ArgRes.get();
5131     QualType ArgType = Arg->getType();
5132     if (!ParamType->isPointerType() ||
5133         ParamType.getQualifiers().hasAddressSpace() ||
5134         !ArgType->isPointerType() ||
5135         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5136       OverloadParams.push_back(ParamType);
5137       continue;
5138     }
5139
5140     NeedsNewDecl = true;
5141     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5142
5143     QualType PointeeType = ParamType->getPointeeType();
5144     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5145     OverloadParams.push_back(Context.getPointerType(PointeeType));
5146   }
5147
5148   if (!NeedsNewDecl)
5149     return nullptr;
5150
5151   FunctionProtoType::ExtProtoInfo EPI;
5152   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5153                                                 OverloadParams, EPI);
5154   DeclContext *Parent = Context.getTranslationUnitDecl();
5155   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5156                                                     FDecl->getLocation(),
5157                                                     FDecl->getLocation(),
5158                                                     FDecl->getIdentifier(),
5159                                                     OverloadTy,
5160                                                     /*TInfo=*/nullptr,
5161                                                     SC_Extern, false,
5162                                                     /*hasPrototype=*/true);
5163   SmallVector<ParmVarDecl*, 16> Params;
5164   FT = cast<FunctionProtoType>(OverloadTy);
5165   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5166     QualType ParamType = FT->getParamType(i);
5167     ParmVarDecl *Parm =
5168         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5169                                 SourceLocation(), nullptr, ParamType,
5170                                 /*TInfo=*/nullptr, SC_None, nullptr);
5171     Parm->setScopeInfo(0, i);
5172     Params.push_back(Parm);
5173   }
5174   OverloadDecl->setParams(Params);
5175   return OverloadDecl;
5176 }
5177
5178 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5179                                     FunctionDecl *Callee,
5180                                     MultiExprArg ArgExprs) {
5181   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5182   // similar attributes) really don't like it when functions are called with an
5183   // invalid number of args.
5184   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5185                          /*PartialOverloading=*/false) &&
5186       !Callee->isVariadic())
5187     return;
5188   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5189     return;
5190
5191   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5192     S.Diag(Fn->getLocStart(),
5193            isa<CXXMethodDecl>(Callee)
5194                ? diag::err_ovl_no_viable_member_function_in_call
5195                : diag::err_ovl_no_viable_function_in_call)
5196         << Callee << Callee->getSourceRange();
5197     S.Diag(Callee->getLocation(),
5198            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5199         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5200     return;
5201   }
5202 }
5203
5204 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5205 /// This provides the location of the left/right parens and a list of comma
5206 /// locations.
5207 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5208                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5209                                Expr *ExecConfig, bool IsExecConfig) {
5210   // Since this might be a postfix expression, get rid of ParenListExprs.
5211   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5212   if (Result.isInvalid()) return ExprError();
5213   Fn = Result.get();
5214
5215   if (checkArgsForPlaceholders(*this, ArgExprs))
5216     return ExprError();
5217
5218   if (getLangOpts().CPlusPlus) {
5219     // If this is a pseudo-destructor expression, build the call immediately.
5220     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5221       if (!ArgExprs.empty()) {
5222         // Pseudo-destructor calls should not have any arguments.
5223         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5224             << FixItHint::CreateRemoval(
5225                    SourceRange(ArgExprs.front()->getLocStart(),
5226                                ArgExprs.back()->getLocEnd()));
5227       }
5228
5229       return new (Context)
5230           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5231     }
5232     if (Fn->getType() == Context.PseudoObjectTy) {
5233       ExprResult result = CheckPlaceholderExpr(Fn);
5234       if (result.isInvalid()) return ExprError();
5235       Fn = result.get();
5236     }
5237
5238     // Determine whether this is a dependent call inside a C++ template,
5239     // in which case we won't do any semantic analysis now.
5240     bool Dependent = false;
5241     if (Fn->isTypeDependent())
5242       Dependent = true;
5243     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5244       Dependent = true;
5245
5246     if (Dependent) {
5247       if (ExecConfig) {
5248         return new (Context) CUDAKernelCallExpr(
5249             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5250             Context.DependentTy, VK_RValue, RParenLoc);
5251       } else {
5252         return new (Context) CallExpr(
5253             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5254       }
5255     }
5256
5257     // Determine whether this is a call to an object (C++ [over.call.object]).
5258     if (Fn->getType()->isRecordType())
5259       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5260                                           RParenLoc);
5261
5262     if (Fn->getType() == Context.UnknownAnyTy) {
5263       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5264       if (result.isInvalid()) return ExprError();
5265       Fn = result.get();
5266     }
5267
5268     if (Fn->getType() == Context.BoundMemberTy) {
5269       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5270                                        RParenLoc);
5271     }
5272   }
5273
5274   // Check for overloaded calls.  This can happen even in C due to extensions.
5275   if (Fn->getType() == Context.OverloadTy) {
5276     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5277
5278     // We aren't supposed to apply this logic if there's an '&' involved.
5279     if (!find.HasFormOfMemberPointer) {
5280       OverloadExpr *ovl = find.Expression;
5281       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5282         return BuildOverloadedCallExpr(
5283             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5284             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5285       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5286                                        RParenLoc);
5287     }
5288   }
5289
5290   // If we're directly calling a function, get the appropriate declaration.
5291   if (Fn->getType() == Context.UnknownAnyTy) {
5292     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5293     if (result.isInvalid()) return ExprError();
5294     Fn = result.get();
5295   }
5296
5297   Expr *NakedFn = Fn->IgnoreParens();
5298
5299   bool CallingNDeclIndirectly = false;
5300   NamedDecl *NDecl = nullptr;
5301   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5302     if (UnOp->getOpcode() == UO_AddrOf) {
5303       CallingNDeclIndirectly = true;
5304       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5305     }
5306   }
5307
5308   if (isa<DeclRefExpr>(NakedFn)) {
5309     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5310
5311     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5312     if (FDecl && FDecl->getBuiltinID()) {
5313       // Rewrite the function decl for this builtin by replacing parameters
5314       // with no explicit address space with the address space of the arguments
5315       // in ArgExprs.
5316       if ((FDecl =
5317                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5318         NDecl = FDecl;
5319         Fn = DeclRefExpr::Create(
5320             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5321             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5322       }
5323     }
5324   } else if (isa<MemberExpr>(NakedFn))
5325     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5326
5327   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5328     if (CallingNDeclIndirectly &&
5329         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5330                                            Fn->getLocStart()))
5331       return ExprError();
5332
5333     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5334       return ExprError();
5335
5336     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5337   }
5338
5339   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5340                                ExecConfig, IsExecConfig);
5341 }
5342
5343 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5344 ///
5345 /// __builtin_astype( value, dst type )
5346 ///
5347 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5348                                  SourceLocation BuiltinLoc,
5349                                  SourceLocation RParenLoc) {
5350   ExprValueKind VK = VK_RValue;
5351   ExprObjectKind OK = OK_Ordinary;
5352   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5353   QualType SrcTy = E->getType();
5354   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5355     return ExprError(Diag(BuiltinLoc,
5356                           diag::err_invalid_astype_of_different_size)
5357                      << DstTy
5358                      << SrcTy
5359                      << E->getSourceRange());
5360   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5361 }
5362
5363 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5364 /// provided arguments.
5365 ///
5366 /// __builtin_convertvector( value, dst type )
5367 ///
5368 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5369                                         SourceLocation BuiltinLoc,
5370                                         SourceLocation RParenLoc) {
5371   TypeSourceInfo *TInfo;
5372   GetTypeFromParser(ParsedDestTy, &TInfo);
5373   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5374 }
5375
5376 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5377 /// i.e. an expression not of \p OverloadTy.  The expression should
5378 /// unary-convert to an expression of function-pointer or
5379 /// block-pointer type.
5380 ///
5381 /// \param NDecl the declaration being called, if available
5382 ExprResult
5383 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5384                             SourceLocation LParenLoc,
5385                             ArrayRef<Expr *> Args,
5386                             SourceLocation RParenLoc,
5387                             Expr *Config, bool IsExecConfig) {
5388   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5389   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5390
5391   // Functions with 'interrupt' attribute cannot be called directly.
5392   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5393     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5394     return ExprError();
5395   }
5396
5397   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5398   // so there's some risk when calling out to non-interrupt handler functions
5399   // that the callee might not preserve them. This is easy to diagnose here,
5400   // but can be very challenging to debug.
5401   if (auto *Caller = getCurFunctionDecl())
5402     if (Caller->hasAttr<ARMInterruptAttr>())
5403       if (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())
5404         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5405
5406   // Promote the function operand.
5407   // We special-case function promotion here because we only allow promoting
5408   // builtin functions to function pointers in the callee of a call.
5409   ExprResult Result;
5410   if (BuiltinID &&
5411       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5412     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5413                                CK_BuiltinFnToFnPtr).get();
5414   } else {
5415     Result = CallExprUnaryConversions(Fn);
5416   }
5417   if (Result.isInvalid())
5418     return ExprError();
5419   Fn = Result.get();
5420
5421   // Make the call expr early, before semantic checks.  This guarantees cleanup
5422   // of arguments and function on error.
5423   CallExpr *TheCall;
5424   if (Config)
5425     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5426                                                cast<CallExpr>(Config), Args,
5427                                                Context.BoolTy, VK_RValue,
5428                                                RParenLoc);
5429   else
5430     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5431                                      VK_RValue, RParenLoc);
5432
5433   if (!getLangOpts().CPlusPlus) {
5434     // C cannot always handle TypoExpr nodes in builtin calls and direct
5435     // function calls as their argument checking don't necessarily handle
5436     // dependent types properly, so make sure any TypoExprs have been
5437     // dealt with.
5438     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5439     if (!Result.isUsable()) return ExprError();
5440     TheCall = dyn_cast<CallExpr>(Result.get());
5441     if (!TheCall) return Result;
5442     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5443   }
5444
5445   // Bail out early if calling a builtin with custom typechecking.
5446   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5447     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5448
5449  retry:
5450   const FunctionType *FuncT;
5451   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5452     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5453     // have type pointer to function".
5454     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5455     if (!FuncT)
5456       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5457                          << Fn->getType() << Fn->getSourceRange());
5458   } else if (const BlockPointerType *BPT =
5459                Fn->getType()->getAs<BlockPointerType>()) {
5460     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5461   } else {
5462     // Handle calls to expressions of unknown-any type.
5463     if (Fn->getType() == Context.UnknownAnyTy) {
5464       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5465       if (rewrite.isInvalid()) return ExprError();
5466       Fn = rewrite.get();
5467       TheCall->setCallee(Fn);
5468       goto retry;
5469     }
5470
5471     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5472       << Fn->getType() << Fn->getSourceRange());
5473   }
5474
5475   if (getLangOpts().CUDA) {
5476     if (Config) {
5477       // CUDA: Kernel calls must be to global functions
5478       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5479         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5480             << FDecl->getName() << Fn->getSourceRange());
5481
5482       // CUDA: Kernel function must have 'void' return type
5483       if (!FuncT->getReturnType()->isVoidType())
5484         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5485             << Fn->getType() << Fn->getSourceRange());
5486     } else {
5487       // CUDA: Calls to global functions must be configured
5488       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5489         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5490             << FDecl->getName() << Fn->getSourceRange());
5491     }
5492   }
5493
5494   // Check for a valid return type
5495   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5496                           FDecl))
5497     return ExprError();
5498
5499   // We know the result type of the call, set it.
5500   TheCall->setType(FuncT->getCallResultType(Context));
5501   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5502
5503   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5504   if (Proto) {
5505     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5506                                 IsExecConfig))
5507       return ExprError();
5508   } else {
5509     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5510
5511     if (FDecl) {
5512       // Check if we have too few/too many template arguments, based
5513       // on our knowledge of the function definition.
5514       const FunctionDecl *Def = nullptr;
5515       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5516         Proto = Def->getType()->getAs<FunctionProtoType>();
5517        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5518           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5519           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5520       }
5521       
5522       // If the function we're calling isn't a function prototype, but we have
5523       // a function prototype from a prior declaratiom, use that prototype.
5524       if (!FDecl->hasPrototype())
5525         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5526     }
5527
5528     // Promote the arguments (C99 6.5.2.2p6).
5529     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5530       Expr *Arg = Args[i];
5531
5532       if (Proto && i < Proto->getNumParams()) {
5533         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5534             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5535         ExprResult ArgE =
5536             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5537         if (ArgE.isInvalid())
5538           return true;
5539         
5540         Arg = ArgE.getAs<Expr>();
5541
5542       } else {
5543         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5544
5545         if (ArgE.isInvalid())
5546           return true;
5547
5548         Arg = ArgE.getAs<Expr>();
5549       }
5550       
5551       if (RequireCompleteType(Arg->getLocStart(),
5552                               Arg->getType(),
5553                               diag::err_call_incomplete_argument, Arg))
5554         return ExprError();
5555
5556       TheCall->setArg(i, Arg);
5557     }
5558   }
5559
5560   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5561     if (!Method->isStatic())
5562       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5563         << Fn->getSourceRange());
5564
5565   // Check for sentinels
5566   if (NDecl)
5567     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5568
5569   // Do special checking on direct calls to functions.
5570   if (FDecl) {
5571     if (CheckFunctionCall(FDecl, TheCall, Proto))
5572       return ExprError();
5573
5574     if (BuiltinID)
5575       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5576   } else if (NDecl) {
5577     if (CheckPointerCall(NDecl, TheCall, Proto))
5578       return ExprError();
5579   } else {
5580     if (CheckOtherCall(TheCall, Proto))
5581       return ExprError();
5582   }
5583
5584   return MaybeBindToTemporary(TheCall);
5585 }
5586
5587 ExprResult
5588 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5589                            SourceLocation RParenLoc, Expr *InitExpr) {
5590   assert(Ty && "ActOnCompoundLiteral(): missing type");
5591   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5592
5593   TypeSourceInfo *TInfo;
5594   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5595   if (!TInfo)
5596     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5597
5598   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5599 }
5600
5601 ExprResult
5602 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5603                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5604   QualType literalType = TInfo->getType();
5605
5606   if (literalType->isArrayType()) {
5607     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5608           diag::err_illegal_decl_array_incomplete_type,
5609           SourceRange(LParenLoc,
5610                       LiteralExpr->getSourceRange().getEnd())))
5611       return ExprError();
5612     if (literalType->isVariableArrayType())
5613       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5614         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5615   } else if (!literalType->isDependentType() &&
5616              RequireCompleteType(LParenLoc, literalType,
5617                diag::err_typecheck_decl_incomplete_type,
5618                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5619     return ExprError();
5620
5621   InitializedEntity Entity
5622     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5623   InitializationKind Kind
5624     = InitializationKind::CreateCStyleCast(LParenLoc, 
5625                                            SourceRange(LParenLoc, RParenLoc),
5626                                            /*InitList=*/true);
5627   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5628   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5629                                       &literalType);
5630   if (Result.isInvalid())
5631     return ExprError();
5632   LiteralExpr = Result.get();
5633
5634   bool isFileScope = !CurContext->isFunctionOrMethod();
5635   if (isFileScope &&
5636       !LiteralExpr->isTypeDependent() &&
5637       !LiteralExpr->isValueDependent() &&
5638       !literalType->isDependentType()) { // 6.5.2.5p3
5639     if (CheckForConstantInitializer(LiteralExpr, literalType))
5640       return ExprError();
5641   }
5642
5643   // In C, compound literals are l-values for some reason.
5644   // For GCC compatibility, in C++, file-scope array compound literals with
5645   // constant initializers are also l-values, and compound literals are
5646   // otherwise prvalues.
5647   //
5648   // (GCC also treats C++ list-initialized file-scope array prvalues with
5649   // constant initializers as l-values, but that's non-conforming, so we don't
5650   // follow it there.)
5651   //
5652   // FIXME: It would be better to handle the lvalue cases as materializing and
5653   // lifetime-extending a temporary object, but our materialized temporaries
5654   // representation only supports lifetime extension from a variable, not "out
5655   // of thin air".
5656   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5657   // is bound to the result of applying array-to-pointer decay to the compound
5658   // literal.
5659   // FIXME: GCC supports compound literals of reference type, which should
5660   // obviously have a value kind derived from the kind of reference involved.
5661   ExprValueKind VK =
5662       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5663           ? VK_RValue
5664           : VK_LValue;
5665
5666   return MaybeBindToTemporary(
5667       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5668                                         VK, LiteralExpr, isFileScope));
5669 }
5670
5671 ExprResult
5672 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5673                     SourceLocation RBraceLoc) {
5674   // Immediately handle non-overload placeholders.  Overloads can be
5675   // resolved contextually, but everything else here can't.
5676   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5677     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5678       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5679
5680       // Ignore failures; dropping the entire initializer list because
5681       // of one failure would be terrible for indexing/etc.
5682       if (result.isInvalid()) continue;
5683
5684       InitArgList[I] = result.get();
5685     }
5686   }
5687
5688   // Semantic analysis for initializers is done by ActOnDeclarator() and
5689   // CheckInitializer() - it requires knowledge of the object being intialized.
5690
5691   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5692                                                RBraceLoc);
5693   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5694   return E;
5695 }
5696
5697 /// Do an explicit extend of the given block pointer if we're in ARC.
5698 void Sema::maybeExtendBlockObject(ExprResult &E) {
5699   assert(E.get()->getType()->isBlockPointerType());
5700   assert(E.get()->isRValue());
5701
5702   // Only do this in an r-value context.
5703   if (!getLangOpts().ObjCAutoRefCount) return;
5704
5705   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5706                                CK_ARCExtendBlockObject, E.get(),
5707                                /*base path*/ nullptr, VK_RValue);
5708   Cleanup.setExprNeedsCleanups(true);
5709 }
5710
5711 /// Prepare a conversion of the given expression to an ObjC object
5712 /// pointer type.
5713 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5714   QualType type = E.get()->getType();
5715   if (type->isObjCObjectPointerType()) {
5716     return CK_BitCast;
5717   } else if (type->isBlockPointerType()) {
5718     maybeExtendBlockObject(E);
5719     return CK_BlockPointerToObjCPointerCast;
5720   } else {
5721     assert(type->isPointerType());
5722     return CK_CPointerToObjCPointerCast;
5723   }
5724 }
5725
5726 /// Prepares for a scalar cast, performing all the necessary stages
5727 /// except the final cast and returning the kind required.
5728 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5729   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5730   // Also, callers should have filtered out the invalid cases with
5731   // pointers.  Everything else should be possible.
5732
5733   QualType SrcTy = Src.get()->getType();
5734   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5735     return CK_NoOp;
5736
5737   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5738   case Type::STK_MemberPointer:
5739     llvm_unreachable("member pointer type in C");
5740
5741   case Type::STK_CPointer:
5742   case Type::STK_BlockPointer:
5743   case Type::STK_ObjCObjectPointer:
5744     switch (DestTy->getScalarTypeKind()) {
5745     case Type::STK_CPointer: {
5746       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5747       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5748       if (SrcAS != DestAS)
5749         return CK_AddressSpaceConversion;
5750       return CK_BitCast;
5751     }
5752     case Type::STK_BlockPointer:
5753       return (SrcKind == Type::STK_BlockPointer
5754                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5755     case Type::STK_ObjCObjectPointer:
5756       if (SrcKind == Type::STK_ObjCObjectPointer)
5757         return CK_BitCast;
5758       if (SrcKind == Type::STK_CPointer)
5759         return CK_CPointerToObjCPointerCast;
5760       maybeExtendBlockObject(Src);
5761       return CK_BlockPointerToObjCPointerCast;
5762     case Type::STK_Bool:
5763       return CK_PointerToBoolean;
5764     case Type::STK_Integral:
5765       return CK_PointerToIntegral;
5766     case Type::STK_Floating:
5767     case Type::STK_FloatingComplex:
5768     case Type::STK_IntegralComplex:
5769     case Type::STK_MemberPointer:
5770       llvm_unreachable("illegal cast from pointer");
5771     }
5772     llvm_unreachable("Should have returned before this");
5773
5774   case Type::STK_Bool: // casting from bool is like casting from an integer
5775   case Type::STK_Integral:
5776     switch (DestTy->getScalarTypeKind()) {
5777     case Type::STK_CPointer:
5778     case Type::STK_ObjCObjectPointer:
5779     case Type::STK_BlockPointer:
5780       if (Src.get()->isNullPointerConstant(Context,
5781                                            Expr::NPC_ValueDependentIsNull))
5782         return CK_NullToPointer;
5783       return CK_IntegralToPointer;
5784     case Type::STK_Bool:
5785       return CK_IntegralToBoolean;
5786     case Type::STK_Integral:
5787       return CK_IntegralCast;
5788     case Type::STK_Floating:
5789       return CK_IntegralToFloating;
5790     case Type::STK_IntegralComplex:
5791       Src = ImpCastExprToType(Src.get(),
5792                       DestTy->castAs<ComplexType>()->getElementType(),
5793                       CK_IntegralCast);
5794       return CK_IntegralRealToComplex;
5795     case Type::STK_FloatingComplex:
5796       Src = ImpCastExprToType(Src.get(),
5797                       DestTy->castAs<ComplexType>()->getElementType(),
5798                       CK_IntegralToFloating);
5799       return CK_FloatingRealToComplex;
5800     case Type::STK_MemberPointer:
5801       llvm_unreachable("member pointer type in C");
5802     }
5803     llvm_unreachable("Should have returned before this");
5804
5805   case Type::STK_Floating:
5806     switch (DestTy->getScalarTypeKind()) {
5807     case Type::STK_Floating:
5808       return CK_FloatingCast;
5809     case Type::STK_Bool:
5810       return CK_FloatingToBoolean;
5811     case Type::STK_Integral:
5812       return CK_FloatingToIntegral;
5813     case Type::STK_FloatingComplex:
5814       Src = ImpCastExprToType(Src.get(),
5815                               DestTy->castAs<ComplexType>()->getElementType(),
5816                               CK_FloatingCast);
5817       return CK_FloatingRealToComplex;
5818     case Type::STK_IntegralComplex:
5819       Src = ImpCastExprToType(Src.get(),
5820                               DestTy->castAs<ComplexType>()->getElementType(),
5821                               CK_FloatingToIntegral);
5822       return CK_IntegralRealToComplex;
5823     case Type::STK_CPointer:
5824     case Type::STK_ObjCObjectPointer:
5825     case Type::STK_BlockPointer:
5826       llvm_unreachable("valid float->pointer cast?");
5827     case Type::STK_MemberPointer:
5828       llvm_unreachable("member pointer type in C");
5829     }
5830     llvm_unreachable("Should have returned before this");
5831
5832   case Type::STK_FloatingComplex:
5833     switch (DestTy->getScalarTypeKind()) {
5834     case Type::STK_FloatingComplex:
5835       return CK_FloatingComplexCast;
5836     case Type::STK_IntegralComplex:
5837       return CK_FloatingComplexToIntegralComplex;
5838     case Type::STK_Floating: {
5839       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5840       if (Context.hasSameType(ET, DestTy))
5841         return CK_FloatingComplexToReal;
5842       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5843       return CK_FloatingCast;
5844     }
5845     case Type::STK_Bool:
5846       return CK_FloatingComplexToBoolean;
5847     case Type::STK_Integral:
5848       Src = ImpCastExprToType(Src.get(),
5849                               SrcTy->castAs<ComplexType>()->getElementType(),
5850                               CK_FloatingComplexToReal);
5851       return CK_FloatingToIntegral;
5852     case Type::STK_CPointer:
5853     case Type::STK_ObjCObjectPointer:
5854     case Type::STK_BlockPointer:
5855       llvm_unreachable("valid complex float->pointer cast?");
5856     case Type::STK_MemberPointer:
5857       llvm_unreachable("member pointer type in C");
5858     }
5859     llvm_unreachable("Should have returned before this");
5860
5861   case Type::STK_IntegralComplex:
5862     switch (DestTy->getScalarTypeKind()) {
5863     case Type::STK_FloatingComplex:
5864       return CK_IntegralComplexToFloatingComplex;
5865     case Type::STK_IntegralComplex:
5866       return CK_IntegralComplexCast;
5867     case Type::STK_Integral: {
5868       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5869       if (Context.hasSameType(ET, DestTy))
5870         return CK_IntegralComplexToReal;
5871       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5872       return CK_IntegralCast;
5873     }
5874     case Type::STK_Bool:
5875       return CK_IntegralComplexToBoolean;
5876     case Type::STK_Floating:
5877       Src = ImpCastExprToType(Src.get(),
5878                               SrcTy->castAs<ComplexType>()->getElementType(),
5879                               CK_IntegralComplexToReal);
5880       return CK_IntegralToFloating;
5881     case Type::STK_CPointer:
5882     case Type::STK_ObjCObjectPointer:
5883     case Type::STK_BlockPointer:
5884       llvm_unreachable("valid complex int->pointer cast?");
5885     case Type::STK_MemberPointer:
5886       llvm_unreachable("member pointer type in C");
5887     }
5888     llvm_unreachable("Should have returned before this");
5889   }
5890
5891   llvm_unreachable("Unhandled scalar cast");
5892 }
5893
5894 static bool breakDownVectorType(QualType type, uint64_t &len,
5895                                 QualType &eltType) {
5896   // Vectors are simple.
5897   if (const VectorType *vecType = type->getAs<VectorType>()) {
5898     len = vecType->getNumElements();
5899     eltType = vecType->getElementType();
5900     assert(eltType->isScalarType());
5901     return true;
5902   }
5903   
5904   // We allow lax conversion to and from non-vector types, but only if
5905   // they're real types (i.e. non-complex, non-pointer scalar types).
5906   if (!type->isRealType()) return false;
5907   
5908   len = 1;
5909   eltType = type;
5910   return true;
5911 }
5912
5913 /// Are the two types lax-compatible vector types?  That is, given
5914 /// that one of them is a vector, do they have equal storage sizes,
5915 /// where the storage size is the number of elements times the element
5916 /// size?
5917 ///
5918 /// This will also return false if either of the types is neither a
5919 /// vector nor a real type.
5920 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5921   assert(destTy->isVectorType() || srcTy->isVectorType());
5922   
5923   // Disallow lax conversions between scalars and ExtVectors (these
5924   // conversions are allowed for other vector types because common headers
5925   // depend on them).  Most scalar OP ExtVector cases are handled by the
5926   // splat path anyway, which does what we want (convert, not bitcast).
5927   // What this rules out for ExtVectors is crazy things like char4*float.
5928   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5929   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5930
5931   uint64_t srcLen, destLen;
5932   QualType srcEltTy, destEltTy;
5933   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5934   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5935   
5936   // ASTContext::getTypeSize will return the size rounded up to a
5937   // power of 2, so instead of using that, we need to use the raw
5938   // element size multiplied by the element count.
5939   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5940   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5941   
5942   return (srcLen * srcEltSize == destLen * destEltSize);
5943 }
5944
5945 /// Is this a legal conversion between two types, one of which is
5946 /// known to be a vector type?
5947 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5948   assert(destTy->isVectorType() || srcTy->isVectorType());
5949   
5950   if (!Context.getLangOpts().LaxVectorConversions)
5951     return false;
5952   return areLaxCompatibleVectorTypes(srcTy, destTy);
5953 }
5954
5955 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5956                            CastKind &Kind) {
5957   assert(VectorTy->isVectorType() && "Not a vector type!");
5958
5959   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5960     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5961       return Diag(R.getBegin(),
5962                   Ty->isVectorType() ?
5963                   diag::err_invalid_conversion_between_vectors :
5964                   diag::err_invalid_conversion_between_vector_and_integer)
5965         << VectorTy << Ty << R;
5966   } else
5967     return Diag(R.getBegin(),
5968                 diag::err_invalid_conversion_between_vector_and_scalar)
5969       << VectorTy << Ty << R;
5970
5971   Kind = CK_BitCast;
5972   return false;
5973 }
5974
5975 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5976   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5977
5978   if (DestElemTy == SplattedExpr->getType())
5979     return SplattedExpr;
5980
5981   assert(DestElemTy->isFloatingType() ||
5982          DestElemTy->isIntegralOrEnumerationType());
5983
5984   CastKind CK;
5985   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5986     // OpenCL requires that we convert `true` boolean expressions to -1, but
5987     // only when splatting vectors.
5988     if (DestElemTy->isFloatingType()) {
5989       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5990       // in two steps: boolean to signed integral, then to floating.
5991       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5992                                                  CK_BooleanToSignedIntegral);
5993       SplattedExpr = CastExprRes.get();
5994       CK = CK_IntegralToFloating;
5995     } else {
5996       CK = CK_BooleanToSignedIntegral;
5997     }
5998   } else {
5999     ExprResult CastExprRes = SplattedExpr;
6000     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6001     if (CastExprRes.isInvalid())
6002       return ExprError();
6003     SplattedExpr = CastExprRes.get();
6004   }
6005   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6006 }
6007
6008 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6009                                     Expr *CastExpr, CastKind &Kind) {
6010   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6011
6012   QualType SrcTy = CastExpr->getType();
6013
6014   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6015   // an ExtVectorType.
6016   // In OpenCL, casts between vectors of different types are not allowed.
6017   // (See OpenCL 6.2).
6018   if (SrcTy->isVectorType()) {
6019     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6020         || (getLangOpts().OpenCL &&
6021             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6022       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6023         << DestTy << SrcTy << R;
6024       return ExprError();
6025     }
6026     Kind = CK_BitCast;
6027     return CastExpr;
6028   }
6029
6030   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6031   // conversion will take place first from scalar to elt type, and then
6032   // splat from elt type to vector.
6033   if (SrcTy->isPointerType())
6034     return Diag(R.getBegin(),
6035                 diag::err_invalid_conversion_between_vector_and_scalar)
6036       << DestTy << SrcTy << R;
6037
6038   Kind = CK_VectorSplat;
6039   return prepareVectorSplat(DestTy, CastExpr);
6040 }
6041
6042 ExprResult
6043 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6044                     Declarator &D, ParsedType &Ty,
6045                     SourceLocation RParenLoc, Expr *CastExpr) {
6046   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6047          "ActOnCastExpr(): missing type or expr");
6048
6049   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6050   if (D.isInvalidType())
6051     return ExprError();
6052
6053   if (getLangOpts().CPlusPlus) {
6054     // Check that there are no default arguments (C++ only).
6055     CheckExtraCXXDefaultArguments(D);
6056   } else {
6057     // Make sure any TypoExprs have been dealt with.
6058     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6059     if (!Res.isUsable())
6060       return ExprError();
6061     CastExpr = Res.get();
6062   }
6063
6064   checkUnusedDeclAttributes(D);
6065
6066   QualType castType = castTInfo->getType();
6067   Ty = CreateParsedType(castType, castTInfo);
6068
6069   bool isVectorLiteral = false;
6070
6071   // Check for an altivec or OpenCL literal,
6072   // i.e. all the elements are integer constants.
6073   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6074   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6075   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6076        && castType->isVectorType() && (PE || PLE)) {
6077     if (PLE && PLE->getNumExprs() == 0) {
6078       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6079       return ExprError();
6080     }
6081     if (PE || PLE->getNumExprs() == 1) {
6082       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6083       if (!E->getType()->isVectorType())
6084         isVectorLiteral = true;
6085     }
6086     else
6087       isVectorLiteral = true;
6088   }
6089
6090   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6091   // then handle it as such.
6092   if (isVectorLiteral)
6093     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6094
6095   // If the Expr being casted is a ParenListExpr, handle it specially.
6096   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6097   // sequence of BinOp comma operators.
6098   if (isa<ParenListExpr>(CastExpr)) {
6099     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6100     if (Result.isInvalid()) return ExprError();
6101     CastExpr = Result.get();
6102   }
6103
6104   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6105       !getSourceManager().isInSystemMacro(LParenLoc))
6106     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6107   
6108   CheckTollFreeBridgeCast(castType, CastExpr);
6109   
6110   CheckObjCBridgeRelatedCast(castType, CastExpr);
6111
6112   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6113
6114   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6115 }
6116
6117 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6118                                     SourceLocation RParenLoc, Expr *E,
6119                                     TypeSourceInfo *TInfo) {
6120   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6121          "Expected paren or paren list expression");
6122
6123   Expr **exprs;
6124   unsigned numExprs;
6125   Expr *subExpr;
6126   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6127   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6128     LiteralLParenLoc = PE->getLParenLoc();
6129     LiteralRParenLoc = PE->getRParenLoc();
6130     exprs = PE->getExprs();
6131     numExprs = PE->getNumExprs();
6132   } else { // isa<ParenExpr> by assertion at function entrance
6133     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6134     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6135     subExpr = cast<ParenExpr>(E)->getSubExpr();
6136     exprs = &subExpr;
6137     numExprs = 1;
6138   }
6139
6140   QualType Ty = TInfo->getType();
6141   assert(Ty->isVectorType() && "Expected vector type");
6142
6143   SmallVector<Expr *, 8> initExprs;
6144   const VectorType *VTy = Ty->getAs<VectorType>();
6145   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6146   
6147   // '(...)' form of vector initialization in AltiVec: the number of
6148   // initializers must be one or must match the size of the vector.
6149   // If a single value is specified in the initializer then it will be
6150   // replicated to all the components of the vector
6151   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6152     // The number of initializers must be one or must match the size of the
6153     // vector. If a single value is specified in the initializer then it will
6154     // be replicated to all the components of the vector
6155     if (numExprs == 1) {
6156       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6157       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6158       if (Literal.isInvalid())
6159         return ExprError();
6160       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6161                                   PrepareScalarCast(Literal, ElemTy));
6162       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6163     }
6164     else if (numExprs < numElems) {
6165       Diag(E->getExprLoc(),
6166            diag::err_incorrect_number_of_vector_initializers);
6167       return ExprError();
6168     }
6169     else
6170       initExprs.append(exprs, exprs + numExprs);
6171   }
6172   else {
6173     // For OpenCL, when the number of initializers is a single value,
6174     // it will be replicated to all components of the vector.
6175     if (getLangOpts().OpenCL &&
6176         VTy->getVectorKind() == VectorType::GenericVector &&
6177         numExprs == 1) {
6178         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6179         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6180         if (Literal.isInvalid())
6181           return ExprError();
6182         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6183                                     PrepareScalarCast(Literal, ElemTy));
6184         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6185     }
6186     
6187     initExprs.append(exprs, exprs + numExprs);
6188   }
6189   // FIXME: This means that pretty-printing the final AST will produce curly
6190   // braces instead of the original commas.
6191   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6192                                                    initExprs, LiteralRParenLoc);
6193   initE->setType(Ty);
6194   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6195 }
6196
6197 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6198 /// the ParenListExpr into a sequence of comma binary operators.
6199 ExprResult
6200 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6201   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6202   if (!E)
6203     return OrigExpr;
6204
6205   ExprResult Result(E->getExpr(0));
6206
6207   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6208     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6209                         E->getExpr(i));
6210
6211   if (Result.isInvalid()) return ExprError();
6212
6213   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6214 }
6215
6216 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6217                                     SourceLocation R,
6218                                     MultiExprArg Val) {
6219   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6220   return expr;
6221 }
6222
6223 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6224 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6225 /// emitted.
6226 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6227                                       SourceLocation QuestionLoc) {
6228   Expr *NullExpr = LHSExpr;
6229   Expr *NonPointerExpr = RHSExpr;
6230   Expr::NullPointerConstantKind NullKind =
6231       NullExpr->isNullPointerConstant(Context,
6232                                       Expr::NPC_ValueDependentIsNotNull);
6233
6234   if (NullKind == Expr::NPCK_NotNull) {
6235     NullExpr = RHSExpr;
6236     NonPointerExpr = LHSExpr;
6237     NullKind =
6238         NullExpr->isNullPointerConstant(Context,
6239                                         Expr::NPC_ValueDependentIsNotNull);
6240   }
6241
6242   if (NullKind == Expr::NPCK_NotNull)
6243     return false;
6244
6245   if (NullKind == Expr::NPCK_ZeroExpression)
6246     return false;
6247
6248   if (NullKind == Expr::NPCK_ZeroLiteral) {
6249     // In this case, check to make sure that we got here from a "NULL"
6250     // string in the source code.
6251     NullExpr = NullExpr->IgnoreParenImpCasts();
6252     SourceLocation loc = NullExpr->getExprLoc();
6253     if (!findMacroSpelling(loc, "NULL"))
6254       return false;
6255   }
6256
6257   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6258   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6259       << NonPointerExpr->getType() << DiagType
6260       << NonPointerExpr->getSourceRange();
6261   return true;
6262 }
6263
6264 /// \brief Return false if the condition expression is valid, true otherwise.
6265 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6266   QualType CondTy = Cond->getType();
6267
6268   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6269   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6270     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6271       << CondTy << Cond->getSourceRange();
6272     return true;
6273   }
6274
6275   // C99 6.5.15p2
6276   if (CondTy->isScalarType()) return false;
6277
6278   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6279     << CondTy << Cond->getSourceRange();
6280   return true;
6281 }
6282
6283 /// \brief Handle when one or both operands are void type.
6284 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6285                                          ExprResult &RHS) {
6286     Expr *LHSExpr = LHS.get();
6287     Expr *RHSExpr = RHS.get();
6288
6289     if (!LHSExpr->getType()->isVoidType())
6290       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6291         << RHSExpr->getSourceRange();
6292     if (!RHSExpr->getType()->isVoidType())
6293       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6294         << LHSExpr->getSourceRange();
6295     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6296     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6297     return S.Context.VoidTy;
6298 }
6299
6300 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6301 /// true otherwise.
6302 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6303                                         QualType PointerTy) {
6304   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6305       !NullExpr.get()->isNullPointerConstant(S.Context,
6306                                             Expr::NPC_ValueDependentIsNull))
6307     return true;
6308
6309   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6310   return false;
6311 }
6312
6313 /// \brief Checks compatibility between two pointers and return the resulting
6314 /// type.
6315 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6316                                                      ExprResult &RHS,
6317                                                      SourceLocation Loc) {
6318   QualType LHSTy = LHS.get()->getType();
6319   QualType RHSTy = RHS.get()->getType();
6320
6321   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6322     // Two identical pointers types are always compatible.
6323     return LHSTy;
6324   }
6325
6326   QualType lhptee, rhptee;
6327
6328   // Get the pointee types.
6329   bool IsBlockPointer = false;
6330   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6331     lhptee = LHSBTy->getPointeeType();
6332     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6333     IsBlockPointer = true;
6334   } else {
6335     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6336     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6337   }
6338
6339   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6340   // differently qualified versions of compatible types, the result type is
6341   // a pointer to an appropriately qualified version of the composite
6342   // type.
6343
6344   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6345   // clause doesn't make sense for our extensions. E.g. address space 2 should
6346   // be incompatible with address space 3: they may live on different devices or
6347   // anything.
6348   Qualifiers lhQual = lhptee.getQualifiers();
6349   Qualifiers rhQual = rhptee.getQualifiers();
6350
6351   unsigned ResultAddrSpace = 0;
6352   unsigned LAddrSpace = lhQual.getAddressSpace();
6353   unsigned RAddrSpace = rhQual.getAddressSpace();
6354   if (S.getLangOpts().OpenCL) {
6355     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6356     // spaces is disallowed.
6357     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6358       ResultAddrSpace = LAddrSpace;
6359     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6360       ResultAddrSpace = RAddrSpace;
6361     else {
6362       S.Diag(Loc,
6363              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6364           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6365           << RHS.get()->getSourceRange();
6366       return QualType();
6367     }
6368   }
6369
6370   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6371   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6372   lhQual.removeCVRQualifiers();
6373   rhQual.removeCVRQualifiers();
6374
6375   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6376   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6377   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6378   // qual types are compatible iff
6379   //  * corresponded types are compatible
6380   //  * CVR qualifiers are equal
6381   //  * address spaces are equal
6382   // Thus for conditional operator we merge CVR and address space unqualified
6383   // pointees and if there is a composite type we return a pointer to it with
6384   // merged qualifiers.
6385   if (S.getLangOpts().OpenCL) {
6386     LHSCastKind = LAddrSpace == ResultAddrSpace
6387                       ? CK_BitCast
6388                       : CK_AddressSpaceConversion;
6389     RHSCastKind = RAddrSpace == ResultAddrSpace
6390                       ? CK_BitCast
6391                       : CK_AddressSpaceConversion;
6392     lhQual.removeAddressSpace();
6393     rhQual.removeAddressSpace();
6394   }
6395
6396   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6397   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6398
6399   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6400
6401   if (CompositeTy.isNull()) {
6402     // In this situation, we assume void* type. No especially good
6403     // reason, but this is what gcc does, and we do have to pick
6404     // to get a consistent AST.
6405     QualType incompatTy;
6406     incompatTy = S.Context.getPointerType(
6407         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6408     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6409     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6410     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6411     // for casts between types with incompatible address space qualifiers.
6412     // For the following code the compiler produces casts between global and
6413     // local address spaces of the corresponded innermost pointees:
6414     // local int *global *a;
6415     // global int *global *b;
6416     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6417     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6418         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6419         << RHS.get()->getSourceRange();
6420     return incompatTy;
6421   }
6422
6423   // The pointer types are compatible.
6424   // In case of OpenCL ResultTy should have the address space qualifier
6425   // which is a superset of address spaces of both the 2nd and the 3rd
6426   // operands of the conditional operator.
6427   QualType ResultTy = [&, ResultAddrSpace]() {
6428     if (S.getLangOpts().OpenCL) {
6429       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6430       CompositeQuals.setAddressSpace(ResultAddrSpace);
6431       return S.Context
6432           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6433           .withCVRQualifiers(MergedCVRQual);
6434     }
6435     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6436   }();
6437   if (IsBlockPointer)
6438     ResultTy = S.Context.getBlockPointerType(ResultTy);
6439   else
6440     ResultTy = S.Context.getPointerType(ResultTy);
6441
6442   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6443   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6444   return ResultTy;
6445 }
6446
6447 /// \brief Return the resulting type when the operands are both block pointers.
6448 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6449                                                           ExprResult &LHS,
6450                                                           ExprResult &RHS,
6451                                                           SourceLocation Loc) {
6452   QualType LHSTy = LHS.get()->getType();
6453   QualType RHSTy = RHS.get()->getType();
6454
6455   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6456     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6457       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6458       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6459       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6460       return destType;
6461     }
6462     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6463       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6464       << RHS.get()->getSourceRange();
6465     return QualType();
6466   }
6467
6468   // We have 2 block pointer types.
6469   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6470 }
6471
6472 /// \brief Return the resulting type when the operands are both pointers.
6473 static QualType
6474 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6475                                             ExprResult &RHS,
6476                                             SourceLocation Loc) {
6477   // get the pointer types
6478   QualType LHSTy = LHS.get()->getType();
6479   QualType RHSTy = RHS.get()->getType();
6480
6481   // get the "pointed to" types
6482   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6483   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6484
6485   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6486   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6487     // Figure out necessary qualifiers (C99 6.5.15p6)
6488     QualType destPointee
6489       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6490     QualType destType = S.Context.getPointerType(destPointee);
6491     // Add qualifiers if necessary.
6492     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6493     // Promote to void*.
6494     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6495     return destType;
6496   }
6497   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6498     QualType destPointee
6499       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6500     QualType destType = S.Context.getPointerType(destPointee);
6501     // Add qualifiers if necessary.
6502     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6503     // Promote to void*.
6504     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6505     return destType;
6506   }
6507
6508   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6509 }
6510
6511 /// \brief Return false if the first expression is not an integer and the second
6512 /// expression is not a pointer, true otherwise.
6513 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6514                                         Expr* PointerExpr, SourceLocation Loc,
6515                                         bool IsIntFirstExpr) {
6516   if (!PointerExpr->getType()->isPointerType() ||
6517       !Int.get()->getType()->isIntegerType())
6518     return false;
6519
6520   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6521   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6522
6523   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6524     << Expr1->getType() << Expr2->getType()
6525     << Expr1->getSourceRange() << Expr2->getSourceRange();
6526   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6527                             CK_IntegralToPointer);
6528   return true;
6529 }
6530
6531 /// \brief Simple conversion between integer and floating point types.
6532 ///
6533 /// Used when handling the OpenCL conditional operator where the
6534 /// condition is a vector while the other operands are scalar.
6535 ///
6536 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6537 /// types are either integer or floating type. Between the two
6538 /// operands, the type with the higher rank is defined as the "result
6539 /// type". The other operand needs to be promoted to the same type. No
6540 /// other type promotion is allowed. We cannot use
6541 /// UsualArithmeticConversions() for this purpose, since it always
6542 /// promotes promotable types.
6543 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6544                                             ExprResult &RHS,
6545                                             SourceLocation QuestionLoc) {
6546   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6547   if (LHS.isInvalid())
6548     return QualType();
6549   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6550   if (RHS.isInvalid())
6551     return QualType();
6552
6553   // For conversion purposes, we ignore any qualifiers.
6554   // For example, "const float" and "float" are equivalent.
6555   QualType LHSType =
6556     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6557   QualType RHSType =
6558     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6559
6560   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6561     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6562       << LHSType << LHS.get()->getSourceRange();
6563     return QualType();
6564   }
6565
6566   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6567     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6568       << RHSType << RHS.get()->getSourceRange();
6569     return QualType();
6570   }
6571
6572   // If both types are identical, no conversion is needed.
6573   if (LHSType == RHSType)
6574     return LHSType;
6575
6576   // Now handle "real" floating types (i.e. float, double, long double).
6577   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6578     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6579                                  /*IsCompAssign = */ false);
6580
6581   // Finally, we have two differing integer types.
6582   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6583   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6584 }
6585
6586 /// \brief Convert scalar operands to a vector that matches the
6587 ///        condition in length.
6588 ///
6589 /// Used when handling the OpenCL conditional operator where the
6590 /// condition is a vector while the other operands are scalar.
6591 ///
6592 /// We first compute the "result type" for the scalar operands
6593 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6594 /// into a vector of that type where the length matches the condition
6595 /// vector type. s6.11.6 requires that the element types of the result
6596 /// and the condition must have the same number of bits.
6597 static QualType
6598 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6599                               QualType CondTy, SourceLocation QuestionLoc) {
6600   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6601   if (ResTy.isNull()) return QualType();
6602
6603   const VectorType *CV = CondTy->getAs<VectorType>();
6604   assert(CV);
6605
6606   // Determine the vector result type
6607   unsigned NumElements = CV->getNumElements();
6608   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6609
6610   // Ensure that all types have the same number of bits
6611   if (S.Context.getTypeSize(CV->getElementType())
6612       != S.Context.getTypeSize(ResTy)) {
6613     // Since VectorTy is created internally, it does not pretty print
6614     // with an OpenCL name. Instead, we just print a description.
6615     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6616     SmallString<64> Str;
6617     llvm::raw_svector_ostream OS(Str);
6618     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6619     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6620       << CondTy << OS.str();
6621     return QualType();
6622   }
6623
6624   // Convert operands to the vector result type
6625   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6626   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6627
6628   return VectorTy;
6629 }
6630
6631 /// \brief Return false if this is a valid OpenCL condition vector
6632 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6633                                        SourceLocation QuestionLoc) {
6634   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6635   // integral type.
6636   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6637   assert(CondTy);
6638   QualType EleTy = CondTy->getElementType();
6639   if (EleTy->isIntegerType()) return false;
6640
6641   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6642     << Cond->getType() << Cond->getSourceRange();
6643   return true;
6644 }
6645
6646 /// \brief Return false if the vector condition type and the vector
6647 ///        result type are compatible.
6648 ///
6649 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6650 /// number of elements, and their element types have the same number
6651 /// of bits.
6652 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6653                               SourceLocation QuestionLoc) {
6654   const VectorType *CV = CondTy->getAs<VectorType>();
6655   const VectorType *RV = VecResTy->getAs<VectorType>();
6656   assert(CV && RV);
6657
6658   if (CV->getNumElements() != RV->getNumElements()) {
6659     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6660       << CondTy << VecResTy;
6661     return true;
6662   }
6663
6664   QualType CVE = CV->getElementType();
6665   QualType RVE = RV->getElementType();
6666
6667   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6668     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6669       << CondTy << VecResTy;
6670     return true;
6671   }
6672
6673   return false;
6674 }
6675
6676 /// \brief Return the resulting type for the conditional operator in
6677 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6678 ///        s6.3.i) when the condition is a vector type.
6679 static QualType
6680 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6681                              ExprResult &LHS, ExprResult &RHS,
6682                              SourceLocation QuestionLoc) {
6683   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6684   if (Cond.isInvalid())
6685     return QualType();
6686   QualType CondTy = Cond.get()->getType();
6687
6688   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6689     return QualType();
6690
6691   // If either operand is a vector then find the vector type of the
6692   // result as specified in OpenCL v1.1 s6.3.i.
6693   if (LHS.get()->getType()->isVectorType() ||
6694       RHS.get()->getType()->isVectorType()) {
6695     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6696                                               /*isCompAssign*/false,
6697                                               /*AllowBothBool*/true,
6698                                               /*AllowBoolConversions*/false);
6699     if (VecResTy.isNull()) return QualType();
6700     // The result type must match the condition type as specified in
6701     // OpenCL v1.1 s6.11.6.
6702     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6703       return QualType();
6704     return VecResTy;
6705   }
6706
6707   // Both operands are scalar.
6708   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6709 }
6710
6711 /// \brief Return true if the Expr is block type
6712 static bool checkBlockType(Sema &S, const Expr *E) {
6713   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6714     QualType Ty = CE->getCallee()->getType();
6715     if (Ty->isBlockPointerType()) {
6716       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6717       return true;
6718     }
6719   }
6720   return false;
6721 }
6722
6723 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6724 /// In that case, LHS = cond.
6725 /// C99 6.5.15
6726 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6727                                         ExprResult &RHS, ExprValueKind &VK,
6728                                         ExprObjectKind &OK,
6729                                         SourceLocation QuestionLoc) {
6730
6731   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6732   if (!LHSResult.isUsable()) return QualType();
6733   LHS = LHSResult;
6734
6735   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6736   if (!RHSResult.isUsable()) return QualType();
6737   RHS = RHSResult;
6738
6739   // C++ is sufficiently different to merit its own checker.
6740   if (getLangOpts().CPlusPlus)
6741     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6742
6743   VK = VK_RValue;
6744   OK = OK_Ordinary;
6745
6746   // The OpenCL operator with a vector condition is sufficiently
6747   // different to merit its own checker.
6748   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6749     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6750
6751   // First, check the condition.
6752   Cond = UsualUnaryConversions(Cond.get());
6753   if (Cond.isInvalid())
6754     return QualType();
6755   if (checkCondition(*this, Cond.get(), QuestionLoc))
6756     return QualType();
6757
6758   // Now check the two expressions.
6759   if (LHS.get()->getType()->isVectorType() ||
6760       RHS.get()->getType()->isVectorType())
6761     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6762                                /*AllowBothBool*/true,
6763                                /*AllowBoolConversions*/false);
6764
6765   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6766   if (LHS.isInvalid() || RHS.isInvalid())
6767     return QualType();
6768
6769   QualType LHSTy = LHS.get()->getType();
6770   QualType RHSTy = RHS.get()->getType();
6771
6772   // Diagnose attempts to convert between __float128 and long double where
6773   // such conversions currently can't be handled.
6774   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6775     Diag(QuestionLoc,
6776          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6777       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6778     return QualType();
6779   }
6780
6781   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6782   // selection operator (?:).
6783   if (getLangOpts().OpenCL &&
6784       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6785     return QualType();
6786   }
6787
6788   // If both operands have arithmetic type, do the usual arithmetic conversions
6789   // to find a common type: C99 6.5.15p3,5.
6790   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6791     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6792     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6793
6794     return ResTy;
6795   }
6796
6797   // If both operands are the same structure or union type, the result is that
6798   // type.
6799   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6800     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6801       if (LHSRT->getDecl() == RHSRT->getDecl())
6802         // "If both the operands have structure or union type, the result has
6803         // that type."  This implies that CV qualifiers are dropped.
6804         return LHSTy.getUnqualifiedType();
6805     // FIXME: Type of conditional expression must be complete in C mode.
6806   }
6807
6808   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6809   // The following || allows only one side to be void (a GCC-ism).
6810   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6811     return checkConditionalVoidType(*this, LHS, RHS);
6812   }
6813
6814   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6815   // the type of the other operand."
6816   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6817   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6818
6819   // All objective-c pointer type analysis is done here.
6820   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6821                                                         QuestionLoc);
6822   if (LHS.isInvalid() || RHS.isInvalid())
6823     return QualType();
6824   if (!compositeType.isNull())
6825     return compositeType;
6826
6827
6828   // Handle block pointer types.
6829   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6830     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6831                                                      QuestionLoc);
6832
6833   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6834   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6835     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6836                                                        QuestionLoc);
6837
6838   // GCC compatibility: soften pointer/integer mismatch.  Note that
6839   // null pointers have been filtered out by this point.
6840   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6841       /*isIntFirstExpr=*/true))
6842     return RHSTy;
6843   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6844       /*isIntFirstExpr=*/false))
6845     return LHSTy;
6846
6847   // Emit a better diagnostic if one of the expressions is a null pointer
6848   // constant and the other is not a pointer type. In this case, the user most
6849   // likely forgot to take the address of the other expression.
6850   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6851     return QualType();
6852
6853   // Otherwise, the operands are not compatible.
6854   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6855     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6856     << RHS.get()->getSourceRange();
6857   return QualType();
6858 }
6859
6860 /// FindCompositeObjCPointerType - Helper method to find composite type of
6861 /// two objective-c pointer types of the two input expressions.
6862 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6863                                             SourceLocation QuestionLoc) {
6864   QualType LHSTy = LHS.get()->getType();
6865   QualType RHSTy = RHS.get()->getType();
6866
6867   // Handle things like Class and struct objc_class*.  Here we case the result
6868   // to the pseudo-builtin, because that will be implicitly cast back to the
6869   // redefinition type if an attempt is made to access its fields.
6870   if (LHSTy->isObjCClassType() &&
6871       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6872     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6873     return LHSTy;
6874   }
6875   if (RHSTy->isObjCClassType() &&
6876       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6877     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6878     return RHSTy;
6879   }
6880   // And the same for struct objc_object* / id
6881   if (LHSTy->isObjCIdType() &&
6882       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6883     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6884     return LHSTy;
6885   }
6886   if (RHSTy->isObjCIdType() &&
6887       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6888     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6889     return RHSTy;
6890   }
6891   // And the same for struct objc_selector* / SEL
6892   if (Context.isObjCSelType(LHSTy) &&
6893       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6894     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6895     return LHSTy;
6896   }
6897   if (Context.isObjCSelType(RHSTy) &&
6898       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6899     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6900     return RHSTy;
6901   }
6902   // Check constraints for Objective-C object pointers types.
6903   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6904
6905     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6906       // Two identical object pointer types are always compatible.
6907       return LHSTy;
6908     }
6909     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6910     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6911     QualType compositeType = LHSTy;
6912
6913     // If both operands are interfaces and either operand can be
6914     // assigned to the other, use that type as the composite
6915     // type. This allows
6916     //   xxx ? (A*) a : (B*) b
6917     // where B is a subclass of A.
6918     //
6919     // Additionally, as for assignment, if either type is 'id'
6920     // allow silent coercion. Finally, if the types are
6921     // incompatible then make sure to use 'id' as the composite
6922     // type so the result is acceptable for sending messages to.
6923
6924     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6925     // It could return the composite type.
6926     if (!(compositeType =
6927           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6928       // Nothing more to do.
6929     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6930       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6931     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6932       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6933     } else if ((LHSTy->isObjCQualifiedIdType() ||
6934                 RHSTy->isObjCQualifiedIdType()) &&
6935                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6936       // Need to handle "id<xx>" explicitly.
6937       // GCC allows qualified id and any Objective-C type to devolve to
6938       // id. Currently localizing to here until clear this should be
6939       // part of ObjCQualifiedIdTypesAreCompatible.
6940       compositeType = Context.getObjCIdType();
6941     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6942       compositeType = Context.getObjCIdType();
6943     } else {
6944       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6945       << LHSTy << RHSTy
6946       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6947       QualType incompatTy = Context.getObjCIdType();
6948       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6949       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6950       return incompatTy;
6951     }
6952     // The object pointer types are compatible.
6953     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6954     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6955     return compositeType;
6956   }
6957   // Check Objective-C object pointer types and 'void *'
6958   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6959     if (getLangOpts().ObjCAutoRefCount) {
6960       // ARC forbids the implicit conversion of object pointers to 'void *',
6961       // so these types are not compatible.
6962       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6963           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6964       LHS = RHS = true;
6965       return QualType();
6966     }
6967     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6968     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6969     QualType destPointee
6970     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6971     QualType destType = Context.getPointerType(destPointee);
6972     // Add qualifiers if necessary.
6973     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6974     // Promote to void*.
6975     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6976     return destType;
6977   }
6978   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6979     if (getLangOpts().ObjCAutoRefCount) {
6980       // ARC forbids the implicit conversion of object pointers to 'void *',
6981       // so these types are not compatible.
6982       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6983           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6984       LHS = RHS = true;
6985       return QualType();
6986     }
6987     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6988     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6989     QualType destPointee
6990     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6991     QualType destType = Context.getPointerType(destPointee);
6992     // Add qualifiers if necessary.
6993     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6994     // Promote to void*.
6995     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6996     return destType;
6997   }
6998   return QualType();
6999 }
7000
7001 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7002 /// ParenRange in parentheses.
7003 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7004                                const PartialDiagnostic &Note,
7005                                SourceRange ParenRange) {
7006   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7007   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7008       EndLoc.isValid()) {
7009     Self.Diag(Loc, Note)
7010       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7011       << FixItHint::CreateInsertion(EndLoc, ")");
7012   } else {
7013     // We can't display the parentheses, so just show the bare note.
7014     Self.Diag(Loc, Note) << ParenRange;
7015   }
7016 }
7017
7018 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7019   return BinaryOperator::isAdditiveOp(Opc) ||
7020          BinaryOperator::isMultiplicativeOp(Opc) ||
7021          BinaryOperator::isShiftOp(Opc);
7022 }
7023
7024 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7025 /// expression, either using a built-in or overloaded operator,
7026 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7027 /// expression.
7028 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7029                                    Expr **RHSExprs) {
7030   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7031   E = E->IgnoreImpCasts();
7032   E = E->IgnoreConversionOperator();
7033   E = E->IgnoreImpCasts();
7034
7035   // Built-in binary operator.
7036   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7037     if (IsArithmeticOp(OP->getOpcode())) {
7038       *Opcode = OP->getOpcode();
7039       *RHSExprs = OP->getRHS();
7040       return true;
7041     }
7042   }
7043
7044   // Overloaded operator.
7045   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7046     if (Call->getNumArgs() != 2)
7047       return false;
7048
7049     // Make sure this is really a binary operator that is safe to pass into
7050     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7051     OverloadedOperatorKind OO = Call->getOperator();
7052     if (OO < OO_Plus || OO > OO_Arrow ||
7053         OO == OO_PlusPlus || OO == OO_MinusMinus)
7054       return false;
7055
7056     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7057     if (IsArithmeticOp(OpKind)) {
7058       *Opcode = OpKind;
7059       *RHSExprs = Call->getArg(1);
7060       return true;
7061     }
7062   }
7063
7064   return false;
7065 }
7066
7067 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7068 /// or is a logical expression such as (x==y) which has int type, but is
7069 /// commonly interpreted as boolean.
7070 static bool ExprLooksBoolean(Expr *E) {
7071   E = E->IgnoreParenImpCasts();
7072
7073   if (E->getType()->isBooleanType())
7074     return true;
7075   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7076     return OP->isComparisonOp() || OP->isLogicalOp();
7077   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7078     return OP->getOpcode() == UO_LNot;
7079   if (E->getType()->isPointerType())
7080     return true;
7081
7082   return false;
7083 }
7084
7085 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7086 /// and binary operator are mixed in a way that suggests the programmer assumed
7087 /// the conditional operator has higher precedence, for example:
7088 /// "int x = a + someBinaryCondition ? 1 : 2".
7089 static void DiagnoseConditionalPrecedence(Sema &Self,
7090                                           SourceLocation OpLoc,
7091                                           Expr *Condition,
7092                                           Expr *LHSExpr,
7093                                           Expr *RHSExpr) {
7094   BinaryOperatorKind CondOpcode;
7095   Expr *CondRHS;
7096
7097   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7098     return;
7099   if (!ExprLooksBoolean(CondRHS))
7100     return;
7101
7102   // The condition is an arithmetic binary expression, with a right-
7103   // hand side that looks boolean, so warn.
7104
7105   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7106       << Condition->getSourceRange()
7107       << BinaryOperator::getOpcodeStr(CondOpcode);
7108
7109   SuggestParentheses(Self, OpLoc,
7110     Self.PDiag(diag::note_precedence_silence)
7111       << BinaryOperator::getOpcodeStr(CondOpcode),
7112     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7113
7114   SuggestParentheses(Self, OpLoc,
7115     Self.PDiag(diag::note_precedence_conditional_first),
7116     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7117 }
7118
7119 /// Compute the nullability of a conditional expression.
7120 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7121                                               QualType LHSTy, QualType RHSTy,
7122                                               ASTContext &Ctx) {
7123   if (!ResTy->isAnyPointerType())
7124     return ResTy;
7125
7126   auto GetNullability = [&Ctx](QualType Ty) {
7127     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7128     if (Kind)
7129       return *Kind;
7130     return NullabilityKind::Unspecified;
7131   };
7132
7133   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7134   NullabilityKind MergedKind;
7135
7136   // Compute nullability of a binary conditional expression.
7137   if (IsBin) {
7138     if (LHSKind == NullabilityKind::NonNull)
7139       MergedKind = NullabilityKind::NonNull;
7140     else
7141       MergedKind = RHSKind;
7142   // Compute nullability of a normal conditional expression.
7143   } else {
7144     if (LHSKind == NullabilityKind::Nullable ||
7145         RHSKind == NullabilityKind::Nullable)
7146       MergedKind = NullabilityKind::Nullable;
7147     else if (LHSKind == NullabilityKind::NonNull)
7148       MergedKind = RHSKind;
7149     else if (RHSKind == NullabilityKind::NonNull)
7150       MergedKind = LHSKind;
7151     else
7152       MergedKind = NullabilityKind::Unspecified;
7153   }
7154
7155   // Return if ResTy already has the correct nullability.
7156   if (GetNullability(ResTy) == MergedKind)
7157     return ResTy;
7158
7159   // Strip all nullability from ResTy.
7160   while (ResTy->getNullability(Ctx))
7161     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7162
7163   // Create a new AttributedType with the new nullability kind.
7164   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7165   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7166 }
7167
7168 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7169 /// in the case of a the GNU conditional expr extension.
7170 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7171                                     SourceLocation ColonLoc,
7172                                     Expr *CondExpr, Expr *LHSExpr,
7173                                     Expr *RHSExpr) {
7174   if (!getLangOpts().CPlusPlus) {
7175     // C cannot handle TypoExpr nodes in the condition because it
7176     // doesn't handle dependent types properly, so make sure any TypoExprs have
7177     // been dealt with before checking the operands.
7178     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7179     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7180     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7181
7182     if (!CondResult.isUsable())
7183       return ExprError();
7184
7185     if (LHSExpr) {
7186       if (!LHSResult.isUsable())
7187         return ExprError();
7188     }
7189
7190     if (!RHSResult.isUsable())
7191       return ExprError();
7192
7193     CondExpr = CondResult.get();
7194     LHSExpr = LHSResult.get();
7195     RHSExpr = RHSResult.get();
7196   }
7197
7198   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7199   // was the condition.
7200   OpaqueValueExpr *opaqueValue = nullptr;
7201   Expr *commonExpr = nullptr;
7202   if (!LHSExpr) {
7203     commonExpr = CondExpr;
7204     // Lower out placeholder types first.  This is important so that we don't
7205     // try to capture a placeholder. This happens in few cases in C++; such
7206     // as Objective-C++'s dictionary subscripting syntax.
7207     if (commonExpr->hasPlaceholderType()) {
7208       ExprResult result = CheckPlaceholderExpr(commonExpr);
7209       if (!result.isUsable()) return ExprError();
7210       commonExpr = result.get();
7211     }
7212     // We usually want to apply unary conversions *before* saving, except
7213     // in the special case of a C++ l-value conditional.
7214     if (!(getLangOpts().CPlusPlus
7215           && !commonExpr->isTypeDependent()
7216           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7217           && commonExpr->isGLValue()
7218           && commonExpr->isOrdinaryOrBitFieldObject()
7219           && RHSExpr->isOrdinaryOrBitFieldObject()
7220           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7221       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7222       if (commonRes.isInvalid())
7223         return ExprError();
7224       commonExpr = commonRes.get();
7225     }
7226
7227     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7228                                                 commonExpr->getType(),
7229                                                 commonExpr->getValueKind(),
7230                                                 commonExpr->getObjectKind(),
7231                                                 commonExpr);
7232     LHSExpr = CondExpr = opaqueValue;
7233   }
7234
7235   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7236   ExprValueKind VK = VK_RValue;
7237   ExprObjectKind OK = OK_Ordinary;
7238   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7239   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
7240                                              VK, OK, QuestionLoc);
7241   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7242       RHS.isInvalid())
7243     return ExprError();
7244
7245   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7246                                 RHS.get());
7247
7248   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7249
7250   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7251                                          Context);
7252
7253   if (!commonExpr)
7254     return new (Context)
7255         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7256                             RHS.get(), result, VK, OK);
7257
7258   return new (Context) BinaryConditionalOperator(
7259       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7260       ColonLoc, result, VK, OK);
7261 }
7262
7263 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7264 // being closely modeled after the C99 spec:-). The odd characteristic of this
7265 // routine is it effectively iqnores the qualifiers on the top level pointee.
7266 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7267 // FIXME: add a couple examples in this comment.
7268 static Sema::AssignConvertType
7269 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7270   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7271   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7272
7273   // get the "pointed to" type (ignoring qualifiers at the top level)
7274   const Type *lhptee, *rhptee;
7275   Qualifiers lhq, rhq;
7276   std::tie(lhptee, lhq) =
7277       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7278   std::tie(rhptee, rhq) =
7279       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7280
7281   Sema::AssignConvertType ConvTy = Sema::Compatible;
7282
7283   // C99 6.5.16.1p1: This following citation is common to constraints
7284   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7285   // qualifiers of the type *pointed to* by the right;
7286
7287   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7288   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7289       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7290     // Ignore lifetime for further calculation.
7291     lhq.removeObjCLifetime();
7292     rhq.removeObjCLifetime();
7293   }
7294
7295   if (!lhq.compatiblyIncludes(rhq)) {
7296     // Treat address-space mismatches as fatal.  TODO: address subspaces
7297     if (!lhq.isAddressSpaceSupersetOf(rhq))
7298       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7299
7300     // It's okay to add or remove GC or lifetime qualifiers when converting to
7301     // and from void*.
7302     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7303                         .compatiblyIncludes(
7304                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7305              && (lhptee->isVoidType() || rhptee->isVoidType()))
7306       ; // keep old
7307
7308     // Treat lifetime mismatches as fatal.
7309     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7310       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7311     
7312     // For GCC/MS compatibility, other qualifier mismatches are treated
7313     // as still compatible in C.
7314     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7315   }
7316
7317   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7318   // incomplete type and the other is a pointer to a qualified or unqualified
7319   // version of void...
7320   if (lhptee->isVoidType()) {
7321     if (rhptee->isIncompleteOrObjectType())
7322       return ConvTy;
7323
7324     // As an extension, we allow cast to/from void* to function pointer.
7325     assert(rhptee->isFunctionType());
7326     return Sema::FunctionVoidPointer;
7327   }
7328
7329   if (rhptee->isVoidType()) {
7330     if (lhptee->isIncompleteOrObjectType())
7331       return ConvTy;
7332
7333     // As an extension, we allow cast to/from void* to function pointer.
7334     assert(lhptee->isFunctionType());
7335     return Sema::FunctionVoidPointer;
7336   }
7337
7338   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7339   // unqualified versions of compatible types, ...
7340   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7341   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7342     // Check if the pointee types are compatible ignoring the sign.
7343     // We explicitly check for char so that we catch "char" vs
7344     // "unsigned char" on systems where "char" is unsigned.
7345     if (lhptee->isCharType())
7346       ltrans = S.Context.UnsignedCharTy;
7347     else if (lhptee->hasSignedIntegerRepresentation())
7348       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7349
7350     if (rhptee->isCharType())
7351       rtrans = S.Context.UnsignedCharTy;
7352     else if (rhptee->hasSignedIntegerRepresentation())
7353       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7354
7355     if (ltrans == rtrans) {
7356       // Types are compatible ignoring the sign. Qualifier incompatibility
7357       // takes priority over sign incompatibility because the sign
7358       // warning can be disabled.
7359       if (ConvTy != Sema::Compatible)
7360         return ConvTy;
7361
7362       return Sema::IncompatiblePointerSign;
7363     }
7364
7365     // If we are a multi-level pointer, it's possible that our issue is simply
7366     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7367     // the eventual target type is the same and the pointers have the same
7368     // level of indirection, this must be the issue.
7369     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7370       do {
7371         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7372         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7373       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7374
7375       if (lhptee == rhptee)
7376         return Sema::IncompatibleNestedPointerQualifiers;
7377     }
7378
7379     // General pointer incompatibility takes priority over qualifiers.
7380     return Sema::IncompatiblePointer;
7381   }
7382   if (!S.getLangOpts().CPlusPlus &&
7383       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7384     return Sema::IncompatiblePointer;
7385   return ConvTy;
7386 }
7387
7388 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7389 /// block pointer types are compatible or whether a block and normal pointer
7390 /// are compatible. It is more restrict than comparing two function pointer
7391 // types.
7392 static Sema::AssignConvertType
7393 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7394                                     QualType RHSType) {
7395   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7396   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7397
7398   QualType lhptee, rhptee;
7399
7400   // get the "pointed to" type (ignoring qualifiers at the top level)
7401   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7402   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7403
7404   // In C++, the types have to match exactly.
7405   if (S.getLangOpts().CPlusPlus)
7406     return Sema::IncompatibleBlockPointer;
7407
7408   Sema::AssignConvertType ConvTy = Sema::Compatible;
7409
7410   // For blocks we enforce that qualifiers are identical.
7411   Qualifiers LQuals = lhptee.getLocalQualifiers();
7412   Qualifiers RQuals = rhptee.getLocalQualifiers();
7413   if (S.getLangOpts().OpenCL) {
7414     LQuals.removeAddressSpace();
7415     RQuals.removeAddressSpace();
7416   }
7417   if (LQuals != RQuals)
7418     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7419
7420   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7421   // assignment.
7422   // The current behavior is similar to C++ lambdas. A block might be
7423   // assigned to a variable iff its return type and parameters are compatible
7424   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7425   // an assignment. Presumably it should behave in way that a function pointer
7426   // assignment does in C, so for each parameter and return type:
7427   //  * CVR and address space of LHS should be a superset of CVR and address
7428   //  space of RHS.
7429   //  * unqualified types should be compatible.
7430   if (S.getLangOpts().OpenCL) {
7431     if (!S.Context.typesAreBlockPointerCompatible(
7432             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7433             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7434       return Sema::IncompatibleBlockPointer;
7435   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7436     return Sema::IncompatibleBlockPointer;
7437
7438   return ConvTy;
7439 }
7440
7441 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7442 /// for assignment compatibility.
7443 static Sema::AssignConvertType
7444 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7445                                    QualType RHSType) {
7446   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7447   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7448
7449   if (LHSType->isObjCBuiltinType()) {
7450     // Class is not compatible with ObjC object pointers.
7451     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7452         !RHSType->isObjCQualifiedClassType())
7453       return Sema::IncompatiblePointer;
7454     return Sema::Compatible;
7455   }
7456   if (RHSType->isObjCBuiltinType()) {
7457     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7458         !LHSType->isObjCQualifiedClassType())
7459       return Sema::IncompatiblePointer;
7460     return Sema::Compatible;
7461   }
7462   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7463   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7464
7465   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7466       // make an exception for id<P>
7467       !LHSType->isObjCQualifiedIdType())
7468     return Sema::CompatiblePointerDiscardsQualifiers;
7469
7470   if (S.Context.typesAreCompatible(LHSType, RHSType))
7471     return Sema::Compatible;
7472   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7473     return Sema::IncompatibleObjCQualifiedId;
7474   return Sema::IncompatiblePointer;
7475 }
7476
7477 Sema::AssignConvertType
7478 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7479                                  QualType LHSType, QualType RHSType) {
7480   // Fake up an opaque expression.  We don't actually care about what
7481   // cast operations are required, so if CheckAssignmentConstraints
7482   // adds casts to this they'll be wasted, but fortunately that doesn't
7483   // usually happen on valid code.
7484   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7485   ExprResult RHSPtr = &RHSExpr;
7486   CastKind K = CK_Invalid;
7487
7488   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7489 }
7490
7491 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7492 /// has code to accommodate several GCC extensions when type checking
7493 /// pointers. Here are some objectionable examples that GCC considers warnings:
7494 ///
7495 ///  int a, *pint;
7496 ///  short *pshort;
7497 ///  struct foo *pfoo;
7498 ///
7499 ///  pint = pshort; // warning: assignment from incompatible pointer type
7500 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7501 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7502 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7503 ///
7504 /// As a result, the code for dealing with pointers is more complex than the
7505 /// C99 spec dictates.
7506 ///
7507 /// Sets 'Kind' for any result kind except Incompatible.
7508 Sema::AssignConvertType
7509 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7510                                  CastKind &Kind, bool ConvertRHS) {
7511   QualType RHSType = RHS.get()->getType();
7512   QualType OrigLHSType = LHSType;
7513
7514   // Get canonical types.  We're not formatting these types, just comparing
7515   // them.
7516   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7517   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7518
7519   // Common case: no conversion required.
7520   if (LHSType == RHSType) {
7521     Kind = CK_NoOp;
7522     return Compatible;
7523   }
7524
7525   // If we have an atomic type, try a non-atomic assignment, then just add an
7526   // atomic qualification step.
7527   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7528     Sema::AssignConvertType result =
7529       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7530     if (result != Compatible)
7531       return result;
7532     if (Kind != CK_NoOp && ConvertRHS)
7533       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7534     Kind = CK_NonAtomicToAtomic;
7535     return Compatible;
7536   }
7537
7538   // If the left-hand side is a reference type, then we are in a
7539   // (rare!) case where we've allowed the use of references in C,
7540   // e.g., as a parameter type in a built-in function. In this case,
7541   // just make sure that the type referenced is compatible with the
7542   // right-hand side type. The caller is responsible for adjusting
7543   // LHSType so that the resulting expression does not have reference
7544   // type.
7545   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7546     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7547       Kind = CK_LValueBitCast;
7548       return Compatible;
7549     }
7550     return Incompatible;
7551   }
7552
7553   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7554   // to the same ExtVector type.
7555   if (LHSType->isExtVectorType()) {
7556     if (RHSType->isExtVectorType())
7557       return Incompatible;
7558     if (RHSType->isArithmeticType()) {
7559       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7560       if (ConvertRHS)
7561         RHS = prepareVectorSplat(LHSType, RHS.get());
7562       Kind = CK_VectorSplat;
7563       return Compatible;
7564     }
7565   }
7566
7567   // Conversions to or from vector type.
7568   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7569     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7570       // Allow assignments of an AltiVec vector type to an equivalent GCC
7571       // vector type and vice versa
7572       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7573         Kind = CK_BitCast;
7574         return Compatible;
7575       }
7576
7577       // If we are allowing lax vector conversions, and LHS and RHS are both
7578       // vectors, the total size only needs to be the same. This is a bitcast;
7579       // no bits are changed but the result type is different.
7580       if (isLaxVectorConversion(RHSType, LHSType)) {
7581         Kind = CK_BitCast;
7582         return IncompatibleVectors;
7583       }
7584     }
7585
7586     // When the RHS comes from another lax conversion (e.g. binops between
7587     // scalars and vectors) the result is canonicalized as a vector. When the
7588     // LHS is also a vector, the lax is allowed by the condition above. Handle
7589     // the case where LHS is a scalar.
7590     if (LHSType->isScalarType()) {
7591       const VectorType *VecType = RHSType->getAs<VectorType>();
7592       if (VecType && VecType->getNumElements() == 1 &&
7593           isLaxVectorConversion(RHSType, LHSType)) {
7594         ExprResult *VecExpr = &RHS;
7595         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7596         Kind = CK_BitCast;
7597         return Compatible;
7598       }
7599     }
7600
7601     return Incompatible;
7602   }
7603
7604   // Diagnose attempts to convert between __float128 and long double where
7605   // such conversions currently can't be handled.
7606   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7607     return Incompatible;
7608
7609   // Arithmetic conversions.
7610   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7611       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7612     if (ConvertRHS)
7613       Kind = PrepareScalarCast(RHS, LHSType);
7614     return Compatible;
7615   }
7616
7617   // Conversions to normal pointers.
7618   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7619     // U* -> T*
7620     if (isa<PointerType>(RHSType)) {
7621       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7622       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7623       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7624       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7625     }
7626
7627     // int -> T*
7628     if (RHSType->isIntegerType()) {
7629       Kind = CK_IntegralToPointer; // FIXME: null?
7630       return IntToPointer;
7631     }
7632
7633     // C pointers are not compatible with ObjC object pointers,
7634     // with two exceptions:
7635     if (isa<ObjCObjectPointerType>(RHSType)) {
7636       //  - conversions to void*
7637       if (LHSPointer->getPointeeType()->isVoidType()) {
7638         Kind = CK_BitCast;
7639         return Compatible;
7640       }
7641
7642       //  - conversions from 'Class' to the redefinition type
7643       if (RHSType->isObjCClassType() &&
7644           Context.hasSameType(LHSType, 
7645                               Context.getObjCClassRedefinitionType())) {
7646         Kind = CK_BitCast;
7647         return Compatible;
7648       }
7649
7650       Kind = CK_BitCast;
7651       return IncompatiblePointer;
7652     }
7653
7654     // U^ -> void*
7655     if (RHSType->getAs<BlockPointerType>()) {
7656       if (LHSPointer->getPointeeType()->isVoidType()) {
7657         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7658         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7659                                   ->getPointeeType()
7660                                   .getAddressSpace();
7661         Kind =
7662             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7663         return Compatible;
7664       }
7665     }
7666
7667     return Incompatible;
7668   }
7669
7670   // Conversions to block pointers.
7671   if (isa<BlockPointerType>(LHSType)) {
7672     // U^ -> T^
7673     if (RHSType->isBlockPointerType()) {
7674       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7675                                 ->getPointeeType()
7676                                 .getAddressSpace();
7677       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7678                                 ->getPointeeType()
7679                                 .getAddressSpace();
7680       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7681       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7682     }
7683
7684     // int or null -> T^
7685     if (RHSType->isIntegerType()) {
7686       Kind = CK_IntegralToPointer; // FIXME: null
7687       return IntToBlockPointer;
7688     }
7689
7690     // id -> T^
7691     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7692       Kind = CK_AnyPointerToBlockPointerCast;
7693       return Compatible;
7694     }
7695
7696     // void* -> T^
7697     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7698       if (RHSPT->getPointeeType()->isVoidType()) {
7699         Kind = CK_AnyPointerToBlockPointerCast;
7700         return Compatible;
7701       }
7702
7703     return Incompatible;
7704   }
7705
7706   // Conversions to Objective-C pointers.
7707   if (isa<ObjCObjectPointerType>(LHSType)) {
7708     // A* -> B*
7709     if (RHSType->isObjCObjectPointerType()) {
7710       Kind = CK_BitCast;
7711       Sema::AssignConvertType result = 
7712         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7713       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7714           result == Compatible && 
7715           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7716         result = IncompatibleObjCWeakRef;
7717       return result;
7718     }
7719
7720     // int or null -> A*
7721     if (RHSType->isIntegerType()) {
7722       Kind = CK_IntegralToPointer; // FIXME: null
7723       return IntToPointer;
7724     }
7725
7726     // In general, C pointers are not compatible with ObjC object pointers,
7727     // with two exceptions:
7728     if (isa<PointerType>(RHSType)) {
7729       Kind = CK_CPointerToObjCPointerCast;
7730
7731       //  - conversions from 'void*'
7732       if (RHSType->isVoidPointerType()) {
7733         return Compatible;
7734       }
7735
7736       //  - conversions to 'Class' from its redefinition type
7737       if (LHSType->isObjCClassType() &&
7738           Context.hasSameType(RHSType, 
7739                               Context.getObjCClassRedefinitionType())) {
7740         return Compatible;
7741       }
7742
7743       return IncompatiblePointer;
7744     }
7745
7746     // Only under strict condition T^ is compatible with an Objective-C pointer.
7747     if (RHSType->isBlockPointerType() && 
7748         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7749       if (ConvertRHS)
7750         maybeExtendBlockObject(RHS);
7751       Kind = CK_BlockPointerToObjCPointerCast;
7752       return Compatible;
7753     }
7754
7755     return Incompatible;
7756   }
7757
7758   // Conversions from pointers that are not covered by the above.
7759   if (isa<PointerType>(RHSType)) {
7760     // T* -> _Bool
7761     if (LHSType == Context.BoolTy) {
7762       Kind = CK_PointerToBoolean;
7763       return Compatible;
7764     }
7765
7766     // T* -> int
7767     if (LHSType->isIntegerType()) {
7768       Kind = CK_PointerToIntegral;
7769       return PointerToInt;
7770     }
7771
7772     return Incompatible;
7773   }
7774
7775   // Conversions from Objective-C pointers that are not covered by the above.
7776   if (isa<ObjCObjectPointerType>(RHSType)) {
7777     // T* -> _Bool
7778     if (LHSType == Context.BoolTy) {
7779       Kind = CK_PointerToBoolean;
7780       return Compatible;
7781     }
7782
7783     // T* -> int
7784     if (LHSType->isIntegerType()) {
7785       Kind = CK_PointerToIntegral;
7786       return PointerToInt;
7787     }
7788
7789     return Incompatible;
7790   }
7791
7792   // struct A -> struct B
7793   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7794     if (Context.typesAreCompatible(LHSType, RHSType)) {
7795       Kind = CK_NoOp;
7796       return Compatible;
7797     }
7798   }
7799
7800   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7801     Kind = CK_IntToOCLSampler;
7802     return Compatible;
7803   }
7804
7805   return Incompatible;
7806 }
7807
7808 /// \brief Constructs a transparent union from an expression that is
7809 /// used to initialize the transparent union.
7810 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7811                                       ExprResult &EResult, QualType UnionType,
7812                                       FieldDecl *Field) {
7813   // Build an initializer list that designates the appropriate member
7814   // of the transparent union.
7815   Expr *E = EResult.get();
7816   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7817                                                    E, SourceLocation());
7818   Initializer->setType(UnionType);
7819   Initializer->setInitializedFieldInUnion(Field);
7820
7821   // Build a compound literal constructing a value of the transparent
7822   // union type from this initializer list.
7823   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7824   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7825                                         VK_RValue, Initializer, false);
7826 }
7827
7828 Sema::AssignConvertType
7829 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7830                                                ExprResult &RHS) {
7831   QualType RHSType = RHS.get()->getType();
7832
7833   // If the ArgType is a Union type, we want to handle a potential
7834   // transparent_union GCC extension.
7835   const RecordType *UT = ArgType->getAsUnionType();
7836   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7837     return Incompatible;
7838
7839   // The field to initialize within the transparent union.
7840   RecordDecl *UD = UT->getDecl();
7841   FieldDecl *InitField = nullptr;
7842   // It's compatible if the expression matches any of the fields.
7843   for (auto *it : UD->fields()) {
7844     if (it->getType()->isPointerType()) {
7845       // If the transparent union contains a pointer type, we allow:
7846       // 1) void pointer
7847       // 2) null pointer constant
7848       if (RHSType->isPointerType())
7849         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7850           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7851           InitField = it;
7852           break;
7853         }
7854
7855       if (RHS.get()->isNullPointerConstant(Context,
7856                                            Expr::NPC_ValueDependentIsNull)) {
7857         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7858                                 CK_NullToPointer);
7859         InitField = it;
7860         break;
7861       }
7862     }
7863
7864     CastKind Kind = CK_Invalid;
7865     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7866           == Compatible) {
7867       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7868       InitField = it;
7869       break;
7870     }
7871   }
7872
7873   if (!InitField)
7874     return Incompatible;
7875
7876   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7877   return Compatible;
7878 }
7879
7880 Sema::AssignConvertType
7881 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7882                                        bool Diagnose,
7883                                        bool DiagnoseCFAudited,
7884                                        bool ConvertRHS) {
7885   // We need to be able to tell the caller whether we diagnosed a problem, if
7886   // they ask us to issue diagnostics.
7887   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7888
7889   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7890   // we can't avoid *all* modifications at the moment, so we need some somewhere
7891   // to put the updated value.
7892   ExprResult LocalRHS = CallerRHS;
7893   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7894
7895   if (getLangOpts().CPlusPlus) {
7896     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7897       // C++ 5.17p3: If the left operand is not of class type, the
7898       // expression is implicitly converted (C++ 4) to the
7899       // cv-unqualified type of the left operand.
7900       QualType RHSType = RHS.get()->getType();
7901       if (Diagnose) {
7902         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7903                                         AA_Assigning);
7904       } else {
7905         ImplicitConversionSequence ICS =
7906             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7907                                   /*SuppressUserConversions=*/false,
7908                                   /*AllowExplicit=*/false,
7909                                   /*InOverloadResolution=*/false,
7910                                   /*CStyle=*/false,
7911                                   /*AllowObjCWritebackConversion=*/false);
7912         if (ICS.isFailure())
7913           return Incompatible;
7914         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7915                                         ICS, AA_Assigning);
7916       }
7917       if (RHS.isInvalid())
7918         return Incompatible;
7919       Sema::AssignConvertType result = Compatible;
7920       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7921           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7922         result = IncompatibleObjCWeakRef;
7923       return result;
7924     }
7925
7926     // FIXME: Currently, we fall through and treat C++ classes like C
7927     // structures.
7928     // FIXME: We also fall through for atomics; not sure what should
7929     // happen there, though.
7930   } else if (RHS.get()->getType() == Context.OverloadTy) {
7931     // As a set of extensions to C, we support overloading on functions. These
7932     // functions need to be resolved here.
7933     DeclAccessPair DAP;
7934     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7935             RHS.get(), LHSType, /*Complain=*/false, DAP))
7936       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7937     else
7938       return Incompatible;
7939   }
7940
7941   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7942   // a null pointer constant.
7943   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7944        LHSType->isBlockPointerType()) &&
7945       RHS.get()->isNullPointerConstant(Context,
7946                                        Expr::NPC_ValueDependentIsNull)) {
7947     if (Diagnose || ConvertRHS) {
7948       CastKind Kind;
7949       CXXCastPath Path;
7950       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7951                              /*IgnoreBaseAccess=*/false, Diagnose);
7952       if (ConvertRHS)
7953         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7954     }
7955     return Compatible;
7956   }
7957
7958   // This check seems unnatural, however it is necessary to ensure the proper
7959   // conversion of functions/arrays. If the conversion were done for all
7960   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7961   // expressions that suppress this implicit conversion (&, sizeof).
7962   //
7963   // Suppress this for references: C++ 8.5.3p5.
7964   if (!LHSType->isReferenceType()) {
7965     // FIXME: We potentially allocate here even if ConvertRHS is false.
7966     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7967     if (RHS.isInvalid())
7968       return Incompatible;
7969   }
7970
7971   Expr *PRE = RHS.get()->IgnoreParenCasts();
7972   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7973     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7974     if (PDecl && !PDecl->hasDefinition()) {
7975       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7976       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7977     }
7978   }
7979   
7980   CastKind Kind = CK_Invalid;
7981   Sema::AssignConvertType result =
7982     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7983
7984   // C99 6.5.16.1p2: The value of the right operand is converted to the
7985   // type of the assignment expression.
7986   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7987   // so that we can use references in built-in functions even in C.
7988   // The getNonReferenceType() call makes sure that the resulting expression
7989   // does not have reference type.
7990   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7991     QualType Ty = LHSType.getNonLValueExprType(Context);
7992     Expr *E = RHS.get();
7993
7994     // Check for various Objective-C errors. If we are not reporting
7995     // diagnostics and just checking for errors, e.g., during overload
7996     // resolution, return Incompatible to indicate the failure.
7997     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7998         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7999                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8000       if (!Diagnose)
8001         return Incompatible;
8002     }
8003     if (getLangOpts().ObjC1 &&
8004         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8005                                            E->getType(), E, Diagnose) ||
8006          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8007       if (!Diagnose)
8008         return Incompatible;
8009       // Replace the expression with a corrected version and continue so we
8010       // can find further errors.
8011       RHS = E;
8012       return Compatible;
8013     }
8014     
8015     if (ConvertRHS)
8016       RHS = ImpCastExprToType(E, Ty, Kind);
8017   }
8018   return result;
8019 }
8020
8021 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8022                                ExprResult &RHS) {
8023   Diag(Loc, diag::err_typecheck_invalid_operands)
8024     << LHS.get()->getType() << RHS.get()->getType()
8025     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8026   return QualType();
8027 }
8028
8029 /// Try to convert a value of non-vector type to a vector type by converting
8030 /// the type to the element type of the vector and then performing a splat.
8031 /// If the language is OpenCL, we only use conversions that promote scalar
8032 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8033 /// for float->int.
8034 ///
8035 /// \param scalar - if non-null, actually perform the conversions
8036 /// \return true if the operation fails (but without diagnosing the failure)
8037 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8038                                      QualType scalarTy,
8039                                      QualType vectorEltTy,
8040                                      QualType vectorTy) {
8041   // The conversion to apply to the scalar before splatting it,
8042   // if necessary.
8043   CastKind scalarCast = CK_Invalid;
8044   
8045   if (vectorEltTy->isIntegralType(S.Context)) {
8046     if (!scalarTy->isIntegralType(S.Context))
8047       return true;
8048     if (S.getLangOpts().OpenCL &&
8049         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8050       return true;
8051     scalarCast = CK_IntegralCast;
8052   } else if (vectorEltTy->isRealFloatingType()) {
8053     if (scalarTy->isRealFloatingType()) {
8054       if (S.getLangOpts().OpenCL &&
8055           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8056         return true;
8057       scalarCast = CK_FloatingCast;
8058     }
8059     else if (scalarTy->isIntegralType(S.Context))
8060       scalarCast = CK_IntegralToFloating;
8061     else
8062       return true;
8063   } else {
8064     return true;
8065   }
8066
8067   // Adjust scalar if desired.
8068   if (scalar) {
8069     if (scalarCast != CK_Invalid)
8070       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8071     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8072   }
8073   return false;
8074 }
8075
8076 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8077                                    SourceLocation Loc, bool IsCompAssign,
8078                                    bool AllowBothBool,
8079                                    bool AllowBoolConversions) {
8080   if (!IsCompAssign) {
8081     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8082     if (LHS.isInvalid())
8083       return QualType();
8084   }
8085   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8086   if (RHS.isInvalid())
8087     return QualType();
8088
8089   // For conversion purposes, we ignore any qualifiers.
8090   // For example, "const float" and "float" are equivalent.
8091   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8092   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8093
8094   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8095   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8096   assert(LHSVecType || RHSVecType);
8097
8098   // AltiVec-style "vector bool op vector bool" combinations are allowed
8099   // for some operators but not others.
8100   if (!AllowBothBool &&
8101       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8102       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8103     return InvalidOperands(Loc, LHS, RHS);
8104
8105   // If the vector types are identical, return.
8106   if (Context.hasSameType(LHSType, RHSType))
8107     return LHSType;
8108
8109   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8110   if (LHSVecType && RHSVecType &&
8111       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8112     if (isa<ExtVectorType>(LHSVecType)) {
8113       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8114       return LHSType;
8115     }
8116
8117     if (!IsCompAssign)
8118       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8119     return RHSType;
8120   }
8121
8122   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8123   // can be mixed, with the result being the non-bool type.  The non-bool
8124   // operand must have integer element type.
8125   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8126       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8127       (Context.getTypeSize(LHSVecType->getElementType()) ==
8128        Context.getTypeSize(RHSVecType->getElementType()))) {
8129     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8130         LHSVecType->getElementType()->isIntegerType() &&
8131         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8132       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8133       return LHSType;
8134     }
8135     if (!IsCompAssign &&
8136         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8137         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8138         RHSVecType->getElementType()->isIntegerType()) {
8139       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8140       return RHSType;
8141     }
8142   }
8143
8144   // If there's an ext-vector type and a scalar, try to convert the scalar to
8145   // the vector element type and splat.
8146   // FIXME: this should also work for regular vector types as supported in GCC.
8147   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8148     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8149                                   LHSVecType->getElementType(), LHSType))
8150       return LHSType;
8151   }
8152   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8153     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8154                                   LHSType, RHSVecType->getElementType(),
8155                                   RHSType))
8156       return RHSType;
8157   }
8158
8159   // FIXME: The code below also handles conversion between vectors and
8160   // non-scalars, we should break this down into fine grained specific checks
8161   // and emit proper diagnostics.
8162   QualType VecType = LHSVecType ? LHSType : RHSType;
8163   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8164   QualType OtherType = LHSVecType ? RHSType : LHSType;
8165   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8166   if (isLaxVectorConversion(OtherType, VecType)) {
8167     // If we're allowing lax vector conversions, only the total (data) size
8168     // needs to be the same. For non compound assignment, if one of the types is
8169     // scalar, the result is always the vector type.
8170     if (!IsCompAssign) {
8171       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8172       return VecType;
8173     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8174     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8175     // type. Note that this is already done by non-compound assignments in
8176     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8177     // <1 x T> -> T. The result is also a vector type.
8178     } else if (OtherType->isExtVectorType() ||
8179                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8180       ExprResult *RHSExpr = &RHS;
8181       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8182       return VecType;
8183     }
8184   }
8185
8186   // Okay, the expression is invalid.
8187
8188   // If there's a non-vector, non-real operand, diagnose that.
8189   if ((!RHSVecType && !RHSType->isRealType()) ||
8190       (!LHSVecType && !LHSType->isRealType())) {
8191     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8192       << LHSType << RHSType
8193       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8194     return QualType();
8195   }
8196
8197   // OpenCL V1.1 6.2.6.p1:
8198   // If the operands are of more than one vector type, then an error shall
8199   // occur. Implicit conversions between vector types are not permitted, per
8200   // section 6.2.1.
8201   if (getLangOpts().OpenCL &&
8202       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8203       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8204     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8205                                                            << RHSType;
8206     return QualType();
8207   }
8208
8209   // Otherwise, use the generic diagnostic.
8210   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8211     << LHSType << RHSType
8212     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8213   return QualType();
8214 }
8215
8216 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8217 // expression.  These are mainly cases where the null pointer is used as an
8218 // integer instead of a pointer.
8219 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8220                                 SourceLocation Loc, bool IsCompare) {
8221   // The canonical way to check for a GNU null is with isNullPointerConstant,
8222   // but we use a bit of a hack here for speed; this is a relatively
8223   // hot path, and isNullPointerConstant is slow.
8224   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8225   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8226
8227   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8228
8229   // Avoid analyzing cases where the result will either be invalid (and
8230   // diagnosed as such) or entirely valid and not something to warn about.
8231   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8232       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8233     return;
8234
8235   // Comparison operations would not make sense with a null pointer no matter
8236   // what the other expression is.
8237   if (!IsCompare) {
8238     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8239         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8240         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8241     return;
8242   }
8243
8244   // The rest of the operations only make sense with a null pointer
8245   // if the other expression is a pointer.
8246   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8247       NonNullType->canDecayToPointerType())
8248     return;
8249
8250   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8251       << LHSNull /* LHS is NULL */ << NonNullType
8252       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8253 }
8254
8255 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8256                                                ExprResult &RHS,
8257                                                SourceLocation Loc, bool IsDiv) {
8258   // Check for division/remainder by zero.
8259   llvm::APSInt RHSValue;
8260   if (!RHS.get()->isValueDependent() &&
8261       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8262     S.DiagRuntimeBehavior(Loc, RHS.get(),
8263                           S.PDiag(diag::warn_remainder_division_by_zero)
8264                             << IsDiv << RHS.get()->getSourceRange());
8265 }
8266
8267 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8268                                            SourceLocation Loc,
8269                                            bool IsCompAssign, bool IsDiv) {
8270   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8271
8272   if (LHS.get()->getType()->isVectorType() ||
8273       RHS.get()->getType()->isVectorType())
8274     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8275                                /*AllowBothBool*/getLangOpts().AltiVec,
8276                                /*AllowBoolConversions*/false);
8277
8278   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8279   if (LHS.isInvalid() || RHS.isInvalid())
8280     return QualType();
8281
8282
8283   if (compType.isNull() || !compType->isArithmeticType())
8284     return InvalidOperands(Loc, LHS, RHS);
8285   if (IsDiv)
8286     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8287   return compType;
8288 }
8289
8290 QualType Sema::CheckRemainderOperands(
8291   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8292   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8293
8294   if (LHS.get()->getType()->isVectorType() ||
8295       RHS.get()->getType()->isVectorType()) {
8296     if (LHS.get()->getType()->hasIntegerRepresentation() && 
8297         RHS.get()->getType()->hasIntegerRepresentation())
8298       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8299                                  /*AllowBothBool*/getLangOpts().AltiVec,
8300                                  /*AllowBoolConversions*/false);
8301     return InvalidOperands(Loc, LHS, RHS);
8302   }
8303
8304   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8305   if (LHS.isInvalid() || RHS.isInvalid())
8306     return QualType();
8307
8308   if (compType.isNull() || !compType->isIntegerType())
8309     return InvalidOperands(Loc, LHS, RHS);
8310   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8311   return compType;
8312 }
8313
8314 /// \brief Diagnose invalid arithmetic on two void pointers.
8315 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8316                                                 Expr *LHSExpr, Expr *RHSExpr) {
8317   S.Diag(Loc, S.getLangOpts().CPlusPlus
8318                 ? diag::err_typecheck_pointer_arith_void_type
8319                 : diag::ext_gnu_void_ptr)
8320     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8321                             << RHSExpr->getSourceRange();
8322 }
8323
8324 /// \brief Diagnose invalid arithmetic on a void pointer.
8325 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8326                                             Expr *Pointer) {
8327   S.Diag(Loc, S.getLangOpts().CPlusPlus
8328                 ? diag::err_typecheck_pointer_arith_void_type
8329                 : diag::ext_gnu_void_ptr)
8330     << 0 /* one pointer */ << Pointer->getSourceRange();
8331 }
8332
8333 /// \brief Diagnose invalid arithmetic on two function pointers.
8334 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8335                                                     Expr *LHS, Expr *RHS) {
8336   assert(LHS->getType()->isAnyPointerType());
8337   assert(RHS->getType()->isAnyPointerType());
8338   S.Diag(Loc, S.getLangOpts().CPlusPlus
8339                 ? diag::err_typecheck_pointer_arith_function_type
8340                 : diag::ext_gnu_ptr_func_arith)
8341     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8342     // We only show the second type if it differs from the first.
8343     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8344                                                    RHS->getType())
8345     << RHS->getType()->getPointeeType()
8346     << LHS->getSourceRange() << RHS->getSourceRange();
8347 }
8348
8349 /// \brief Diagnose invalid arithmetic on a function pointer.
8350 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8351                                                 Expr *Pointer) {
8352   assert(Pointer->getType()->isAnyPointerType());
8353   S.Diag(Loc, S.getLangOpts().CPlusPlus
8354                 ? diag::err_typecheck_pointer_arith_function_type
8355                 : diag::ext_gnu_ptr_func_arith)
8356     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8357     << 0 /* one pointer, so only one type */
8358     << Pointer->getSourceRange();
8359 }
8360
8361 /// \brief Emit error if Operand is incomplete pointer type
8362 ///
8363 /// \returns True if pointer has incomplete type
8364 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8365                                                  Expr *Operand) {
8366   QualType ResType = Operand->getType();
8367   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8368     ResType = ResAtomicType->getValueType();
8369
8370   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8371   QualType PointeeTy = ResType->getPointeeType();
8372   return S.RequireCompleteType(Loc, PointeeTy,
8373                                diag::err_typecheck_arithmetic_incomplete_type,
8374                                PointeeTy, Operand->getSourceRange());
8375 }
8376
8377 /// \brief Check the validity of an arithmetic pointer operand.
8378 ///
8379 /// If the operand has pointer type, this code will check for pointer types
8380 /// which are invalid in arithmetic operations. These will be diagnosed
8381 /// appropriately, including whether or not the use is supported as an
8382 /// extension.
8383 ///
8384 /// \returns True when the operand is valid to use (even if as an extension).
8385 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8386                                             Expr *Operand) {
8387   QualType ResType = Operand->getType();
8388   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8389     ResType = ResAtomicType->getValueType();
8390
8391   if (!ResType->isAnyPointerType()) return true;
8392
8393   QualType PointeeTy = ResType->getPointeeType();
8394   if (PointeeTy->isVoidType()) {
8395     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8396     return !S.getLangOpts().CPlusPlus;
8397   }
8398   if (PointeeTy->isFunctionType()) {
8399     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8400     return !S.getLangOpts().CPlusPlus;
8401   }
8402
8403   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8404
8405   return true;
8406 }
8407
8408 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8409 /// operands.
8410 ///
8411 /// This routine will diagnose any invalid arithmetic on pointer operands much
8412 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8413 /// for emitting a single diagnostic even for operations where both LHS and RHS
8414 /// are (potentially problematic) pointers.
8415 ///
8416 /// \returns True when the operand is valid to use (even if as an extension).
8417 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8418                                                 Expr *LHSExpr, Expr *RHSExpr) {
8419   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8420   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8421   if (!isLHSPointer && !isRHSPointer) return true;
8422
8423   QualType LHSPointeeTy, RHSPointeeTy;
8424   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8425   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8426
8427   // if both are pointers check if operation is valid wrt address spaces
8428   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8429     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8430     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8431     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8432       S.Diag(Loc,
8433              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8434           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8435           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8436       return false;
8437     }
8438   }
8439
8440   // Check for arithmetic on pointers to incomplete types.
8441   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8442   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8443   if (isLHSVoidPtr || isRHSVoidPtr) {
8444     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8445     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8446     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8447
8448     return !S.getLangOpts().CPlusPlus;
8449   }
8450
8451   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8452   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8453   if (isLHSFuncPtr || isRHSFuncPtr) {
8454     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8455     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8456                                                                 RHSExpr);
8457     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8458
8459     return !S.getLangOpts().CPlusPlus;
8460   }
8461
8462   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8463     return false;
8464   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8465     return false;
8466
8467   return true;
8468 }
8469
8470 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8471 /// literal.
8472 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8473                                   Expr *LHSExpr, Expr *RHSExpr) {
8474   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8475   Expr* IndexExpr = RHSExpr;
8476   if (!StrExpr) {
8477     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8478     IndexExpr = LHSExpr;
8479   }
8480
8481   bool IsStringPlusInt = StrExpr &&
8482       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8483   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8484     return;
8485
8486   llvm::APSInt index;
8487   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8488     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8489     if (index.isNonNegative() &&
8490         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8491                               index.isUnsigned()))
8492       return;
8493   }
8494
8495   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8496   Self.Diag(OpLoc, diag::warn_string_plus_int)
8497       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8498
8499   // Only print a fixit for "str" + int, not for int + "str".
8500   if (IndexExpr == RHSExpr) {
8501     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8502     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8503         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8504         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8505         << FixItHint::CreateInsertion(EndLoc, "]");
8506   } else
8507     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8508 }
8509
8510 /// \brief Emit a warning when adding a char literal to a string.
8511 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8512                                    Expr *LHSExpr, Expr *RHSExpr) {
8513   const Expr *StringRefExpr = LHSExpr;
8514   const CharacterLiteral *CharExpr =
8515       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8516
8517   if (!CharExpr) {
8518     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8519     StringRefExpr = RHSExpr;
8520   }
8521
8522   if (!CharExpr || !StringRefExpr)
8523     return;
8524
8525   const QualType StringType = StringRefExpr->getType();
8526
8527   // Return if not a PointerType.
8528   if (!StringType->isAnyPointerType())
8529     return;
8530
8531   // Return if not a CharacterType.
8532   if (!StringType->getPointeeType()->isAnyCharacterType())
8533     return;
8534
8535   ASTContext &Ctx = Self.getASTContext();
8536   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8537
8538   const QualType CharType = CharExpr->getType();
8539   if (!CharType->isAnyCharacterType() &&
8540       CharType->isIntegerType() &&
8541       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8542     Self.Diag(OpLoc, diag::warn_string_plus_char)
8543         << DiagRange << Ctx.CharTy;
8544   } else {
8545     Self.Diag(OpLoc, diag::warn_string_plus_char)
8546         << DiagRange << CharExpr->getType();
8547   }
8548
8549   // Only print a fixit for str + char, not for char + str.
8550   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8551     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8552     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8553         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8554         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8555         << FixItHint::CreateInsertion(EndLoc, "]");
8556   } else {
8557     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8558   }
8559 }
8560
8561 /// \brief Emit error when two pointers are incompatible.
8562 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8563                                            Expr *LHSExpr, Expr *RHSExpr) {
8564   assert(LHSExpr->getType()->isAnyPointerType());
8565   assert(RHSExpr->getType()->isAnyPointerType());
8566   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8567     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8568     << RHSExpr->getSourceRange();
8569 }
8570
8571 // C99 6.5.6
8572 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8573                                      SourceLocation Loc, BinaryOperatorKind Opc,
8574                                      QualType* CompLHSTy) {
8575   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8576
8577   if (LHS.get()->getType()->isVectorType() ||
8578       RHS.get()->getType()->isVectorType()) {
8579     QualType compType = CheckVectorOperands(
8580         LHS, RHS, Loc, CompLHSTy,
8581         /*AllowBothBool*/getLangOpts().AltiVec,
8582         /*AllowBoolConversions*/getLangOpts().ZVector);
8583     if (CompLHSTy) *CompLHSTy = compType;
8584     return compType;
8585   }
8586
8587   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8588   if (LHS.isInvalid() || RHS.isInvalid())
8589     return QualType();
8590
8591   // Diagnose "string literal" '+' int and string '+' "char literal".
8592   if (Opc == BO_Add) {
8593     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8594     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8595   }
8596
8597   // handle the common case first (both operands are arithmetic).
8598   if (!compType.isNull() && compType->isArithmeticType()) {
8599     if (CompLHSTy) *CompLHSTy = compType;
8600     return compType;
8601   }
8602
8603   // Type-checking.  Ultimately the pointer's going to be in PExp;
8604   // note that we bias towards the LHS being the pointer.
8605   Expr *PExp = LHS.get(), *IExp = RHS.get();
8606
8607   bool isObjCPointer;
8608   if (PExp->getType()->isPointerType()) {
8609     isObjCPointer = false;
8610   } else if (PExp->getType()->isObjCObjectPointerType()) {
8611     isObjCPointer = true;
8612   } else {
8613     std::swap(PExp, IExp);
8614     if (PExp->getType()->isPointerType()) {
8615       isObjCPointer = false;
8616     } else if (PExp->getType()->isObjCObjectPointerType()) {
8617       isObjCPointer = true;
8618     } else {
8619       return InvalidOperands(Loc, LHS, RHS);
8620     }
8621   }
8622   assert(PExp->getType()->isAnyPointerType());
8623
8624   if (!IExp->getType()->isIntegerType())
8625     return InvalidOperands(Loc, LHS, RHS);
8626
8627   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8628     return QualType();
8629
8630   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8631     return QualType();
8632
8633   // Check array bounds for pointer arithemtic
8634   CheckArrayAccess(PExp, IExp);
8635
8636   if (CompLHSTy) {
8637     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8638     if (LHSTy.isNull()) {
8639       LHSTy = LHS.get()->getType();
8640       if (LHSTy->isPromotableIntegerType())
8641         LHSTy = Context.getPromotedIntegerType(LHSTy);
8642     }
8643     *CompLHSTy = LHSTy;
8644   }
8645
8646   return PExp->getType();
8647 }
8648
8649 // C99 6.5.6
8650 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8651                                         SourceLocation Loc,
8652                                         QualType* CompLHSTy) {
8653   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8654
8655   if (LHS.get()->getType()->isVectorType() ||
8656       RHS.get()->getType()->isVectorType()) {
8657     QualType compType = CheckVectorOperands(
8658         LHS, RHS, Loc, CompLHSTy,
8659         /*AllowBothBool*/getLangOpts().AltiVec,
8660         /*AllowBoolConversions*/getLangOpts().ZVector);
8661     if (CompLHSTy) *CompLHSTy = compType;
8662     return compType;
8663   }
8664
8665   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8666   if (LHS.isInvalid() || RHS.isInvalid())
8667     return QualType();
8668
8669   // Enforce type constraints: C99 6.5.6p3.
8670
8671   // Handle the common case first (both operands are arithmetic).
8672   if (!compType.isNull() && compType->isArithmeticType()) {
8673     if (CompLHSTy) *CompLHSTy = compType;
8674     return compType;
8675   }
8676
8677   // Either ptr - int   or   ptr - ptr.
8678   if (LHS.get()->getType()->isAnyPointerType()) {
8679     QualType lpointee = LHS.get()->getType()->getPointeeType();
8680
8681     // Diagnose bad cases where we step over interface counts.
8682     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8683         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8684       return QualType();
8685
8686     // The result type of a pointer-int computation is the pointer type.
8687     if (RHS.get()->getType()->isIntegerType()) {
8688       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8689         return QualType();
8690
8691       // Check array bounds for pointer arithemtic
8692       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8693                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8694
8695       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8696       return LHS.get()->getType();
8697     }
8698
8699     // Handle pointer-pointer subtractions.
8700     if (const PointerType *RHSPTy
8701           = RHS.get()->getType()->getAs<PointerType>()) {
8702       QualType rpointee = RHSPTy->getPointeeType();
8703
8704       if (getLangOpts().CPlusPlus) {
8705         // Pointee types must be the same: C++ [expr.add]
8706         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8707           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8708         }
8709       } else {
8710         // Pointee types must be compatible C99 6.5.6p3
8711         if (!Context.typesAreCompatible(
8712                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8713                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8714           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8715           return QualType();
8716         }
8717       }
8718
8719       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8720                                                LHS.get(), RHS.get()))
8721         return QualType();
8722
8723       // The pointee type may have zero size.  As an extension, a structure or
8724       // union may have zero size or an array may have zero length.  In this
8725       // case subtraction does not make sense.
8726       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8727         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8728         if (ElementSize.isZero()) {
8729           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8730             << rpointee.getUnqualifiedType()
8731             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8732         }
8733       }
8734
8735       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8736       return Context.getPointerDiffType();
8737     }
8738   }
8739
8740   return InvalidOperands(Loc, LHS, RHS);
8741 }
8742
8743 static bool isScopedEnumerationType(QualType T) {
8744   if (const EnumType *ET = T->getAs<EnumType>())
8745     return ET->getDecl()->isScoped();
8746   return false;
8747 }
8748
8749 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8750                                    SourceLocation Loc, BinaryOperatorKind Opc,
8751                                    QualType LHSType) {
8752   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8753   // so skip remaining warnings as we don't want to modify values within Sema.
8754   if (S.getLangOpts().OpenCL)
8755     return;
8756
8757   llvm::APSInt Right;
8758   // Check right/shifter operand
8759   if (RHS.get()->isValueDependent() ||
8760       !RHS.get()->EvaluateAsInt(Right, S.Context))
8761     return;
8762
8763   if (Right.isNegative()) {
8764     S.DiagRuntimeBehavior(Loc, RHS.get(),
8765                           S.PDiag(diag::warn_shift_negative)
8766                             << RHS.get()->getSourceRange());
8767     return;
8768   }
8769   llvm::APInt LeftBits(Right.getBitWidth(),
8770                        S.Context.getTypeSize(LHS.get()->getType()));
8771   if (Right.uge(LeftBits)) {
8772     S.DiagRuntimeBehavior(Loc, RHS.get(),
8773                           S.PDiag(diag::warn_shift_gt_typewidth)
8774                             << RHS.get()->getSourceRange());
8775     return;
8776   }
8777   if (Opc != BO_Shl)
8778     return;
8779
8780   // When left shifting an ICE which is signed, we can check for overflow which
8781   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8782   // integers have defined behavior modulo one more than the maximum value
8783   // representable in the result type, so never warn for those.
8784   llvm::APSInt Left;
8785   if (LHS.get()->isValueDependent() ||
8786       LHSType->hasUnsignedIntegerRepresentation() ||
8787       !LHS.get()->EvaluateAsInt(Left, S.Context))
8788     return;
8789
8790   // If LHS does not have a signed type and non-negative value
8791   // then, the behavior is undefined. Warn about it.
8792   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8793     S.DiagRuntimeBehavior(Loc, LHS.get(),
8794                           S.PDiag(diag::warn_shift_lhs_negative)
8795                             << LHS.get()->getSourceRange());
8796     return;
8797   }
8798
8799   llvm::APInt ResultBits =
8800       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8801   if (LeftBits.uge(ResultBits))
8802     return;
8803   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8804   Result = Result.shl(Right);
8805
8806   // Print the bit representation of the signed integer as an unsigned
8807   // hexadecimal number.
8808   SmallString<40> HexResult;
8809   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8810
8811   // If we are only missing a sign bit, this is less likely to result in actual
8812   // bugs -- if the result is cast back to an unsigned type, it will have the
8813   // expected value. Thus we place this behind a different warning that can be
8814   // turned off separately if needed.
8815   if (LeftBits == ResultBits - 1) {
8816     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8817         << HexResult << LHSType
8818         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8819     return;
8820   }
8821
8822   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8823     << HexResult.str() << Result.getMinSignedBits() << LHSType
8824     << Left.getBitWidth() << LHS.get()->getSourceRange()
8825     << RHS.get()->getSourceRange();
8826 }
8827
8828 /// \brief Return the resulting type when a vector is shifted
8829 ///        by a scalar or vector shift amount.
8830 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8831                                  SourceLocation Loc, bool IsCompAssign) {
8832   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8833   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8834       !LHS.get()->getType()->isVectorType()) {
8835     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8836       << RHS.get()->getType() << LHS.get()->getType()
8837       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8838     return QualType();
8839   }
8840
8841   if (!IsCompAssign) {
8842     LHS = S.UsualUnaryConversions(LHS.get());
8843     if (LHS.isInvalid()) return QualType();
8844   }
8845
8846   RHS = S.UsualUnaryConversions(RHS.get());
8847   if (RHS.isInvalid()) return QualType();
8848
8849   QualType LHSType = LHS.get()->getType();
8850   // Note that LHS might be a scalar because the routine calls not only in
8851   // OpenCL case.
8852   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8853   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8854
8855   // Note that RHS might not be a vector.
8856   QualType RHSType = RHS.get()->getType();
8857   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8858   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8859
8860   // The operands need to be integers.
8861   if (!LHSEleType->isIntegerType()) {
8862     S.Diag(Loc, diag::err_typecheck_expect_int)
8863       << LHS.get()->getType() << LHS.get()->getSourceRange();
8864     return QualType();
8865   }
8866
8867   if (!RHSEleType->isIntegerType()) {
8868     S.Diag(Loc, diag::err_typecheck_expect_int)
8869       << RHS.get()->getType() << RHS.get()->getSourceRange();
8870     return QualType();
8871   }
8872
8873   if (!LHSVecTy) {
8874     assert(RHSVecTy);
8875     if (IsCompAssign)
8876       return RHSType;
8877     if (LHSEleType != RHSEleType) {
8878       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8879       LHSEleType = RHSEleType;
8880     }
8881     QualType VecTy =
8882         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8883     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8884     LHSType = VecTy;
8885   } else if (RHSVecTy) {
8886     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8887     // are applied component-wise. So if RHS is a vector, then ensure
8888     // that the number of elements is the same as LHS...
8889     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8890       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8891         << LHS.get()->getType() << RHS.get()->getType()
8892         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8893       return QualType();
8894     }
8895     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8896       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8897       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8898       if (LHSBT != RHSBT &&
8899           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8900         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8901             << LHS.get()->getType() << RHS.get()->getType()
8902             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8903       }
8904     }
8905   } else {
8906     // ...else expand RHS to match the number of elements in LHS.
8907     QualType VecTy =
8908       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8909     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8910   }
8911
8912   return LHSType;
8913 }
8914
8915 // C99 6.5.7
8916 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8917                                   SourceLocation Loc, BinaryOperatorKind Opc,
8918                                   bool IsCompAssign) {
8919   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8920
8921   // Vector shifts promote their scalar inputs to vector type.
8922   if (LHS.get()->getType()->isVectorType() ||
8923       RHS.get()->getType()->isVectorType()) {
8924     if (LangOpts.ZVector) {
8925       // The shift operators for the z vector extensions work basically
8926       // like general shifts, except that neither the LHS nor the RHS is
8927       // allowed to be a "vector bool".
8928       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8929         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8930           return InvalidOperands(Loc, LHS, RHS);
8931       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8932         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8933           return InvalidOperands(Loc, LHS, RHS);
8934     }
8935     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8936   }
8937
8938   // Shifts don't perform usual arithmetic conversions, they just do integer
8939   // promotions on each operand. C99 6.5.7p3
8940
8941   // For the LHS, do usual unary conversions, but then reset them away
8942   // if this is a compound assignment.
8943   ExprResult OldLHS = LHS;
8944   LHS = UsualUnaryConversions(LHS.get());
8945   if (LHS.isInvalid())
8946     return QualType();
8947   QualType LHSType = LHS.get()->getType();
8948   if (IsCompAssign) LHS = OldLHS;
8949
8950   // The RHS is simpler.
8951   RHS = UsualUnaryConversions(RHS.get());
8952   if (RHS.isInvalid())
8953     return QualType();
8954   QualType RHSType = RHS.get()->getType();
8955
8956   // C99 6.5.7p2: Each of the operands shall have integer type.
8957   if (!LHSType->hasIntegerRepresentation() ||
8958       !RHSType->hasIntegerRepresentation())
8959     return InvalidOperands(Loc, LHS, RHS);
8960
8961   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8962   // hasIntegerRepresentation() above instead of this.
8963   if (isScopedEnumerationType(LHSType) ||
8964       isScopedEnumerationType(RHSType)) {
8965     return InvalidOperands(Loc, LHS, RHS);
8966   }
8967   // Sanity-check shift operands
8968   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8969
8970   // "The type of the result is that of the promoted left operand."
8971   return LHSType;
8972 }
8973
8974 static bool IsWithinTemplateSpecialization(Decl *D) {
8975   if (DeclContext *DC = D->getDeclContext()) {
8976     if (isa<ClassTemplateSpecializationDecl>(DC))
8977       return true;
8978     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8979       return FD->isFunctionTemplateSpecialization();
8980   }
8981   return false;
8982 }
8983
8984 /// If two different enums are compared, raise a warning.
8985 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8986                                 Expr *RHS) {
8987   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8988   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8989
8990   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8991   if (!LHSEnumType)
8992     return;
8993   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8994   if (!RHSEnumType)
8995     return;
8996
8997   // Ignore anonymous enums.
8998   if (!LHSEnumType->getDecl()->getIdentifier())
8999     return;
9000   if (!RHSEnumType->getDecl()->getIdentifier())
9001     return;
9002
9003   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9004     return;
9005
9006   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9007       << LHSStrippedType << RHSStrippedType
9008       << LHS->getSourceRange() << RHS->getSourceRange();
9009 }
9010
9011 /// \brief Diagnose bad pointer comparisons.
9012 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9013                                               ExprResult &LHS, ExprResult &RHS,
9014                                               bool IsError) {
9015   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9016                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9017     << LHS.get()->getType() << RHS.get()->getType()
9018     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9019 }
9020
9021 /// \brief Returns false if the pointers are converted to a composite type,
9022 /// true otherwise.
9023 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9024                                            ExprResult &LHS, ExprResult &RHS) {
9025   // C++ [expr.rel]p2:
9026   //   [...] Pointer conversions (4.10) and qualification
9027   //   conversions (4.4) are performed on pointer operands (or on
9028   //   a pointer operand and a null pointer constant) to bring
9029   //   them to their composite pointer type. [...]
9030   //
9031   // C++ [expr.eq]p1 uses the same notion for (in)equality
9032   // comparisons of pointers.
9033
9034   QualType LHSType = LHS.get()->getType();
9035   QualType RHSType = RHS.get()->getType();
9036   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9037          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9038
9039   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9040   if (T.isNull()) {
9041     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9042         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9043       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9044     else
9045       S.InvalidOperands(Loc, LHS, RHS);
9046     return true;
9047   }
9048
9049   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9050   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9051   return false;
9052 }
9053
9054 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9055                                                     ExprResult &LHS,
9056                                                     ExprResult &RHS,
9057                                                     bool IsError) {
9058   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9059                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9060     << LHS.get()->getType() << RHS.get()->getType()
9061     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9062 }
9063
9064 static bool isObjCObjectLiteral(ExprResult &E) {
9065   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9066   case Stmt::ObjCArrayLiteralClass:
9067   case Stmt::ObjCDictionaryLiteralClass:
9068   case Stmt::ObjCStringLiteralClass:
9069   case Stmt::ObjCBoxedExprClass:
9070     return true;
9071   default:
9072     // Note that ObjCBoolLiteral is NOT an object literal!
9073     return false;
9074   }
9075 }
9076
9077 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9078   const ObjCObjectPointerType *Type =
9079     LHS->getType()->getAs<ObjCObjectPointerType>();
9080
9081   // If this is not actually an Objective-C object, bail out.
9082   if (!Type)
9083     return false;
9084
9085   // Get the LHS object's interface type.
9086   QualType InterfaceType = Type->getPointeeType();
9087
9088   // If the RHS isn't an Objective-C object, bail out.
9089   if (!RHS->getType()->isObjCObjectPointerType())
9090     return false;
9091
9092   // Try to find the -isEqual: method.
9093   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9094   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9095                                                       InterfaceType,
9096                                                       /*instance=*/true);
9097   if (!Method) {
9098     if (Type->isObjCIdType()) {
9099       // For 'id', just check the global pool.
9100       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9101                                                   /*receiverId=*/true);
9102     } else {
9103       // Check protocols.
9104       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9105                                              /*instance=*/true);
9106     }
9107   }
9108
9109   if (!Method)
9110     return false;
9111
9112   QualType T = Method->parameters()[0]->getType();
9113   if (!T->isObjCObjectPointerType())
9114     return false;
9115
9116   QualType R = Method->getReturnType();
9117   if (!R->isScalarType())
9118     return false;
9119
9120   return true;
9121 }
9122
9123 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9124   FromE = FromE->IgnoreParenImpCasts();
9125   switch (FromE->getStmtClass()) {
9126     default:
9127       break;
9128     case Stmt::ObjCStringLiteralClass:
9129       // "string literal"
9130       return LK_String;
9131     case Stmt::ObjCArrayLiteralClass:
9132       // "array literal"
9133       return LK_Array;
9134     case Stmt::ObjCDictionaryLiteralClass:
9135       // "dictionary literal"
9136       return LK_Dictionary;
9137     case Stmt::BlockExprClass:
9138       return LK_Block;
9139     case Stmt::ObjCBoxedExprClass: {
9140       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9141       switch (Inner->getStmtClass()) {
9142         case Stmt::IntegerLiteralClass:
9143         case Stmt::FloatingLiteralClass:
9144         case Stmt::CharacterLiteralClass:
9145         case Stmt::ObjCBoolLiteralExprClass:
9146         case Stmt::CXXBoolLiteralExprClass:
9147           // "numeric literal"
9148           return LK_Numeric;
9149         case Stmt::ImplicitCastExprClass: {
9150           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9151           // Boolean literals can be represented by implicit casts.
9152           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9153             return LK_Numeric;
9154           break;
9155         }
9156         default:
9157           break;
9158       }
9159       return LK_Boxed;
9160     }
9161   }
9162   return LK_None;
9163 }
9164
9165 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9166                                           ExprResult &LHS, ExprResult &RHS,
9167                                           BinaryOperator::Opcode Opc){
9168   Expr *Literal;
9169   Expr *Other;
9170   if (isObjCObjectLiteral(LHS)) {
9171     Literal = LHS.get();
9172     Other = RHS.get();
9173   } else {
9174     Literal = RHS.get();
9175     Other = LHS.get();
9176   }
9177
9178   // Don't warn on comparisons against nil.
9179   Other = Other->IgnoreParenCasts();
9180   if (Other->isNullPointerConstant(S.getASTContext(),
9181                                    Expr::NPC_ValueDependentIsNotNull))
9182     return;
9183
9184   // This should be kept in sync with warn_objc_literal_comparison.
9185   // LK_String should always be after the other literals, since it has its own
9186   // warning flag.
9187   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9188   assert(LiteralKind != Sema::LK_Block);
9189   if (LiteralKind == Sema::LK_None) {
9190     llvm_unreachable("Unknown Objective-C object literal kind");
9191   }
9192
9193   if (LiteralKind == Sema::LK_String)
9194     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9195       << Literal->getSourceRange();
9196   else
9197     S.Diag(Loc, diag::warn_objc_literal_comparison)
9198       << LiteralKind << Literal->getSourceRange();
9199
9200   if (BinaryOperator::isEqualityOp(Opc) &&
9201       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9202     SourceLocation Start = LHS.get()->getLocStart();
9203     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9204     CharSourceRange OpRange =
9205       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9206
9207     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9208       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9209       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9210       << FixItHint::CreateInsertion(End, "]");
9211   }
9212 }
9213
9214 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9215 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9216                                            ExprResult &RHS, SourceLocation Loc,
9217                                            BinaryOperatorKind Opc) {
9218   // Check that left hand side is !something.
9219   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9220   if (!UO || UO->getOpcode() != UO_LNot) return;
9221
9222   // Only check if the right hand side is non-bool arithmetic type.
9223   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9224
9225   // Make sure that the something in !something is not bool.
9226   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9227   if (SubExpr->isKnownToHaveBooleanValue()) return;
9228
9229   // Emit warning.
9230   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9231   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9232       << Loc << IsBitwiseOp;
9233
9234   // First note suggest !(x < y)
9235   SourceLocation FirstOpen = SubExpr->getLocStart();
9236   SourceLocation FirstClose = RHS.get()->getLocEnd();
9237   FirstClose = S.getLocForEndOfToken(FirstClose);
9238   if (FirstClose.isInvalid())
9239     FirstOpen = SourceLocation();
9240   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9241       << IsBitwiseOp
9242       << FixItHint::CreateInsertion(FirstOpen, "(")
9243       << FixItHint::CreateInsertion(FirstClose, ")");
9244
9245   // Second note suggests (!x) < y
9246   SourceLocation SecondOpen = LHS.get()->getLocStart();
9247   SourceLocation SecondClose = LHS.get()->getLocEnd();
9248   SecondClose = S.getLocForEndOfToken(SecondClose);
9249   if (SecondClose.isInvalid())
9250     SecondOpen = SourceLocation();
9251   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9252       << FixItHint::CreateInsertion(SecondOpen, "(")
9253       << FixItHint::CreateInsertion(SecondClose, ")");
9254 }
9255
9256 // Get the decl for a simple expression: a reference to a variable,
9257 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9258 static ValueDecl *getCompareDecl(Expr *E) {
9259   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9260     return DR->getDecl();
9261   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9262     if (Ivar->isFreeIvar())
9263       return Ivar->getDecl();
9264   }
9265   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9266     if (Mem->isImplicitAccess())
9267       return Mem->getMemberDecl();
9268   }
9269   return nullptr;
9270 }
9271
9272 // C99 6.5.8, C++ [expr.rel]
9273 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9274                                     SourceLocation Loc, BinaryOperatorKind Opc,
9275                                     bool IsRelational) {
9276   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9277
9278   // Handle vector comparisons separately.
9279   if (LHS.get()->getType()->isVectorType() ||
9280       RHS.get()->getType()->isVectorType())
9281     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9282
9283   QualType LHSType = LHS.get()->getType();
9284   QualType RHSType = RHS.get()->getType();
9285
9286   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9287   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9288
9289   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9290   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9291
9292   if (!LHSType->hasFloatingRepresentation() &&
9293       !(LHSType->isBlockPointerType() && IsRelational) &&
9294       !LHS.get()->getLocStart().isMacroID() &&
9295       !RHS.get()->getLocStart().isMacroID() &&
9296       !inTemplateInstantiation()) {
9297     // For non-floating point types, check for self-comparisons of the form
9298     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9299     // often indicate logic errors in the program.
9300     //
9301     // NOTE: Don't warn about comparison expressions resulting from macro
9302     // expansion. Also don't warn about comparisons which are only self
9303     // comparisons within a template specialization. The warnings should catch
9304     // obvious cases in the definition of the template anyways. The idea is to
9305     // warn when the typed comparison operator will always evaluate to the same
9306     // result.
9307     ValueDecl *DL = getCompareDecl(LHSStripped);
9308     ValueDecl *DR = getCompareDecl(RHSStripped);
9309     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9310       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9311                           << 0 // self-
9312                           << (Opc == BO_EQ
9313                               || Opc == BO_LE
9314                               || Opc == BO_GE));
9315     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9316                !DL->getType()->isReferenceType() &&
9317                !DR->getType()->isReferenceType()) {
9318         // what is it always going to eval to?
9319         char always_evals_to;
9320         switch(Opc) {
9321         case BO_EQ: // e.g. array1 == array2
9322           always_evals_to = 0; // false
9323           break;
9324         case BO_NE: // e.g. array1 != array2
9325           always_evals_to = 1; // true
9326           break;
9327         default:
9328           // best we can say is 'a constant'
9329           always_evals_to = 2; // e.g. array1 <= array2
9330           break;
9331         }
9332         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9333                             << 1 // array
9334                             << always_evals_to);
9335     }
9336
9337     if (isa<CastExpr>(LHSStripped))
9338       LHSStripped = LHSStripped->IgnoreParenCasts();
9339     if (isa<CastExpr>(RHSStripped))
9340       RHSStripped = RHSStripped->IgnoreParenCasts();
9341
9342     // Warn about comparisons against a string constant (unless the other
9343     // operand is null), the user probably wants strcmp.
9344     Expr *literalString = nullptr;
9345     Expr *literalStringStripped = nullptr;
9346     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9347         !RHSStripped->isNullPointerConstant(Context,
9348                                             Expr::NPC_ValueDependentIsNull)) {
9349       literalString = LHS.get();
9350       literalStringStripped = LHSStripped;
9351     } else if ((isa<StringLiteral>(RHSStripped) ||
9352                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9353                !LHSStripped->isNullPointerConstant(Context,
9354                                             Expr::NPC_ValueDependentIsNull)) {
9355       literalString = RHS.get();
9356       literalStringStripped = RHSStripped;
9357     }
9358
9359     if (literalString) {
9360       DiagRuntimeBehavior(Loc, nullptr,
9361         PDiag(diag::warn_stringcompare)
9362           << isa<ObjCEncodeExpr>(literalStringStripped)
9363           << literalString->getSourceRange());
9364     }
9365   }
9366
9367   // C99 6.5.8p3 / C99 6.5.9p4
9368   UsualArithmeticConversions(LHS, RHS);
9369   if (LHS.isInvalid() || RHS.isInvalid())
9370     return QualType();
9371
9372   LHSType = LHS.get()->getType();
9373   RHSType = RHS.get()->getType();
9374
9375   // The result of comparisons is 'bool' in C++, 'int' in C.
9376   QualType ResultTy = Context.getLogicalOperationType();
9377
9378   if (IsRelational) {
9379     if (LHSType->isRealType() && RHSType->isRealType())
9380       return ResultTy;
9381   } else {
9382     // Check for comparisons of floating point operands using != and ==.
9383     if (LHSType->hasFloatingRepresentation())
9384       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9385
9386     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9387       return ResultTy;
9388   }
9389
9390   const Expr::NullPointerConstantKind LHSNullKind =
9391       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9392   const Expr::NullPointerConstantKind RHSNullKind =
9393       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9394   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9395   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9396
9397   if (!IsRelational && LHSIsNull != RHSIsNull) {
9398     bool IsEquality = Opc == BO_EQ;
9399     if (RHSIsNull)
9400       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9401                                    RHS.get()->getSourceRange());
9402     else
9403       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9404                                    LHS.get()->getSourceRange());
9405   }
9406
9407   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9408       (RHSType->isIntegerType() && !RHSIsNull)) {
9409     // Skip normal pointer conversion checks in this case; we have better
9410     // diagnostics for this below.
9411   } else if (getLangOpts().CPlusPlus) {
9412     // Equality comparison of a function pointer to a void pointer is invalid,
9413     // but we allow it as an extension.
9414     // FIXME: If we really want to allow this, should it be part of composite
9415     // pointer type computation so it works in conditionals too?
9416     if (!IsRelational &&
9417         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9418          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9419       // This is a gcc extension compatibility comparison.
9420       // In a SFINAE context, we treat this as a hard error to maintain
9421       // conformance with the C++ standard.
9422       diagnoseFunctionPointerToVoidComparison(
9423           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9424       
9425       if (isSFINAEContext())
9426         return QualType();
9427       
9428       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9429       return ResultTy;
9430     }
9431
9432     // C++ [expr.eq]p2:
9433     //   If at least one operand is a pointer [...] bring them to their
9434     //   composite pointer type.
9435     // C++ [expr.rel]p2:
9436     //   If both operands are pointers, [...] bring them to their composite
9437     //   pointer type.
9438     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9439             (IsRelational ? 2 : 1) &&
9440         (!LangOpts.ObjCAutoRefCount ||
9441          !(LHSType->isObjCObjectPointerType() ||
9442            RHSType->isObjCObjectPointerType()))) {
9443       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9444         return QualType();
9445       else
9446         return ResultTy;
9447     }
9448   } else if (LHSType->isPointerType() &&
9449              RHSType->isPointerType()) { // C99 6.5.8p2
9450     // All of the following pointer-related warnings are GCC extensions, except
9451     // when handling null pointer constants.
9452     QualType LCanPointeeTy =
9453       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9454     QualType RCanPointeeTy =
9455       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9456
9457     // C99 6.5.9p2 and C99 6.5.8p2
9458     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9459                                    RCanPointeeTy.getUnqualifiedType())) {
9460       // Valid unless a relational comparison of function pointers
9461       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9462         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9463           << LHSType << RHSType << LHS.get()->getSourceRange()
9464           << RHS.get()->getSourceRange();
9465       }
9466     } else if (!IsRelational &&
9467                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9468       // Valid unless comparison between non-null pointer and function pointer
9469       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9470           && !LHSIsNull && !RHSIsNull)
9471         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9472                                                 /*isError*/false);
9473     } else {
9474       // Invalid
9475       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9476     }
9477     if (LCanPointeeTy != RCanPointeeTy) {
9478       // Treat NULL constant as a special case in OpenCL.
9479       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9480         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9481         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9482           Diag(Loc,
9483                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9484               << LHSType << RHSType << 0 /* comparison */
9485               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9486         }
9487       }
9488       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9489       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9490       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9491                                                : CK_BitCast;
9492       if (LHSIsNull && !RHSIsNull)
9493         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9494       else
9495         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9496     }
9497     return ResultTy;
9498   }
9499
9500   if (getLangOpts().CPlusPlus) {
9501     // C++ [expr.eq]p4:
9502     //   Two operands of type std::nullptr_t or one operand of type
9503     //   std::nullptr_t and the other a null pointer constant compare equal.
9504     if (!IsRelational && LHSIsNull && RHSIsNull) {
9505       if (LHSType->isNullPtrType()) {
9506         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9507         return ResultTy;
9508       }
9509       if (RHSType->isNullPtrType()) {
9510         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9511         return ResultTy;
9512       }
9513     }
9514
9515     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9516     // These aren't covered by the composite pointer type rules.
9517     if (!IsRelational && RHSType->isNullPtrType() &&
9518         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9519       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9520       return ResultTy;
9521     }
9522     if (!IsRelational && LHSType->isNullPtrType() &&
9523         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9524       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9525       return ResultTy;
9526     }
9527
9528     if (IsRelational &&
9529         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9530          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9531       // HACK: Relational comparison of nullptr_t against a pointer type is
9532       // invalid per DR583, but we allow it within std::less<> and friends,
9533       // since otherwise common uses of it break.
9534       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9535       // friends to have std::nullptr_t overload candidates.
9536       DeclContext *DC = CurContext;
9537       if (isa<FunctionDecl>(DC))
9538         DC = DC->getParent();
9539       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9540         if (CTSD->isInStdNamespace() &&
9541             llvm::StringSwitch<bool>(CTSD->getName())
9542                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9543                 .Default(false)) {
9544           if (RHSType->isNullPtrType())
9545             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9546           else
9547             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9548           return ResultTy;
9549         }
9550       }
9551     }
9552
9553     // C++ [expr.eq]p2:
9554     //   If at least one operand is a pointer to member, [...] bring them to
9555     //   their composite pointer type.
9556     if (!IsRelational &&
9557         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9558       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9559         return QualType();
9560       else
9561         return ResultTy;
9562     }
9563
9564     // Handle scoped enumeration types specifically, since they don't promote
9565     // to integers.
9566     if (LHS.get()->getType()->isEnumeralType() &&
9567         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9568                                        RHS.get()->getType()))
9569       return ResultTy;
9570   }
9571
9572   // Handle block pointer types.
9573   if (!IsRelational && LHSType->isBlockPointerType() &&
9574       RHSType->isBlockPointerType()) {
9575     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9576     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9577
9578     if (!LHSIsNull && !RHSIsNull &&
9579         !Context.typesAreCompatible(lpointee, rpointee)) {
9580       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9581         << LHSType << RHSType << LHS.get()->getSourceRange()
9582         << RHS.get()->getSourceRange();
9583     }
9584     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9585     return ResultTy;
9586   }
9587
9588   // Allow block pointers to be compared with null pointer constants.
9589   if (!IsRelational
9590       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9591           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9592     if (!LHSIsNull && !RHSIsNull) {
9593       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9594              ->getPointeeType()->isVoidType())
9595             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9596                 ->getPointeeType()->isVoidType())))
9597         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9598           << LHSType << RHSType << LHS.get()->getSourceRange()
9599           << RHS.get()->getSourceRange();
9600     }
9601     if (LHSIsNull && !RHSIsNull)
9602       LHS = ImpCastExprToType(LHS.get(), RHSType,
9603                               RHSType->isPointerType() ? CK_BitCast
9604                                 : CK_AnyPointerToBlockPointerCast);
9605     else
9606       RHS = ImpCastExprToType(RHS.get(), LHSType,
9607                               LHSType->isPointerType() ? CK_BitCast
9608                                 : CK_AnyPointerToBlockPointerCast);
9609     return ResultTy;
9610   }
9611
9612   if (LHSType->isObjCObjectPointerType() ||
9613       RHSType->isObjCObjectPointerType()) {
9614     const PointerType *LPT = LHSType->getAs<PointerType>();
9615     const PointerType *RPT = RHSType->getAs<PointerType>();
9616     if (LPT || RPT) {
9617       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9618       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9619
9620       if (!LPtrToVoid && !RPtrToVoid &&
9621           !Context.typesAreCompatible(LHSType, RHSType)) {
9622         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9623                                           /*isError*/false);
9624       }
9625       if (LHSIsNull && !RHSIsNull) {
9626         Expr *E = LHS.get();
9627         if (getLangOpts().ObjCAutoRefCount)
9628           CheckObjCConversion(SourceRange(), RHSType, E,
9629                               CCK_ImplicitConversion);
9630         LHS = ImpCastExprToType(E, RHSType,
9631                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9632       }
9633       else {
9634         Expr *E = RHS.get();
9635         if (getLangOpts().ObjCAutoRefCount)
9636           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9637                               /*Diagnose=*/true,
9638                               /*DiagnoseCFAudited=*/false, Opc);
9639         RHS = ImpCastExprToType(E, LHSType,
9640                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9641       }
9642       return ResultTy;
9643     }
9644     if (LHSType->isObjCObjectPointerType() &&
9645         RHSType->isObjCObjectPointerType()) {
9646       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9647         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9648                                           /*isError*/false);
9649       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9650         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9651
9652       if (LHSIsNull && !RHSIsNull)
9653         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9654       else
9655         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9656       return ResultTy;
9657     }
9658   }
9659   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9660       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9661     unsigned DiagID = 0;
9662     bool isError = false;
9663     if (LangOpts.DebuggerSupport) {
9664       // Under a debugger, allow the comparison of pointers to integers,
9665       // since users tend to want to compare addresses.
9666     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9667                (RHSIsNull && RHSType->isIntegerType())) {
9668       if (IsRelational) {
9669         isError = getLangOpts().CPlusPlus;
9670         DiagID =
9671           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9672                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9673       }
9674     } else if (getLangOpts().CPlusPlus) {
9675       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9676       isError = true;
9677     } else if (IsRelational)
9678       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9679     else
9680       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9681
9682     if (DiagID) {
9683       Diag(Loc, DiagID)
9684         << LHSType << RHSType << LHS.get()->getSourceRange()
9685         << RHS.get()->getSourceRange();
9686       if (isError)
9687         return QualType();
9688     }
9689     
9690     if (LHSType->isIntegerType())
9691       LHS = ImpCastExprToType(LHS.get(), RHSType,
9692                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9693     else
9694       RHS = ImpCastExprToType(RHS.get(), LHSType,
9695                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9696     return ResultTy;
9697   }
9698   
9699   // Handle block pointers.
9700   if (!IsRelational && RHSIsNull
9701       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9702     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9703     return ResultTy;
9704   }
9705   if (!IsRelational && LHSIsNull
9706       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9707     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9708     return ResultTy;
9709   }
9710
9711   if (getLangOpts().OpenCLVersion >= 200) {
9712     if (LHSIsNull && RHSType->isQueueT()) {
9713       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9714       return ResultTy;
9715     }
9716
9717     if (LHSType->isQueueT() && RHSIsNull) {
9718       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9719       return ResultTy;
9720     }
9721   }
9722
9723   return InvalidOperands(Loc, LHS, RHS);
9724 }
9725
9726 // Return a signed ext_vector_type that is of identical size and number of
9727 // elements. For floating point vectors, return an integer type of identical
9728 // size and number of elements. In the non ext_vector_type case, search from
9729 // the largest type to the smallest type to avoid cases where long long == long,
9730 // where long gets picked over long long.
9731 QualType Sema::GetSignedVectorType(QualType V) {
9732   const VectorType *VTy = V->getAs<VectorType>();
9733   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9734
9735   if (isa<ExtVectorType>(VTy)) {
9736     if (TypeSize == Context.getTypeSize(Context.CharTy))
9737       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9738     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9739       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9740     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9741       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9742     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9743       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9744     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9745            "Unhandled vector element size in vector compare");
9746     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9747   }
9748
9749   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9750     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9751                                  VectorType::GenericVector);
9752   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9753     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9754                                  VectorType::GenericVector);
9755   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9756     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9757                                  VectorType::GenericVector);
9758   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9759     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9760                                  VectorType::GenericVector);
9761   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9762          "Unhandled vector element size in vector compare");
9763   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9764                                VectorType::GenericVector);
9765 }
9766
9767 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9768 /// operates on extended vector types.  Instead of producing an IntTy result,
9769 /// like a scalar comparison, a vector comparison produces a vector of integer
9770 /// types.
9771 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9772                                           SourceLocation Loc,
9773                                           bool IsRelational) {
9774   // Check to make sure we're operating on vectors of the same type and width,
9775   // Allowing one side to be a scalar of element type.
9776   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9777                               /*AllowBothBool*/true,
9778                               /*AllowBoolConversions*/getLangOpts().ZVector);
9779   if (vType.isNull())
9780     return vType;
9781
9782   QualType LHSType = LHS.get()->getType();
9783
9784   // If AltiVec, the comparison results in a numeric type, i.e.
9785   // bool for C++, int for C
9786   if (getLangOpts().AltiVec &&
9787       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9788     return Context.getLogicalOperationType();
9789
9790   // For non-floating point types, check for self-comparisons of the form
9791   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9792   // often indicate logic errors in the program.
9793   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9794     if (DeclRefExpr* DRL
9795           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9796       if (DeclRefExpr* DRR
9797             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9798         if (DRL->getDecl() == DRR->getDecl())
9799           DiagRuntimeBehavior(Loc, nullptr,
9800                               PDiag(diag::warn_comparison_always)
9801                                 << 0 // self-
9802                                 << 2 // "a constant"
9803                               );
9804   }
9805
9806   // Check for comparisons of floating point operands using != and ==.
9807   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9808     assert (RHS.get()->getType()->hasFloatingRepresentation());
9809     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9810   }
9811
9812   // Return a signed type for the vector.
9813   return GetSignedVectorType(vType);
9814 }
9815
9816 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9817                                           SourceLocation Loc) {
9818   // Ensure that either both operands are of the same vector type, or
9819   // one operand is of a vector type and the other is of its element type.
9820   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9821                                        /*AllowBothBool*/true,
9822                                        /*AllowBoolConversions*/false);
9823   if (vType.isNull())
9824     return InvalidOperands(Loc, LHS, RHS);
9825   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9826       vType->hasFloatingRepresentation())
9827     return InvalidOperands(Loc, LHS, RHS);
9828
9829   return GetSignedVectorType(LHS.get()->getType());
9830 }
9831
9832 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9833                                            SourceLocation Loc,
9834                                            BinaryOperatorKind Opc) {
9835   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9836
9837   bool IsCompAssign =
9838       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9839
9840   if (LHS.get()->getType()->isVectorType() ||
9841       RHS.get()->getType()->isVectorType()) {
9842     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9843         RHS.get()->getType()->hasIntegerRepresentation())
9844       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9845                         /*AllowBothBool*/true,
9846                         /*AllowBoolConversions*/getLangOpts().ZVector);
9847     return InvalidOperands(Loc, LHS, RHS);
9848   }
9849
9850   if (Opc == BO_And)
9851     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9852
9853   ExprResult LHSResult = LHS, RHSResult = RHS;
9854   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9855                                                  IsCompAssign);
9856   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9857     return QualType();
9858   LHS = LHSResult.get();
9859   RHS = RHSResult.get();
9860
9861   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9862     return compType;
9863   return InvalidOperands(Loc, LHS, RHS);
9864 }
9865
9866 // C99 6.5.[13,14]
9867 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9868                                            SourceLocation Loc,
9869                                            BinaryOperatorKind Opc) {
9870   // Check vector operands differently.
9871   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9872     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9873   
9874   // Diagnose cases where the user write a logical and/or but probably meant a
9875   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9876   // is a constant.
9877   if (LHS.get()->getType()->isIntegerType() &&
9878       !LHS.get()->getType()->isBooleanType() &&
9879       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9880       // Don't warn in macros or template instantiations.
9881       !Loc.isMacroID() && !inTemplateInstantiation()) {
9882     // If the RHS can be constant folded, and if it constant folds to something
9883     // that isn't 0 or 1 (which indicate a potential logical operation that
9884     // happened to fold to true/false) then warn.
9885     // Parens on the RHS are ignored.
9886     llvm::APSInt Result;
9887     if (RHS.get()->EvaluateAsInt(Result, Context))
9888       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9889            !RHS.get()->getExprLoc().isMacroID()) ||
9890           (Result != 0 && Result != 1)) {
9891         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9892           << RHS.get()->getSourceRange()
9893           << (Opc == BO_LAnd ? "&&" : "||");
9894         // Suggest replacing the logical operator with the bitwise version
9895         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9896             << (Opc == BO_LAnd ? "&" : "|")
9897             << FixItHint::CreateReplacement(SourceRange(
9898                                                  Loc, getLocForEndOfToken(Loc)),
9899                                             Opc == BO_LAnd ? "&" : "|");
9900         if (Opc == BO_LAnd)
9901           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9902           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9903               << FixItHint::CreateRemoval(
9904                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9905                               RHS.get()->getLocEnd()));
9906       }
9907   }
9908
9909   if (!Context.getLangOpts().CPlusPlus) {
9910     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9911     // not operate on the built-in scalar and vector float types.
9912     if (Context.getLangOpts().OpenCL &&
9913         Context.getLangOpts().OpenCLVersion < 120) {
9914       if (LHS.get()->getType()->isFloatingType() ||
9915           RHS.get()->getType()->isFloatingType())
9916         return InvalidOperands(Loc, LHS, RHS);
9917     }
9918
9919     LHS = UsualUnaryConversions(LHS.get());
9920     if (LHS.isInvalid())
9921       return QualType();
9922
9923     RHS = UsualUnaryConversions(RHS.get());
9924     if (RHS.isInvalid())
9925       return QualType();
9926
9927     if (!LHS.get()->getType()->isScalarType() ||
9928         !RHS.get()->getType()->isScalarType())
9929       return InvalidOperands(Loc, LHS, RHS);
9930
9931     return Context.IntTy;
9932   }
9933
9934   // The following is safe because we only use this method for
9935   // non-overloadable operands.
9936
9937   // C++ [expr.log.and]p1
9938   // C++ [expr.log.or]p1
9939   // The operands are both contextually converted to type bool.
9940   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9941   if (LHSRes.isInvalid())
9942     return InvalidOperands(Loc, LHS, RHS);
9943   LHS = LHSRes;
9944
9945   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9946   if (RHSRes.isInvalid())
9947     return InvalidOperands(Loc, LHS, RHS);
9948   RHS = RHSRes;
9949
9950   // C++ [expr.log.and]p2
9951   // C++ [expr.log.or]p2
9952   // The result is a bool.
9953   return Context.BoolTy;
9954 }
9955
9956 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9957   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9958   if (!ME) return false;
9959   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9960   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9961       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9962   if (!Base) return false;
9963   return Base->getMethodDecl() != nullptr;
9964 }
9965
9966 /// Is the given expression (which must be 'const') a reference to a
9967 /// variable which was originally non-const, but which has become
9968 /// 'const' due to being captured within a block?
9969 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9970 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9971   assert(E->isLValue() && E->getType().isConstQualified());
9972   E = E->IgnoreParens();
9973
9974   // Must be a reference to a declaration from an enclosing scope.
9975   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9976   if (!DRE) return NCCK_None;
9977   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9978
9979   // The declaration must be a variable which is not declared 'const'.
9980   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9981   if (!var) return NCCK_None;
9982   if (var->getType().isConstQualified()) return NCCK_None;
9983   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9984
9985   // Decide whether the first capture was for a block or a lambda.
9986   DeclContext *DC = S.CurContext, *Prev = nullptr;
9987   // Decide whether the first capture was for a block or a lambda.
9988   while (DC) {
9989     // For init-capture, it is possible that the variable belongs to the
9990     // template pattern of the current context.
9991     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9992       if (var->isInitCapture() &&
9993           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9994         break;
9995     if (DC == var->getDeclContext())
9996       break;
9997     Prev = DC;
9998     DC = DC->getParent();
9999   }
10000   // Unless we have an init-capture, we've gone one step too far.
10001   if (!var->isInitCapture())
10002     DC = Prev;
10003   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10004 }
10005
10006 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10007   Ty = Ty.getNonReferenceType();
10008   if (IsDereference && Ty->isPointerType())
10009     Ty = Ty->getPointeeType();
10010   return !Ty.isConstQualified();
10011 }
10012
10013 /// Emit the "read-only variable not assignable" error and print notes to give
10014 /// more information about why the variable is not assignable, such as pointing
10015 /// to the declaration of a const variable, showing that a method is const, or
10016 /// that the function is returning a const reference.
10017 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10018                                     SourceLocation Loc) {
10019   // Update err_typecheck_assign_const and note_typecheck_assign_const
10020   // when this enum is changed.
10021   enum {
10022     ConstFunction,
10023     ConstVariable,
10024     ConstMember,
10025     ConstMethod,
10026     ConstUnknown,  // Keep as last element
10027   };
10028
10029   SourceRange ExprRange = E->getSourceRange();
10030
10031   // Only emit one error on the first const found.  All other consts will emit
10032   // a note to the error.
10033   bool DiagnosticEmitted = false;
10034
10035   // Track if the current expression is the result of a dereference, and if the
10036   // next checked expression is the result of a dereference.
10037   bool IsDereference = false;
10038   bool NextIsDereference = false;
10039
10040   // Loop to process MemberExpr chains.
10041   while (true) {
10042     IsDereference = NextIsDereference;
10043
10044     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10045     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10046       NextIsDereference = ME->isArrow();
10047       const ValueDecl *VD = ME->getMemberDecl();
10048       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10049         // Mutable fields can be modified even if the class is const.
10050         if (Field->isMutable()) {
10051           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10052           break;
10053         }
10054
10055         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10056           if (!DiagnosticEmitted) {
10057             S.Diag(Loc, diag::err_typecheck_assign_const)
10058                 << ExprRange << ConstMember << false /*static*/ << Field
10059                 << Field->getType();
10060             DiagnosticEmitted = true;
10061           }
10062           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10063               << ConstMember << false /*static*/ << Field << Field->getType()
10064               << Field->getSourceRange();
10065         }
10066         E = ME->getBase();
10067         continue;
10068       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10069         if (VDecl->getType().isConstQualified()) {
10070           if (!DiagnosticEmitted) {
10071             S.Diag(Loc, diag::err_typecheck_assign_const)
10072                 << ExprRange << ConstMember << true /*static*/ << VDecl
10073                 << VDecl->getType();
10074             DiagnosticEmitted = true;
10075           }
10076           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10077               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10078               << VDecl->getSourceRange();
10079         }
10080         // Static fields do not inherit constness from parents.
10081         break;
10082       }
10083       break;
10084     } // End MemberExpr
10085     break;
10086   }
10087
10088   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10089     // Function calls
10090     const FunctionDecl *FD = CE->getDirectCallee();
10091     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10092       if (!DiagnosticEmitted) {
10093         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10094                                                       << ConstFunction << FD;
10095         DiagnosticEmitted = true;
10096       }
10097       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10098              diag::note_typecheck_assign_const)
10099           << ConstFunction << FD << FD->getReturnType()
10100           << FD->getReturnTypeSourceRange();
10101     }
10102   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10103     // Point to variable declaration.
10104     if (const ValueDecl *VD = DRE->getDecl()) {
10105       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10106         if (!DiagnosticEmitted) {
10107           S.Diag(Loc, diag::err_typecheck_assign_const)
10108               << ExprRange << ConstVariable << VD << VD->getType();
10109           DiagnosticEmitted = true;
10110         }
10111         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10112             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10113       }
10114     }
10115   } else if (isa<CXXThisExpr>(E)) {
10116     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10117       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10118         if (MD->isConst()) {
10119           if (!DiagnosticEmitted) {
10120             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10121                                                           << ConstMethod << MD;
10122             DiagnosticEmitted = true;
10123           }
10124           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10125               << ConstMethod << MD << MD->getSourceRange();
10126         }
10127       }
10128     }
10129   }
10130
10131   if (DiagnosticEmitted)
10132     return;
10133
10134   // Can't determine a more specific message, so display the generic error.
10135   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10136 }
10137
10138 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10139 /// emit an error and return true.  If so, return false.
10140 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10141   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10142
10143   S.CheckShadowingDeclModification(E, Loc);
10144
10145   SourceLocation OrigLoc = Loc;
10146   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10147                                                               &Loc);
10148   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10149     IsLV = Expr::MLV_InvalidMessageExpression;
10150   if (IsLV == Expr::MLV_Valid)
10151     return false;
10152
10153   unsigned DiagID = 0;
10154   bool NeedType = false;
10155   switch (IsLV) { // C99 6.5.16p2
10156   case Expr::MLV_ConstQualified:
10157     // Use a specialized diagnostic when we're assigning to an object
10158     // from an enclosing function or block.
10159     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10160       if (NCCK == NCCK_Block)
10161         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10162       else
10163         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10164       break;
10165     }
10166
10167     // In ARC, use some specialized diagnostics for occasions where we
10168     // infer 'const'.  These are always pseudo-strong variables.
10169     if (S.getLangOpts().ObjCAutoRefCount) {
10170       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10171       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10172         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10173
10174         // Use the normal diagnostic if it's pseudo-__strong but the
10175         // user actually wrote 'const'.
10176         if (var->isARCPseudoStrong() &&
10177             (!var->getTypeSourceInfo() ||
10178              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10179           // There are two pseudo-strong cases:
10180           //  - self
10181           ObjCMethodDecl *method = S.getCurMethodDecl();
10182           if (method && var == method->getSelfDecl())
10183             DiagID = method->isClassMethod()
10184               ? diag::err_typecheck_arc_assign_self_class_method
10185               : diag::err_typecheck_arc_assign_self;
10186
10187           //  - fast enumeration variables
10188           else
10189             DiagID = diag::err_typecheck_arr_assign_enumeration;
10190
10191           SourceRange Assign;
10192           if (Loc != OrigLoc)
10193             Assign = SourceRange(OrigLoc, OrigLoc);
10194           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10195           // We need to preserve the AST regardless, so migration tool
10196           // can do its job.
10197           return false;
10198         }
10199       }
10200     }
10201
10202     // If none of the special cases above are triggered, then this is a
10203     // simple const assignment.
10204     if (DiagID == 0) {
10205       DiagnoseConstAssignment(S, E, Loc);
10206       return true;
10207     }
10208
10209     break;
10210   case Expr::MLV_ConstAddrSpace:
10211     DiagnoseConstAssignment(S, E, Loc);
10212     return true;
10213   case Expr::MLV_ArrayType:
10214   case Expr::MLV_ArrayTemporary:
10215     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10216     NeedType = true;
10217     break;
10218   case Expr::MLV_NotObjectType:
10219     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10220     NeedType = true;
10221     break;
10222   case Expr::MLV_LValueCast:
10223     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10224     break;
10225   case Expr::MLV_Valid:
10226     llvm_unreachable("did not take early return for MLV_Valid");
10227   case Expr::MLV_InvalidExpression:
10228   case Expr::MLV_MemberFunction:
10229   case Expr::MLV_ClassTemporary:
10230     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10231     break;
10232   case Expr::MLV_IncompleteType:
10233   case Expr::MLV_IncompleteVoidType:
10234     return S.RequireCompleteType(Loc, E->getType(),
10235              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10236   case Expr::MLV_DuplicateVectorComponents:
10237     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10238     break;
10239   case Expr::MLV_NoSetterProperty:
10240     llvm_unreachable("readonly properties should be processed differently");
10241   case Expr::MLV_InvalidMessageExpression:
10242     DiagID = diag::err_readonly_message_assignment;
10243     break;
10244   case Expr::MLV_SubObjCPropertySetting:
10245     DiagID = diag::err_no_subobject_property_setting;
10246     break;
10247   }
10248
10249   SourceRange Assign;
10250   if (Loc != OrigLoc)
10251     Assign = SourceRange(OrigLoc, OrigLoc);
10252   if (NeedType)
10253     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10254   else
10255     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10256   return true;
10257 }
10258
10259 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10260                                          SourceLocation Loc,
10261                                          Sema &Sema) {
10262   // C / C++ fields
10263   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10264   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10265   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10266     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10267       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10268   }
10269
10270   // Objective-C instance variables
10271   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10272   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10273   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10274     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10275     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10276     if (RL && RR && RL->getDecl() == RR->getDecl())
10277       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10278   }
10279 }
10280
10281 // C99 6.5.16.1
10282 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10283                                        SourceLocation Loc,
10284                                        QualType CompoundType) {
10285   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10286
10287   // Verify that LHS is a modifiable lvalue, and emit error if not.
10288   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10289     return QualType();
10290
10291   QualType LHSType = LHSExpr->getType();
10292   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10293                                              CompoundType;
10294   // OpenCL v1.2 s6.1.1.1 p2:
10295   // The half data type can only be used to declare a pointer to a buffer that
10296   // contains half values
10297   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10298     LHSType->isHalfType()) {
10299     Diag(Loc, diag::err_opencl_half_load_store) << 1
10300         << LHSType.getUnqualifiedType();
10301     return QualType();
10302   }
10303     
10304   AssignConvertType ConvTy;
10305   if (CompoundType.isNull()) {
10306     Expr *RHSCheck = RHS.get();
10307
10308     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10309
10310     QualType LHSTy(LHSType);
10311     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10312     if (RHS.isInvalid())
10313       return QualType();
10314     // Special case of NSObject attributes on c-style pointer types.
10315     if (ConvTy == IncompatiblePointer &&
10316         ((Context.isObjCNSObjectType(LHSType) &&
10317           RHSType->isObjCObjectPointerType()) ||
10318          (Context.isObjCNSObjectType(RHSType) &&
10319           LHSType->isObjCObjectPointerType())))
10320       ConvTy = Compatible;
10321
10322     if (ConvTy == Compatible &&
10323         LHSType->isObjCObjectType())
10324         Diag(Loc, diag::err_objc_object_assignment)
10325           << LHSType;
10326
10327     // If the RHS is a unary plus or minus, check to see if they = and + are
10328     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10329     // instead of "x += 4".
10330     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10331       RHSCheck = ICE->getSubExpr();
10332     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10333       if ((UO->getOpcode() == UO_Plus ||
10334            UO->getOpcode() == UO_Minus) &&
10335           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10336           // Only if the two operators are exactly adjacent.
10337           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10338           // And there is a space or other character before the subexpr of the
10339           // unary +/-.  We don't want to warn on "x=-1".
10340           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10341           UO->getSubExpr()->getLocStart().isFileID()) {
10342         Diag(Loc, diag::warn_not_compound_assign)
10343           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10344           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10345       }
10346     }
10347
10348     if (ConvTy == Compatible) {
10349       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10350         // Warn about retain cycles where a block captures the LHS, but
10351         // not if the LHS is a simple variable into which the block is
10352         // being stored...unless that variable can be captured by reference!
10353         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10354         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10355         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10356           checkRetainCycles(LHSExpr, RHS.get());
10357       }
10358
10359       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10360           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10361         // It is safe to assign a weak reference into a strong variable.
10362         // Although this code can still have problems:
10363         //   id x = self.weakProp;
10364         //   id y = self.weakProp;
10365         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10366         // paths through the function. This should be revisited if
10367         // -Wrepeated-use-of-weak is made flow-sensitive.
10368         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10369         // variable, which will be valid for the current autorelease scope.
10370         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10371                              RHS.get()->getLocStart()))
10372           getCurFunction()->markSafeWeakUse(RHS.get());
10373
10374       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10375         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10376       }
10377     }
10378   } else {
10379     // Compound assignment "x += y"
10380     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10381   }
10382
10383   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10384                                RHS.get(), AA_Assigning))
10385     return QualType();
10386
10387   CheckForNullPointerDereference(*this, LHSExpr);
10388
10389   // C99 6.5.16p3: The type of an assignment expression is the type of the
10390   // left operand unless the left operand has qualified type, in which case
10391   // it is the unqualified version of the type of the left operand.
10392   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10393   // is converted to the type of the assignment expression (above).
10394   // C++ 5.17p1: the type of the assignment expression is that of its left
10395   // operand.
10396   return (getLangOpts().CPlusPlus
10397           ? LHSType : LHSType.getUnqualifiedType());
10398 }
10399
10400 // Only ignore explicit casts to void.
10401 static bool IgnoreCommaOperand(const Expr *E) {
10402   E = E->IgnoreParens();
10403
10404   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10405     if (CE->getCastKind() == CK_ToVoid) {
10406       return true;
10407     }
10408   }
10409
10410   return false;
10411 }
10412
10413 // Look for instances where it is likely the comma operator is confused with
10414 // another operator.  There is a whitelist of acceptable expressions for the
10415 // left hand side of the comma operator, otherwise emit a warning.
10416 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10417   // No warnings in macros
10418   if (Loc.isMacroID())
10419     return;
10420
10421   // Don't warn in template instantiations.
10422   if (inTemplateInstantiation())
10423     return;
10424
10425   // Scope isn't fine-grained enough to whitelist the specific cases, so
10426   // instead, skip more than needed, then call back into here with the
10427   // CommaVisitor in SemaStmt.cpp.
10428   // The whitelisted locations are the initialization and increment portions
10429   // of a for loop.  The additional checks are on the condition of
10430   // if statements, do/while loops, and for loops.
10431   const unsigned ForIncrementFlags =
10432       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10433   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10434   const unsigned ScopeFlags = getCurScope()->getFlags();
10435   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10436       (ScopeFlags & ForInitFlags) == ForInitFlags)
10437     return;
10438
10439   // If there are multiple comma operators used together, get the RHS of the
10440   // of the comma operator as the LHS.
10441   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10442     if (BO->getOpcode() != BO_Comma)
10443       break;
10444     LHS = BO->getRHS();
10445   }
10446
10447   // Only allow some expressions on LHS to not warn.
10448   if (IgnoreCommaOperand(LHS))
10449     return;
10450
10451   Diag(Loc, diag::warn_comma_operator);
10452   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10453       << LHS->getSourceRange()
10454       << FixItHint::CreateInsertion(LHS->getLocStart(),
10455                                     LangOpts.CPlusPlus ? "static_cast<void>("
10456                                                        : "(void)(")
10457       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10458                                     ")");
10459 }
10460
10461 // C99 6.5.17
10462 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10463                                    SourceLocation Loc) {
10464   LHS = S.CheckPlaceholderExpr(LHS.get());
10465   RHS = S.CheckPlaceholderExpr(RHS.get());
10466   if (LHS.isInvalid() || RHS.isInvalid())
10467     return QualType();
10468
10469   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10470   // operands, but not unary promotions.
10471   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10472
10473   // So we treat the LHS as a ignored value, and in C++ we allow the
10474   // containing site to determine what should be done with the RHS.
10475   LHS = S.IgnoredValueConversions(LHS.get());
10476   if (LHS.isInvalid())
10477     return QualType();
10478
10479   S.DiagnoseUnusedExprResult(LHS.get());
10480
10481   if (!S.getLangOpts().CPlusPlus) {
10482     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10483     if (RHS.isInvalid())
10484       return QualType();
10485     if (!RHS.get()->getType()->isVoidType())
10486       S.RequireCompleteType(Loc, RHS.get()->getType(),
10487                             diag::err_incomplete_type);
10488   }
10489
10490   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10491     S.DiagnoseCommaOperator(LHS.get(), Loc);
10492
10493   return RHS.get()->getType();
10494 }
10495
10496 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10497 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10498 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10499                                                ExprValueKind &VK,
10500                                                ExprObjectKind &OK,
10501                                                SourceLocation OpLoc,
10502                                                bool IsInc, bool IsPrefix) {
10503   if (Op->isTypeDependent())
10504     return S.Context.DependentTy;
10505
10506   QualType ResType = Op->getType();
10507   // Atomic types can be used for increment / decrement where the non-atomic
10508   // versions can, so ignore the _Atomic() specifier for the purpose of
10509   // checking.
10510   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10511     ResType = ResAtomicType->getValueType();
10512
10513   assert(!ResType.isNull() && "no type for increment/decrement expression");
10514
10515   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10516     // Decrement of bool is not allowed.
10517     if (!IsInc) {
10518       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10519       return QualType();
10520     }
10521     // Increment of bool sets it to true, but is deprecated.
10522     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10523                                               : diag::warn_increment_bool)
10524       << Op->getSourceRange();
10525   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10526     // Error on enum increments and decrements in C++ mode
10527     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10528     return QualType();
10529   } else if (ResType->isRealType()) {
10530     // OK!
10531   } else if (ResType->isPointerType()) {
10532     // C99 6.5.2.4p2, 6.5.6p2
10533     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10534       return QualType();
10535   } else if (ResType->isObjCObjectPointerType()) {
10536     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10537     // Otherwise, we just need a complete type.
10538     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10539         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10540       return QualType();    
10541   } else if (ResType->isAnyComplexType()) {
10542     // C99 does not support ++/-- on complex types, we allow as an extension.
10543     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10544       << ResType << Op->getSourceRange();
10545   } else if (ResType->isPlaceholderType()) {
10546     ExprResult PR = S.CheckPlaceholderExpr(Op);
10547     if (PR.isInvalid()) return QualType();
10548     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10549                                           IsInc, IsPrefix);
10550   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10551     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10552   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10553              (ResType->getAs<VectorType>()->getVectorKind() !=
10554               VectorType::AltiVecBool)) {
10555     // The z vector extensions allow ++ and -- for non-bool vectors.
10556   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10557             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10558     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10559   } else {
10560     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10561       << ResType << int(IsInc) << Op->getSourceRange();
10562     return QualType();
10563   }
10564   // At this point, we know we have a real, complex or pointer type.
10565   // Now make sure the operand is a modifiable lvalue.
10566   if (CheckForModifiableLvalue(Op, OpLoc, S))
10567     return QualType();
10568   // In C++, a prefix increment is the same type as the operand. Otherwise
10569   // (in C or with postfix), the increment is the unqualified type of the
10570   // operand.
10571   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10572     VK = VK_LValue;
10573     OK = Op->getObjectKind();
10574     return ResType;
10575   } else {
10576     VK = VK_RValue;
10577     return ResType.getUnqualifiedType();
10578   }
10579 }
10580   
10581
10582 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10583 /// This routine allows us to typecheck complex/recursive expressions
10584 /// where the declaration is needed for type checking. We only need to
10585 /// handle cases when the expression references a function designator
10586 /// or is an lvalue. Here are some examples:
10587 ///  - &(x) => x
10588 ///  - &*****f => f for f a function designator.
10589 ///  - &s.xx => s
10590 ///  - &s.zz[1].yy -> s, if zz is an array
10591 ///  - *(x + 1) -> x, if x is an array
10592 ///  - &"123"[2] -> 0
10593 ///  - & __real__ x -> x
10594 static ValueDecl *getPrimaryDecl(Expr *E) {
10595   switch (E->getStmtClass()) {
10596   case Stmt::DeclRefExprClass:
10597     return cast<DeclRefExpr>(E)->getDecl();
10598   case Stmt::MemberExprClass:
10599     // If this is an arrow operator, the address is an offset from
10600     // the base's value, so the object the base refers to is
10601     // irrelevant.
10602     if (cast<MemberExpr>(E)->isArrow())
10603       return nullptr;
10604     // Otherwise, the expression refers to a part of the base
10605     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10606   case Stmt::ArraySubscriptExprClass: {
10607     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10608     // promotion of register arrays earlier.
10609     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10610     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10611       if (ICE->getSubExpr()->getType()->isArrayType())
10612         return getPrimaryDecl(ICE->getSubExpr());
10613     }
10614     return nullptr;
10615   }
10616   case Stmt::UnaryOperatorClass: {
10617     UnaryOperator *UO = cast<UnaryOperator>(E);
10618
10619     switch(UO->getOpcode()) {
10620     case UO_Real:
10621     case UO_Imag:
10622     case UO_Extension:
10623       return getPrimaryDecl(UO->getSubExpr());
10624     default:
10625       return nullptr;
10626     }
10627   }
10628   case Stmt::ParenExprClass:
10629     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10630   case Stmt::ImplicitCastExprClass:
10631     // If the result of an implicit cast is an l-value, we care about
10632     // the sub-expression; otherwise, the result here doesn't matter.
10633     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10634   default:
10635     return nullptr;
10636   }
10637 }
10638
10639 namespace {
10640   enum {
10641     AO_Bit_Field = 0,
10642     AO_Vector_Element = 1,
10643     AO_Property_Expansion = 2,
10644     AO_Register_Variable = 3,
10645     AO_No_Error = 4
10646   };
10647 }
10648 /// \brief Diagnose invalid operand for address of operations.
10649 ///
10650 /// \param Type The type of operand which cannot have its address taken.
10651 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10652                                          Expr *E, unsigned Type) {
10653   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10654 }
10655
10656 /// CheckAddressOfOperand - The operand of & must be either a function
10657 /// designator or an lvalue designating an object. If it is an lvalue, the
10658 /// object cannot be declared with storage class register or be a bit field.
10659 /// Note: The usual conversions are *not* applied to the operand of the &
10660 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10661 /// In C++, the operand might be an overloaded function name, in which case
10662 /// we allow the '&' but retain the overloaded-function type.
10663 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10664   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10665     if (PTy->getKind() == BuiltinType::Overload) {
10666       Expr *E = OrigOp.get()->IgnoreParens();
10667       if (!isa<OverloadExpr>(E)) {
10668         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10669         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10670           << OrigOp.get()->getSourceRange();
10671         return QualType();
10672       }
10673
10674       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10675       if (isa<UnresolvedMemberExpr>(Ovl))
10676         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10677           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10678             << OrigOp.get()->getSourceRange();
10679           return QualType();
10680         }
10681
10682       return Context.OverloadTy;
10683     }
10684
10685     if (PTy->getKind() == BuiltinType::UnknownAny)
10686       return Context.UnknownAnyTy;
10687
10688     if (PTy->getKind() == BuiltinType::BoundMember) {
10689       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10690         << OrigOp.get()->getSourceRange();
10691       return QualType();
10692     }
10693
10694     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10695     if (OrigOp.isInvalid()) return QualType();
10696   }
10697
10698   if (OrigOp.get()->isTypeDependent())
10699     return Context.DependentTy;
10700
10701   assert(!OrigOp.get()->getType()->isPlaceholderType());
10702
10703   // Make sure to ignore parentheses in subsequent checks
10704   Expr *op = OrigOp.get()->IgnoreParens();
10705
10706   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10707   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10708     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10709     return QualType();
10710   }
10711
10712   if (getLangOpts().C99) {
10713     // Implement C99-only parts of addressof rules.
10714     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10715       if (uOp->getOpcode() == UO_Deref)
10716         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10717         // (assuming the deref expression is valid).
10718         return uOp->getSubExpr()->getType();
10719     }
10720     // Technically, there should be a check for array subscript
10721     // expressions here, but the result of one is always an lvalue anyway.
10722   }
10723   ValueDecl *dcl = getPrimaryDecl(op);
10724
10725   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10726     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10727                                            op->getLocStart()))
10728       return QualType();
10729
10730   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10731   unsigned AddressOfError = AO_No_Error;
10732
10733   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10734     bool sfinae = (bool)isSFINAEContext();
10735     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10736                                   : diag::ext_typecheck_addrof_temporary)
10737       << op->getType() << op->getSourceRange();
10738     if (sfinae)
10739       return QualType();
10740     // Materialize the temporary as an lvalue so that we can take its address.
10741     OrigOp = op =
10742         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10743   } else if (isa<ObjCSelectorExpr>(op)) {
10744     return Context.getPointerType(op->getType());
10745   } else if (lval == Expr::LV_MemberFunction) {
10746     // If it's an instance method, make a member pointer.
10747     // The expression must have exactly the form &A::foo.
10748
10749     // If the underlying expression isn't a decl ref, give up.
10750     if (!isa<DeclRefExpr>(op)) {
10751       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10752         << OrigOp.get()->getSourceRange();
10753       return QualType();
10754     }
10755     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10756     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10757
10758     // The id-expression was parenthesized.
10759     if (OrigOp.get() != DRE) {
10760       Diag(OpLoc, diag::err_parens_pointer_member_function)
10761         << OrigOp.get()->getSourceRange();
10762
10763     // The method was named without a qualifier.
10764     } else if (!DRE->getQualifier()) {
10765       if (MD->getParent()->getName().empty())
10766         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10767           << op->getSourceRange();
10768       else {
10769         SmallString<32> Str;
10770         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10771         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10772           << op->getSourceRange()
10773           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10774       }
10775     }
10776
10777     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10778     if (isa<CXXDestructorDecl>(MD))
10779       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10780
10781     QualType MPTy = Context.getMemberPointerType(
10782         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10783     // Under the MS ABI, lock down the inheritance model now.
10784     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10785       (void)isCompleteType(OpLoc, MPTy);
10786     return MPTy;
10787   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10788     // C99 6.5.3.2p1
10789     // The operand must be either an l-value or a function designator
10790     if (!op->getType()->isFunctionType()) {
10791       // Use a special diagnostic for loads from property references.
10792       if (isa<PseudoObjectExpr>(op)) {
10793         AddressOfError = AO_Property_Expansion;
10794       } else {
10795         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10796           << op->getType() << op->getSourceRange();
10797         return QualType();
10798       }
10799     }
10800   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10801     // The operand cannot be a bit-field
10802     AddressOfError = AO_Bit_Field;
10803   } else if (op->getObjectKind() == OK_VectorComponent) {
10804     // The operand cannot be an element of a vector
10805     AddressOfError = AO_Vector_Element;
10806   } else if (dcl) { // C99 6.5.3.2p1
10807     // We have an lvalue with a decl. Make sure the decl is not declared
10808     // with the register storage-class specifier.
10809     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10810       // in C++ it is not error to take address of a register
10811       // variable (c++03 7.1.1P3)
10812       if (vd->getStorageClass() == SC_Register &&
10813           !getLangOpts().CPlusPlus) {
10814         AddressOfError = AO_Register_Variable;
10815       }
10816     } else if (isa<MSPropertyDecl>(dcl)) {
10817       AddressOfError = AO_Property_Expansion;
10818     } else if (isa<FunctionTemplateDecl>(dcl)) {
10819       return Context.OverloadTy;
10820     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10821       // Okay: we can take the address of a field.
10822       // Could be a pointer to member, though, if there is an explicit
10823       // scope qualifier for the class.
10824       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10825         DeclContext *Ctx = dcl->getDeclContext();
10826         if (Ctx && Ctx->isRecord()) {
10827           if (dcl->getType()->isReferenceType()) {
10828             Diag(OpLoc,
10829                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10830               << dcl->getDeclName() << dcl->getType();
10831             return QualType();
10832           }
10833
10834           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10835             Ctx = Ctx->getParent();
10836
10837           QualType MPTy = Context.getMemberPointerType(
10838               op->getType(),
10839               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10840           // Under the MS ABI, lock down the inheritance model now.
10841           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10842             (void)isCompleteType(OpLoc, MPTy);
10843           return MPTy;
10844         }
10845       }
10846     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10847                !isa<BindingDecl>(dcl))
10848       llvm_unreachable("Unknown/unexpected decl type");
10849   }
10850
10851   if (AddressOfError != AO_No_Error) {
10852     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10853     return QualType();
10854   }
10855
10856   if (lval == Expr::LV_IncompleteVoidType) {
10857     // Taking the address of a void variable is technically illegal, but we
10858     // allow it in cases which are otherwise valid.
10859     // Example: "extern void x; void* y = &x;".
10860     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10861   }
10862
10863   // If the operand has type "type", the result has type "pointer to type".
10864   if (op->getType()->isObjCObjectType())
10865     return Context.getObjCObjectPointerType(op->getType());
10866
10867   CheckAddressOfPackedMember(op);
10868
10869   return Context.getPointerType(op->getType());
10870 }
10871
10872 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10873   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10874   if (!DRE)
10875     return;
10876   const Decl *D = DRE->getDecl();
10877   if (!D)
10878     return;
10879   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10880   if (!Param)
10881     return;
10882   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10883     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10884       return;
10885   if (FunctionScopeInfo *FD = S.getCurFunction())
10886     if (!FD->ModifiedNonNullParams.count(Param))
10887       FD->ModifiedNonNullParams.insert(Param);
10888 }
10889
10890 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10891 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10892                                         SourceLocation OpLoc) {
10893   if (Op->isTypeDependent())
10894     return S.Context.DependentTy;
10895
10896   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10897   if (ConvResult.isInvalid())
10898     return QualType();
10899   Op = ConvResult.get();
10900   QualType OpTy = Op->getType();
10901   QualType Result;
10902
10903   if (isa<CXXReinterpretCastExpr>(Op)) {
10904     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10905     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10906                                      Op->getSourceRange());
10907   }
10908
10909   if (const PointerType *PT = OpTy->getAs<PointerType>())
10910   {
10911     Result = PT->getPointeeType();
10912   }
10913   else if (const ObjCObjectPointerType *OPT =
10914              OpTy->getAs<ObjCObjectPointerType>())
10915     Result = OPT->getPointeeType();
10916   else {
10917     ExprResult PR = S.CheckPlaceholderExpr(Op);
10918     if (PR.isInvalid()) return QualType();
10919     if (PR.get() != Op)
10920       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10921   }
10922
10923   if (Result.isNull()) {
10924     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10925       << OpTy << Op->getSourceRange();
10926     return QualType();
10927   }
10928
10929   // Note that per both C89 and C99, indirection is always legal, even if Result
10930   // is an incomplete type or void.  It would be possible to warn about
10931   // dereferencing a void pointer, but it's completely well-defined, and such a
10932   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10933   // for pointers to 'void' but is fine for any other pointer type:
10934   //
10935   // C++ [expr.unary.op]p1:
10936   //   [...] the expression to which [the unary * operator] is applied shall
10937   //   be a pointer to an object type, or a pointer to a function type
10938   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10939     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10940       << OpTy << Op->getSourceRange();
10941
10942   // Dereferences are usually l-values...
10943   VK = VK_LValue;
10944
10945   // ...except that certain expressions are never l-values in C.
10946   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10947     VK = VK_RValue;
10948   
10949   return Result;
10950 }
10951
10952 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10953   BinaryOperatorKind Opc;
10954   switch (Kind) {
10955   default: llvm_unreachable("Unknown binop!");
10956   case tok::periodstar:           Opc = BO_PtrMemD; break;
10957   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10958   case tok::star:                 Opc = BO_Mul; break;
10959   case tok::slash:                Opc = BO_Div; break;
10960   case tok::percent:              Opc = BO_Rem; break;
10961   case tok::plus:                 Opc = BO_Add; break;
10962   case tok::minus:                Opc = BO_Sub; break;
10963   case tok::lessless:             Opc = BO_Shl; break;
10964   case tok::greatergreater:       Opc = BO_Shr; break;
10965   case tok::lessequal:            Opc = BO_LE; break;
10966   case tok::less:                 Opc = BO_LT; break;
10967   case tok::greaterequal:         Opc = BO_GE; break;
10968   case tok::greater:              Opc = BO_GT; break;
10969   case tok::exclaimequal:         Opc = BO_NE; break;
10970   case tok::equalequal:           Opc = BO_EQ; break;
10971   case tok::amp:                  Opc = BO_And; break;
10972   case tok::caret:                Opc = BO_Xor; break;
10973   case tok::pipe:                 Opc = BO_Or; break;
10974   case tok::ampamp:               Opc = BO_LAnd; break;
10975   case tok::pipepipe:             Opc = BO_LOr; break;
10976   case tok::equal:                Opc = BO_Assign; break;
10977   case tok::starequal:            Opc = BO_MulAssign; break;
10978   case tok::slashequal:           Opc = BO_DivAssign; break;
10979   case tok::percentequal:         Opc = BO_RemAssign; break;
10980   case tok::plusequal:            Opc = BO_AddAssign; break;
10981   case tok::minusequal:           Opc = BO_SubAssign; break;
10982   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10983   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10984   case tok::ampequal:             Opc = BO_AndAssign; break;
10985   case tok::caretequal:           Opc = BO_XorAssign; break;
10986   case tok::pipeequal:            Opc = BO_OrAssign; break;
10987   case tok::comma:                Opc = BO_Comma; break;
10988   }
10989   return Opc;
10990 }
10991
10992 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10993   tok::TokenKind Kind) {
10994   UnaryOperatorKind Opc;
10995   switch (Kind) {
10996   default: llvm_unreachable("Unknown unary op!");
10997   case tok::plusplus:     Opc = UO_PreInc; break;
10998   case tok::minusminus:   Opc = UO_PreDec; break;
10999   case tok::amp:          Opc = UO_AddrOf; break;
11000   case tok::star:         Opc = UO_Deref; break;
11001   case tok::plus:         Opc = UO_Plus; break;
11002   case tok::minus:        Opc = UO_Minus; break;
11003   case tok::tilde:        Opc = UO_Not; break;
11004   case tok::exclaim:      Opc = UO_LNot; break;
11005   case tok::kw___real:    Opc = UO_Real; break;
11006   case tok::kw___imag:    Opc = UO_Imag; break;
11007   case tok::kw___extension__: Opc = UO_Extension; break;
11008   }
11009   return Opc;
11010 }
11011
11012 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11013 /// This warning is only emitted for builtin assignment operations. It is also
11014 /// suppressed in the event of macro expansions.
11015 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11016                                    SourceLocation OpLoc) {
11017   if (S.inTemplateInstantiation())
11018     return;
11019   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11020     return;
11021   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11022   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11023   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11024   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11025   if (!LHSDeclRef || !RHSDeclRef ||
11026       LHSDeclRef->getLocation().isMacroID() ||
11027       RHSDeclRef->getLocation().isMacroID())
11028     return;
11029   const ValueDecl *LHSDecl =
11030     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11031   const ValueDecl *RHSDecl =
11032     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11033   if (LHSDecl != RHSDecl)
11034     return;
11035   if (LHSDecl->getType().isVolatileQualified())
11036     return;
11037   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11038     if (RefTy->getPointeeType().isVolatileQualified())
11039       return;
11040
11041   S.Diag(OpLoc, diag::warn_self_assignment)
11042       << LHSDeclRef->getType()
11043       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11044 }
11045
11046 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11047 /// is usually indicative of introspection within the Objective-C pointer.
11048 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11049                                           SourceLocation OpLoc) {
11050   if (!S.getLangOpts().ObjC1)
11051     return;
11052
11053   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11054   const Expr *LHS = L.get();
11055   const Expr *RHS = R.get();
11056
11057   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11058     ObjCPointerExpr = LHS;
11059     OtherExpr = RHS;
11060   }
11061   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11062     ObjCPointerExpr = RHS;
11063     OtherExpr = LHS;
11064   }
11065
11066   // This warning is deliberately made very specific to reduce false
11067   // positives with logic that uses '&' for hashing.  This logic mainly
11068   // looks for code trying to introspect into tagged pointers, which
11069   // code should generally never do.
11070   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11071     unsigned Diag = diag::warn_objc_pointer_masking;
11072     // Determine if we are introspecting the result of performSelectorXXX.
11073     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11074     // Special case messages to -performSelector and friends, which
11075     // can return non-pointer values boxed in a pointer value.
11076     // Some clients may wish to silence warnings in this subcase.
11077     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11078       Selector S = ME->getSelector();
11079       StringRef SelArg0 = S.getNameForSlot(0);
11080       if (SelArg0.startswith("performSelector"))
11081         Diag = diag::warn_objc_pointer_masking_performSelector;
11082     }
11083     
11084     S.Diag(OpLoc, Diag)
11085       << ObjCPointerExpr->getSourceRange();
11086   }
11087 }
11088
11089 static NamedDecl *getDeclFromExpr(Expr *E) {
11090   if (!E)
11091     return nullptr;
11092   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11093     return DRE->getDecl();
11094   if (auto *ME = dyn_cast<MemberExpr>(E))
11095     return ME->getMemberDecl();
11096   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11097     return IRE->getDecl();
11098   return nullptr;
11099 }
11100
11101 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11102 /// operator @p Opc at location @c TokLoc. This routine only supports
11103 /// built-in operations; ActOnBinOp handles overloaded operators.
11104 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11105                                     BinaryOperatorKind Opc,
11106                                     Expr *LHSExpr, Expr *RHSExpr) {
11107   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11108     // The syntax only allows initializer lists on the RHS of assignment,
11109     // so we don't need to worry about accepting invalid code for
11110     // non-assignment operators.
11111     // C++11 5.17p9:
11112     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11113     //   of x = {} is x = T().
11114     InitializationKind Kind =
11115         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11116     InitializedEntity Entity =
11117         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11118     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11119     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11120     if (Init.isInvalid())
11121       return Init;
11122     RHSExpr = Init.get();
11123   }
11124
11125   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11126   QualType ResultTy;     // Result type of the binary operator.
11127   // The following two variables are used for compound assignment operators
11128   QualType CompLHSTy;    // Type of LHS after promotions for computation
11129   QualType CompResultTy; // Type of computation result
11130   ExprValueKind VK = VK_RValue;
11131   ExprObjectKind OK = OK_Ordinary;
11132
11133   if (!getLangOpts().CPlusPlus) {
11134     // C cannot handle TypoExpr nodes on either side of a binop because it
11135     // doesn't handle dependent types properly, so make sure any TypoExprs have
11136     // been dealt with before checking the operands.
11137     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11138     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11139       if (Opc != BO_Assign)
11140         return ExprResult(E);
11141       // Avoid correcting the RHS to the same Expr as the LHS.
11142       Decl *D = getDeclFromExpr(E);
11143       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11144     });
11145     if (!LHS.isUsable() || !RHS.isUsable())
11146       return ExprError();
11147   }
11148
11149   if (getLangOpts().OpenCL) {
11150     QualType LHSTy = LHSExpr->getType();
11151     QualType RHSTy = RHSExpr->getType();
11152     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11153     // the ATOMIC_VAR_INIT macro.
11154     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11155       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11156       if (BO_Assign == Opc)
11157         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11158       else
11159         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11160       return ExprError();
11161     }
11162
11163     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11164     // only with a builtin functions and therefore should be disallowed here.
11165     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11166         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11167         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11168         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11169       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11170       return ExprError();
11171     }
11172   }
11173
11174   switch (Opc) {
11175   case BO_Assign:
11176     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11177     if (getLangOpts().CPlusPlus &&
11178         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11179       VK = LHS.get()->getValueKind();
11180       OK = LHS.get()->getObjectKind();
11181     }
11182     if (!ResultTy.isNull()) {
11183       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11184       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11185     }
11186     RecordModifiableNonNullParam(*this, LHS.get());
11187     break;
11188   case BO_PtrMemD:
11189   case BO_PtrMemI:
11190     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11191                                             Opc == BO_PtrMemI);
11192     break;
11193   case BO_Mul:
11194   case BO_Div:
11195     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11196                                            Opc == BO_Div);
11197     break;
11198   case BO_Rem:
11199     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11200     break;
11201   case BO_Add:
11202     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11203     break;
11204   case BO_Sub:
11205     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11206     break;
11207   case BO_Shl:
11208   case BO_Shr:
11209     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11210     break;
11211   case BO_LE:
11212   case BO_LT:
11213   case BO_GE:
11214   case BO_GT:
11215     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11216     break;
11217   case BO_EQ:
11218   case BO_NE:
11219     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11220     break;
11221   case BO_And:
11222     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11223   case BO_Xor:
11224   case BO_Or:
11225     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11226     break;
11227   case BO_LAnd:
11228   case BO_LOr:
11229     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11230     break;
11231   case BO_MulAssign:
11232   case BO_DivAssign:
11233     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11234                                                Opc == BO_DivAssign);
11235     CompLHSTy = CompResultTy;
11236     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11237       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11238     break;
11239   case BO_RemAssign:
11240     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11241     CompLHSTy = CompResultTy;
11242     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11243       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11244     break;
11245   case BO_AddAssign:
11246     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11247     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11248       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11249     break;
11250   case BO_SubAssign:
11251     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11252     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11253       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11254     break;
11255   case BO_ShlAssign:
11256   case BO_ShrAssign:
11257     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11258     CompLHSTy = CompResultTy;
11259     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11260       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11261     break;
11262   case BO_AndAssign:
11263   case BO_OrAssign: // fallthrough
11264     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11265   case BO_XorAssign:
11266     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11267     CompLHSTy = CompResultTy;
11268     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11269       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11270     break;
11271   case BO_Comma:
11272     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11273     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11274       VK = RHS.get()->getValueKind();
11275       OK = RHS.get()->getObjectKind();
11276     }
11277     break;
11278   }
11279   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11280     return ExprError();
11281
11282   // Check for array bounds violations for both sides of the BinaryOperator
11283   CheckArrayAccess(LHS.get());
11284   CheckArrayAccess(RHS.get());
11285
11286   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11287     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11288                                                  &Context.Idents.get("object_setClass"),
11289                                                  SourceLocation(), LookupOrdinaryName);
11290     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11291       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11292       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11293       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11294       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11295       FixItHint::CreateInsertion(RHSLocEnd, ")");
11296     }
11297     else
11298       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11299   }
11300   else if (const ObjCIvarRefExpr *OIRE =
11301            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11302     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11303   
11304   if (CompResultTy.isNull())
11305     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11306                                         OK, OpLoc, FPFeatures);
11307   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11308       OK_ObjCProperty) {
11309     VK = VK_LValue;
11310     OK = LHS.get()->getObjectKind();
11311   }
11312   return new (Context) CompoundAssignOperator(
11313       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11314       OpLoc, FPFeatures);
11315 }
11316
11317 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11318 /// operators are mixed in a way that suggests that the programmer forgot that
11319 /// comparison operators have higher precedence. The most typical example of
11320 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11321 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11322                                       SourceLocation OpLoc, Expr *LHSExpr,
11323                                       Expr *RHSExpr) {
11324   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11325   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11326
11327   // Check that one of the sides is a comparison operator and the other isn't.
11328   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11329   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11330   if (isLeftComp == isRightComp)
11331     return;
11332
11333   // Bitwise operations are sometimes used as eager logical ops.
11334   // Don't diagnose this.
11335   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11336   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11337   if (isLeftBitwise || isRightBitwise)
11338     return;
11339
11340   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11341                                                    OpLoc)
11342                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11343   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11344   SourceRange ParensRange = isLeftComp ?
11345       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11346     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11347
11348   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11349     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11350   SuggestParentheses(Self, OpLoc,
11351     Self.PDiag(diag::note_precedence_silence) << OpStr,
11352     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11353   SuggestParentheses(Self, OpLoc,
11354     Self.PDiag(diag::note_precedence_bitwise_first)
11355       << BinaryOperator::getOpcodeStr(Opc),
11356     ParensRange);
11357 }
11358
11359 /// \brief It accepts a '&&' expr that is inside a '||' one.
11360 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11361 /// in parentheses.
11362 static void
11363 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11364                                        BinaryOperator *Bop) {
11365   assert(Bop->getOpcode() == BO_LAnd);
11366   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11367       << Bop->getSourceRange() << OpLoc;
11368   SuggestParentheses(Self, Bop->getOperatorLoc(),
11369     Self.PDiag(diag::note_precedence_silence)
11370       << Bop->getOpcodeStr(),
11371     Bop->getSourceRange());
11372 }
11373
11374 /// \brief Returns true if the given expression can be evaluated as a constant
11375 /// 'true'.
11376 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11377   bool Res;
11378   return !E->isValueDependent() &&
11379          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11380 }
11381
11382 /// \brief Returns true if the given expression can be evaluated as a constant
11383 /// 'false'.
11384 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11385   bool Res;
11386   return !E->isValueDependent() &&
11387          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11388 }
11389
11390 /// \brief Look for '&&' in the left hand of a '||' expr.
11391 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11392                                              Expr *LHSExpr, Expr *RHSExpr) {
11393   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11394     if (Bop->getOpcode() == BO_LAnd) {
11395       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11396       if (EvaluatesAsFalse(S, RHSExpr))
11397         return;
11398       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11399       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11400         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11401     } else if (Bop->getOpcode() == BO_LOr) {
11402       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11403         // If it's "a || b && 1 || c" we didn't warn earlier for
11404         // "a || b && 1", but warn now.
11405         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11406           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11407       }
11408     }
11409   }
11410 }
11411
11412 /// \brief Look for '&&' in the right hand of a '||' expr.
11413 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11414                                              Expr *LHSExpr, Expr *RHSExpr) {
11415   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11416     if (Bop->getOpcode() == BO_LAnd) {
11417       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11418       if (EvaluatesAsFalse(S, LHSExpr))
11419         return;
11420       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11421       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11422         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11423     }
11424   }
11425 }
11426
11427 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11428 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11429 /// the '&' expression in parentheses.
11430 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11431                                          SourceLocation OpLoc, Expr *SubExpr) {
11432   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11433     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11434       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11435         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11436         << Bop->getSourceRange() << OpLoc;
11437       SuggestParentheses(S, Bop->getOperatorLoc(),
11438         S.PDiag(diag::note_precedence_silence)
11439           << Bop->getOpcodeStr(),
11440         Bop->getSourceRange());
11441     }
11442   }
11443 }
11444
11445 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11446                                     Expr *SubExpr, StringRef Shift) {
11447   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11448     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11449       StringRef Op = Bop->getOpcodeStr();
11450       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11451           << Bop->getSourceRange() << OpLoc << Shift << Op;
11452       SuggestParentheses(S, Bop->getOperatorLoc(),
11453           S.PDiag(diag::note_precedence_silence) << Op,
11454           Bop->getSourceRange());
11455     }
11456   }
11457 }
11458
11459 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11460                                  Expr *LHSExpr, Expr *RHSExpr) {
11461   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11462   if (!OCE)
11463     return;
11464
11465   FunctionDecl *FD = OCE->getDirectCallee();
11466   if (!FD || !FD->isOverloadedOperator())
11467     return;
11468
11469   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11470   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11471     return;
11472
11473   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11474       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11475       << (Kind == OO_LessLess);
11476   SuggestParentheses(S, OCE->getOperatorLoc(),
11477                      S.PDiag(diag::note_precedence_silence)
11478                          << (Kind == OO_LessLess ? "<<" : ">>"),
11479                      OCE->getSourceRange());
11480   SuggestParentheses(S, OpLoc,
11481                      S.PDiag(diag::note_evaluate_comparison_first),
11482                      SourceRange(OCE->getArg(1)->getLocStart(),
11483                                  RHSExpr->getLocEnd()));
11484 }
11485
11486 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11487 /// precedence.
11488 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11489                                     SourceLocation OpLoc, Expr *LHSExpr,
11490                                     Expr *RHSExpr){
11491   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11492   if (BinaryOperator::isBitwiseOp(Opc))
11493     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11494
11495   // Diagnose "arg1 & arg2 | arg3"
11496   if ((Opc == BO_Or || Opc == BO_Xor) &&
11497       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11498     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11499     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11500   }
11501
11502   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11503   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11504   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11505     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11506     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11507   }
11508
11509   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11510       || Opc == BO_Shr) {
11511     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11512     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11513     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11514   }
11515
11516   // Warn on overloaded shift operators and comparisons, such as:
11517   // cout << 5 == 4;
11518   if (BinaryOperator::isComparisonOp(Opc))
11519     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11520 }
11521
11522 // Binary Operators.  'Tok' is the token for the operator.
11523 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11524                             tok::TokenKind Kind,
11525                             Expr *LHSExpr, Expr *RHSExpr) {
11526   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11527   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11528   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11529
11530   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11531   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11532
11533   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11534 }
11535
11536 /// Build an overloaded binary operator expression in the given scope.
11537 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11538                                        BinaryOperatorKind Opc,
11539                                        Expr *LHS, Expr *RHS) {
11540   // Find all of the overloaded operators visible from this
11541   // point. We perform both an operator-name lookup from the local
11542   // scope and an argument-dependent lookup based on the types of
11543   // the arguments.
11544   UnresolvedSet<16> Functions;
11545   OverloadedOperatorKind OverOp
11546     = BinaryOperator::getOverloadedOperator(Opc);
11547   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11548     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11549                                    RHS->getType(), Functions);
11550
11551   // Build the (potentially-overloaded, potentially-dependent)
11552   // binary operation.
11553   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11554 }
11555
11556 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11557                             BinaryOperatorKind Opc,
11558                             Expr *LHSExpr, Expr *RHSExpr) {
11559   // We want to end up calling one of checkPseudoObjectAssignment
11560   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11561   // both expressions are overloadable or either is type-dependent),
11562   // or CreateBuiltinBinOp (in any other case).  We also want to get
11563   // any placeholder types out of the way.
11564
11565   // Handle pseudo-objects in the LHS.
11566   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11567     // Assignments with a pseudo-object l-value need special analysis.
11568     if (pty->getKind() == BuiltinType::PseudoObject &&
11569         BinaryOperator::isAssignmentOp(Opc))
11570       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11571
11572     // Don't resolve overloads if the other type is overloadable.
11573     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11574       // We can't actually test that if we still have a placeholder,
11575       // though.  Fortunately, none of the exceptions we see in that
11576       // code below are valid when the LHS is an overload set.  Note
11577       // that an overload set can be dependently-typed, but it never
11578       // instantiates to having an overloadable type.
11579       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11580       if (resolvedRHS.isInvalid()) return ExprError();
11581       RHSExpr = resolvedRHS.get();
11582
11583       if (RHSExpr->isTypeDependent() ||
11584           RHSExpr->getType()->isOverloadableType())
11585         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11586     }
11587         
11588     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11589     if (LHS.isInvalid()) return ExprError();
11590     LHSExpr = LHS.get();
11591   }
11592
11593   // Handle pseudo-objects in the RHS.
11594   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11595     // An overload in the RHS can potentially be resolved by the type
11596     // being assigned to.
11597     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11598       if (getLangOpts().CPlusPlus &&
11599           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11600            LHSExpr->getType()->isOverloadableType()))
11601         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11602
11603       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11604     }
11605
11606     // Don't resolve overloads if the other type is overloadable.
11607     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11608         LHSExpr->getType()->isOverloadableType())
11609       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11610
11611     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11612     if (!resolvedRHS.isUsable()) return ExprError();
11613     RHSExpr = resolvedRHS.get();
11614   }
11615
11616   if (getLangOpts().CPlusPlus) {
11617     // If either expression is type-dependent, always build an
11618     // overloaded op.
11619     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11620       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11621
11622     // Otherwise, build an overloaded op if either expression has an
11623     // overloadable type.
11624     if (LHSExpr->getType()->isOverloadableType() ||
11625         RHSExpr->getType()->isOverloadableType())
11626       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11627   }
11628
11629   // Build a built-in binary operation.
11630   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11631 }
11632
11633 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11634                                       UnaryOperatorKind Opc,
11635                                       Expr *InputExpr) {
11636   ExprResult Input = InputExpr;
11637   ExprValueKind VK = VK_RValue;
11638   ExprObjectKind OK = OK_Ordinary;
11639   QualType resultType;
11640   if (getLangOpts().OpenCL) {
11641     QualType Ty = InputExpr->getType();
11642     // The only legal unary operation for atomics is '&'.
11643     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11644     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11645     // only with a builtin functions and therefore should be disallowed here.
11646         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11647         || Ty->isBlockPointerType())) {
11648       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11649                        << InputExpr->getType()
11650                        << Input.get()->getSourceRange());
11651     }
11652   }
11653   switch (Opc) {
11654   case UO_PreInc:
11655   case UO_PreDec:
11656   case UO_PostInc:
11657   case UO_PostDec:
11658     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11659                                                 OpLoc,
11660                                                 Opc == UO_PreInc ||
11661                                                 Opc == UO_PostInc,
11662                                                 Opc == UO_PreInc ||
11663                                                 Opc == UO_PreDec);
11664     break;
11665   case UO_AddrOf:
11666     resultType = CheckAddressOfOperand(Input, OpLoc);
11667     RecordModifiableNonNullParam(*this, InputExpr);
11668     break;
11669   case UO_Deref: {
11670     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11671     if (Input.isInvalid()) return ExprError();
11672     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11673     break;
11674   }
11675   case UO_Plus:
11676   case UO_Minus:
11677     Input = UsualUnaryConversions(Input.get());
11678     if (Input.isInvalid()) return ExprError();
11679     resultType = Input.get()->getType();
11680     if (resultType->isDependentType())
11681       break;
11682     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11683       break;
11684     else if (resultType->isVectorType() &&
11685              // The z vector extensions don't allow + or - with bool vectors.
11686              (!Context.getLangOpts().ZVector ||
11687               resultType->getAs<VectorType>()->getVectorKind() !=
11688               VectorType::AltiVecBool))
11689       break;
11690     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11691              Opc == UO_Plus &&
11692              resultType->isPointerType())
11693       break;
11694
11695     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11696       << resultType << Input.get()->getSourceRange());
11697
11698   case UO_Not: // bitwise complement
11699     Input = UsualUnaryConversions(Input.get());
11700     if (Input.isInvalid())
11701       return ExprError();
11702     resultType = Input.get()->getType();
11703     if (resultType->isDependentType())
11704       break;
11705     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11706     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11707       // C99 does not support '~' for complex conjugation.
11708       Diag(OpLoc, diag::ext_integer_complement_complex)
11709           << resultType << Input.get()->getSourceRange();
11710     else if (resultType->hasIntegerRepresentation())
11711       break;
11712     else if (resultType->isExtVectorType()) {
11713       if (Context.getLangOpts().OpenCL) {
11714         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11715         // on vector float types.
11716         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11717         if (!T->isIntegerType())
11718           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11719                            << resultType << Input.get()->getSourceRange());
11720       }
11721       break;
11722     } else {
11723       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11724                        << resultType << Input.get()->getSourceRange());
11725     }
11726     break;
11727
11728   case UO_LNot: // logical negation
11729     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11730     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11731     if (Input.isInvalid()) return ExprError();
11732     resultType = Input.get()->getType();
11733
11734     // Though we still have to promote half FP to float...
11735     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11736       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11737       resultType = Context.FloatTy;
11738     }
11739
11740     if (resultType->isDependentType())
11741       break;
11742     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11743       // C99 6.5.3.3p1: ok, fallthrough;
11744       if (Context.getLangOpts().CPlusPlus) {
11745         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11746         // operand contextually converted to bool.
11747         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11748                                   ScalarTypeToBooleanCastKind(resultType));
11749       } else if (Context.getLangOpts().OpenCL &&
11750                  Context.getLangOpts().OpenCLVersion < 120) {
11751         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11752         // operate on scalar float types.
11753         if (!resultType->isIntegerType() && !resultType->isPointerType())
11754           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11755                            << resultType << Input.get()->getSourceRange());
11756       }
11757     } else if (resultType->isExtVectorType()) {
11758       if (Context.getLangOpts().OpenCL &&
11759           Context.getLangOpts().OpenCLVersion < 120) {
11760         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11761         // operate on vector float types.
11762         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11763         if (!T->isIntegerType())
11764           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11765                            << resultType << Input.get()->getSourceRange());
11766       }
11767       // Vector logical not returns the signed variant of the operand type.
11768       resultType = GetSignedVectorType(resultType);
11769       break;
11770     } else {
11771       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11772         << resultType << Input.get()->getSourceRange());
11773     }
11774     
11775     // LNot always has type int. C99 6.5.3.3p5.
11776     // In C++, it's bool. C++ 5.3.1p8
11777     resultType = Context.getLogicalOperationType();
11778     break;
11779   case UO_Real:
11780   case UO_Imag:
11781     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11782     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11783     // complex l-values to ordinary l-values and all other values to r-values.
11784     if (Input.isInvalid()) return ExprError();
11785     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11786       if (Input.get()->getValueKind() != VK_RValue &&
11787           Input.get()->getObjectKind() == OK_Ordinary)
11788         VK = Input.get()->getValueKind();
11789     } else if (!getLangOpts().CPlusPlus) {
11790       // In C, a volatile scalar is read by __imag. In C++, it is not.
11791       Input = DefaultLvalueConversion(Input.get());
11792     }
11793     break;
11794   case UO_Extension:
11795   case UO_Coawait:
11796     resultType = Input.get()->getType();
11797     VK = Input.get()->getValueKind();
11798     OK = Input.get()->getObjectKind();
11799     break;
11800   }
11801   if (resultType.isNull() || Input.isInvalid())
11802     return ExprError();
11803
11804   // Check for array bounds violations in the operand of the UnaryOperator,
11805   // except for the '*' and '&' operators that have to be handled specially
11806   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11807   // that are explicitly defined as valid by the standard).
11808   if (Opc != UO_AddrOf && Opc != UO_Deref)
11809     CheckArrayAccess(Input.get());
11810
11811   return new (Context)
11812       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11813 }
11814
11815 /// \brief Determine whether the given expression is a qualified member
11816 /// access expression, of a form that could be turned into a pointer to member
11817 /// with the address-of operator.
11818 static bool isQualifiedMemberAccess(Expr *E) {
11819   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11820     if (!DRE->getQualifier())
11821       return false;
11822     
11823     ValueDecl *VD = DRE->getDecl();
11824     if (!VD->isCXXClassMember())
11825       return false;
11826     
11827     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11828       return true;
11829     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11830       return Method->isInstance();
11831       
11832     return false;
11833   }
11834   
11835   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11836     if (!ULE->getQualifier())
11837       return false;
11838     
11839     for (NamedDecl *D : ULE->decls()) {
11840       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11841         if (Method->isInstance())
11842           return true;
11843       } else {
11844         // Overload set does not contain methods.
11845         break;
11846       }
11847     }
11848     
11849     return false;
11850   }
11851   
11852   return false;
11853 }
11854
11855 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11856                               UnaryOperatorKind Opc, Expr *Input) {
11857   // First things first: handle placeholders so that the
11858   // overloaded-operator check considers the right type.
11859   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11860     // Increment and decrement of pseudo-object references.
11861     if (pty->getKind() == BuiltinType::PseudoObject &&
11862         UnaryOperator::isIncrementDecrementOp(Opc))
11863       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11864
11865     // extension is always a builtin operator.
11866     if (Opc == UO_Extension)
11867       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11868
11869     // & gets special logic for several kinds of placeholder.
11870     // The builtin code knows what to do.
11871     if (Opc == UO_AddrOf &&
11872         (pty->getKind() == BuiltinType::Overload ||
11873          pty->getKind() == BuiltinType::UnknownAny ||
11874          pty->getKind() == BuiltinType::BoundMember))
11875       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11876
11877     // Anything else needs to be handled now.
11878     ExprResult Result = CheckPlaceholderExpr(Input);
11879     if (Result.isInvalid()) return ExprError();
11880     Input = Result.get();
11881   }
11882
11883   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11884       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11885       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11886     // Find all of the overloaded operators visible from this
11887     // point. We perform both an operator-name lookup from the local
11888     // scope and an argument-dependent lookup based on the types of
11889     // the arguments.
11890     UnresolvedSet<16> Functions;
11891     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11892     if (S && OverOp != OO_None)
11893       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11894                                    Functions);
11895
11896     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11897   }
11898
11899   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11900 }
11901
11902 // Unary Operators.  'Tok' is the token for the operator.
11903 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11904                               tok::TokenKind Op, Expr *Input) {
11905   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11906 }
11907
11908 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11909 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11910                                 LabelDecl *TheDecl) {
11911   TheDecl->markUsed(Context);
11912   // Create the AST node.  The address of a label always has type 'void*'.
11913   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11914                                      Context.getPointerType(Context.VoidTy));
11915 }
11916
11917 /// Given the last statement in a statement-expression, check whether
11918 /// the result is a producing expression (like a call to an
11919 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11920 /// release out of the full-expression.  Otherwise, return null.
11921 /// Cannot fail.
11922 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11923   // Should always be wrapped with one of these.
11924   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11925   if (!cleanups) return nullptr;
11926
11927   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11928   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11929     return nullptr;
11930
11931   // Splice out the cast.  This shouldn't modify any interesting
11932   // features of the statement.
11933   Expr *producer = cast->getSubExpr();
11934   assert(producer->getType() == cast->getType());
11935   assert(producer->getValueKind() == cast->getValueKind());
11936   cleanups->setSubExpr(producer);
11937   return cleanups;
11938 }
11939
11940 void Sema::ActOnStartStmtExpr() {
11941   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11942 }
11943
11944 void Sema::ActOnStmtExprError() {
11945   // Note that function is also called by TreeTransform when leaving a
11946   // StmtExpr scope without rebuilding anything.
11947
11948   DiscardCleanupsInEvaluationContext();
11949   PopExpressionEvaluationContext();
11950 }
11951
11952 ExprResult
11953 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11954                     SourceLocation RPLoc) { // "({..})"
11955   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11956   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11957
11958   if (hasAnyUnrecoverableErrorsInThisFunction())
11959     DiscardCleanupsInEvaluationContext();
11960   assert(!Cleanup.exprNeedsCleanups() &&
11961          "cleanups within StmtExpr not correctly bound!");
11962   PopExpressionEvaluationContext();
11963
11964   // FIXME: there are a variety of strange constraints to enforce here, for
11965   // example, it is not possible to goto into a stmt expression apparently.
11966   // More semantic analysis is needed.
11967
11968   // If there are sub-stmts in the compound stmt, take the type of the last one
11969   // as the type of the stmtexpr.
11970   QualType Ty = Context.VoidTy;
11971   bool StmtExprMayBindToTemp = false;
11972   if (!Compound->body_empty()) {
11973     Stmt *LastStmt = Compound->body_back();
11974     LabelStmt *LastLabelStmt = nullptr;
11975     // If LastStmt is a label, skip down through into the body.
11976     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11977       LastLabelStmt = Label;
11978       LastStmt = Label->getSubStmt();
11979     }
11980
11981     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11982       // Do function/array conversion on the last expression, but not
11983       // lvalue-to-rvalue.  However, initialize an unqualified type.
11984       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11985       if (LastExpr.isInvalid())
11986         return ExprError();
11987       Ty = LastExpr.get()->getType().getUnqualifiedType();
11988
11989       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11990         // In ARC, if the final expression ends in a consume, splice
11991         // the consume out and bind it later.  In the alternate case
11992         // (when dealing with a retainable type), the result
11993         // initialization will create a produce.  In both cases the
11994         // result will be +1, and we'll need to balance that out with
11995         // a bind.
11996         if (Expr *rebuiltLastStmt
11997               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11998           LastExpr = rebuiltLastStmt;
11999         } else {
12000           LastExpr = PerformCopyInitialization(
12001                             InitializedEntity::InitializeResult(LPLoc, 
12002                                                                 Ty,
12003                                                                 false),
12004                                                    SourceLocation(),
12005                                                LastExpr);
12006         }
12007
12008         if (LastExpr.isInvalid())
12009           return ExprError();
12010         if (LastExpr.get() != nullptr) {
12011           if (!LastLabelStmt)
12012             Compound->setLastStmt(LastExpr.get());
12013           else
12014             LastLabelStmt->setSubStmt(LastExpr.get());
12015           StmtExprMayBindToTemp = true;
12016         }
12017       }
12018     }
12019   }
12020
12021   // FIXME: Check that expression type is complete/non-abstract; statement
12022   // expressions are not lvalues.
12023   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12024   if (StmtExprMayBindToTemp)
12025     return MaybeBindToTemporary(ResStmtExpr);
12026   return ResStmtExpr;
12027 }
12028
12029 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12030                                       TypeSourceInfo *TInfo,
12031                                       ArrayRef<OffsetOfComponent> Components,
12032                                       SourceLocation RParenLoc) {
12033   QualType ArgTy = TInfo->getType();
12034   bool Dependent = ArgTy->isDependentType();
12035   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12036   
12037   // We must have at least one component that refers to the type, and the first
12038   // one is known to be a field designator.  Verify that the ArgTy represents
12039   // a struct/union/class.
12040   if (!Dependent && !ArgTy->isRecordType())
12041     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
12042                        << ArgTy << TypeRange);
12043   
12044   // Type must be complete per C99 7.17p3 because a declaring a variable
12045   // with an incomplete type would be ill-formed.
12046   if (!Dependent 
12047       && RequireCompleteType(BuiltinLoc, ArgTy,
12048                              diag::err_offsetof_incomplete_type, TypeRange))
12049     return ExprError();
12050   
12051   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12052   // GCC extension, diagnose them.
12053   // FIXME: This diagnostic isn't actually visible because the location is in
12054   // a system header!
12055   if (Components.size() != 1)
12056     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12057       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12058   
12059   bool DidWarnAboutNonPOD = false;
12060   QualType CurrentType = ArgTy;
12061   SmallVector<OffsetOfNode, 4> Comps;
12062   SmallVector<Expr*, 4> Exprs;
12063   for (const OffsetOfComponent &OC : Components) {
12064     if (OC.isBrackets) {
12065       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12066       if (!CurrentType->isDependentType()) {
12067         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12068         if(!AT)
12069           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12070                            << CurrentType);
12071         CurrentType = AT->getElementType();
12072       } else
12073         CurrentType = Context.DependentTy;
12074       
12075       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12076       if (IdxRval.isInvalid())
12077         return ExprError();
12078       Expr *Idx = IdxRval.get();
12079
12080       // The expression must be an integral expression.
12081       // FIXME: An integral constant expression?
12082       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12083           !Idx->getType()->isIntegerType())
12084         return ExprError(Diag(Idx->getLocStart(),
12085                               diag::err_typecheck_subscript_not_integer)
12086                          << Idx->getSourceRange());
12087
12088       // Record this array index.
12089       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12090       Exprs.push_back(Idx);
12091       continue;
12092     }
12093     
12094     // Offset of a field.
12095     if (CurrentType->isDependentType()) {
12096       // We have the offset of a field, but we can't look into the dependent
12097       // type. Just record the identifier of the field.
12098       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12099       CurrentType = Context.DependentTy;
12100       continue;
12101     }
12102     
12103     // We need to have a complete type to look into.
12104     if (RequireCompleteType(OC.LocStart, CurrentType,
12105                             diag::err_offsetof_incomplete_type))
12106       return ExprError();
12107     
12108     // Look for the designated field.
12109     const RecordType *RC = CurrentType->getAs<RecordType>();
12110     if (!RC) 
12111       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12112                        << CurrentType);
12113     RecordDecl *RD = RC->getDecl();
12114     
12115     // C++ [lib.support.types]p5:
12116     //   The macro offsetof accepts a restricted set of type arguments in this
12117     //   International Standard. type shall be a POD structure or a POD union
12118     //   (clause 9).
12119     // C++11 [support.types]p4:
12120     //   If type is not a standard-layout class (Clause 9), the results are
12121     //   undefined.
12122     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12123       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12124       unsigned DiagID =
12125         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12126                             : diag::ext_offsetof_non_pod_type;
12127
12128       if (!IsSafe && !DidWarnAboutNonPOD &&
12129           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12130                               PDiag(DiagID)
12131                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12132                               << CurrentType))
12133         DidWarnAboutNonPOD = true;
12134     }
12135     
12136     // Look for the field.
12137     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12138     LookupQualifiedName(R, RD);
12139     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12140     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12141     if (!MemberDecl) {
12142       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12143         MemberDecl = IndirectMemberDecl->getAnonField();
12144     }
12145
12146     if (!MemberDecl)
12147       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12148                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
12149                                                               OC.LocEnd));
12150     
12151     // C99 7.17p3:
12152     //   (If the specified member is a bit-field, the behavior is undefined.)
12153     //
12154     // We diagnose this as an error.
12155     if (MemberDecl->isBitField()) {
12156       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12157         << MemberDecl->getDeclName()
12158         << SourceRange(BuiltinLoc, RParenLoc);
12159       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12160       return ExprError();
12161     }
12162
12163     RecordDecl *Parent = MemberDecl->getParent();
12164     if (IndirectMemberDecl)
12165       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12166
12167     // If the member was found in a base class, introduce OffsetOfNodes for
12168     // the base class indirections.
12169     CXXBasePaths Paths;
12170     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12171                       Paths)) {
12172       if (Paths.getDetectedVirtual()) {
12173         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12174           << MemberDecl->getDeclName()
12175           << SourceRange(BuiltinLoc, RParenLoc);
12176         return ExprError();
12177       }
12178
12179       CXXBasePath &Path = Paths.front();
12180       for (const CXXBasePathElement &B : Path)
12181         Comps.push_back(OffsetOfNode(B.Base));
12182     }
12183
12184     if (IndirectMemberDecl) {
12185       for (auto *FI : IndirectMemberDecl->chain()) {
12186         assert(isa<FieldDecl>(FI));
12187         Comps.push_back(OffsetOfNode(OC.LocStart,
12188                                      cast<FieldDecl>(FI), OC.LocEnd));
12189       }
12190     } else
12191       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12192
12193     CurrentType = MemberDecl->getType().getNonReferenceType(); 
12194   }
12195   
12196   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12197                               Comps, Exprs, RParenLoc);
12198 }
12199
12200 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12201                                       SourceLocation BuiltinLoc,
12202                                       SourceLocation TypeLoc,
12203                                       ParsedType ParsedArgTy,
12204                                       ArrayRef<OffsetOfComponent> Components,
12205                                       SourceLocation RParenLoc) {
12206   
12207   TypeSourceInfo *ArgTInfo;
12208   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12209   if (ArgTy.isNull())
12210     return ExprError();
12211
12212   if (!ArgTInfo)
12213     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12214
12215   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12216 }
12217
12218
12219 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12220                                  Expr *CondExpr,
12221                                  Expr *LHSExpr, Expr *RHSExpr,
12222                                  SourceLocation RPLoc) {
12223   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12224
12225   ExprValueKind VK = VK_RValue;
12226   ExprObjectKind OK = OK_Ordinary;
12227   QualType resType;
12228   bool ValueDependent = false;
12229   bool CondIsTrue = false;
12230   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12231     resType = Context.DependentTy;
12232     ValueDependent = true;
12233   } else {
12234     // The conditional expression is required to be a constant expression.
12235     llvm::APSInt condEval(32);
12236     ExprResult CondICE
12237       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12238           diag::err_typecheck_choose_expr_requires_constant, false);
12239     if (CondICE.isInvalid())
12240       return ExprError();
12241     CondExpr = CondICE.get();
12242     CondIsTrue = condEval.getZExtValue();
12243
12244     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12245     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12246
12247     resType = ActiveExpr->getType();
12248     ValueDependent = ActiveExpr->isValueDependent();
12249     VK = ActiveExpr->getValueKind();
12250     OK = ActiveExpr->getObjectKind();
12251   }
12252
12253   return new (Context)
12254       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12255                  CondIsTrue, resType->isDependentType(), ValueDependent);
12256 }
12257
12258 //===----------------------------------------------------------------------===//
12259 // Clang Extensions.
12260 //===----------------------------------------------------------------------===//
12261
12262 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12263 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12264   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12265
12266   if (LangOpts.CPlusPlus) {
12267     Decl *ManglingContextDecl;
12268     if (MangleNumberingContext *MCtx =
12269             getCurrentMangleNumberContext(Block->getDeclContext(),
12270                                           ManglingContextDecl)) {
12271       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12272       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12273     }
12274   }
12275
12276   PushBlockScope(CurScope, Block);
12277   CurContext->addDecl(Block);
12278   if (CurScope)
12279     PushDeclContext(CurScope, Block);
12280   else
12281     CurContext = Block;
12282
12283   getCurBlock()->HasImplicitReturnType = true;
12284
12285   // Enter a new evaluation context to insulate the block from any
12286   // cleanups from the enclosing full-expression.
12287   PushExpressionEvaluationContext(
12288       ExpressionEvaluationContext::PotentiallyEvaluated);
12289 }
12290
12291 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12292                                Scope *CurScope) {
12293   assert(ParamInfo.getIdentifier() == nullptr &&
12294          "block-id should have no identifier!");
12295   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12296   BlockScopeInfo *CurBlock = getCurBlock();
12297
12298   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12299   QualType T = Sig->getType();
12300
12301   // FIXME: We should allow unexpanded parameter packs here, but that would,
12302   // in turn, make the block expression contain unexpanded parameter packs.
12303   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12304     // Drop the parameters.
12305     FunctionProtoType::ExtProtoInfo EPI;
12306     EPI.HasTrailingReturn = false;
12307     EPI.TypeQuals |= DeclSpec::TQ_const;
12308     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12309     Sig = Context.getTrivialTypeSourceInfo(T);
12310   }
12311   
12312   // GetTypeForDeclarator always produces a function type for a block
12313   // literal signature.  Furthermore, it is always a FunctionProtoType
12314   // unless the function was written with a typedef.
12315   assert(T->isFunctionType() &&
12316          "GetTypeForDeclarator made a non-function block signature");
12317
12318   // Look for an explicit signature in that function type.
12319   FunctionProtoTypeLoc ExplicitSignature;
12320
12321   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12322   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12323
12324     // Check whether that explicit signature was synthesized by
12325     // GetTypeForDeclarator.  If so, don't save that as part of the
12326     // written signature.
12327     if (ExplicitSignature.getLocalRangeBegin() ==
12328         ExplicitSignature.getLocalRangeEnd()) {
12329       // This would be much cheaper if we stored TypeLocs instead of
12330       // TypeSourceInfos.
12331       TypeLoc Result = ExplicitSignature.getReturnLoc();
12332       unsigned Size = Result.getFullDataSize();
12333       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12334       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12335
12336       ExplicitSignature = FunctionProtoTypeLoc();
12337     }
12338   }
12339
12340   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12341   CurBlock->FunctionType = T;
12342
12343   const FunctionType *Fn = T->getAs<FunctionType>();
12344   QualType RetTy = Fn->getReturnType();
12345   bool isVariadic =
12346     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12347
12348   CurBlock->TheDecl->setIsVariadic(isVariadic);
12349
12350   // Context.DependentTy is used as a placeholder for a missing block
12351   // return type.  TODO:  what should we do with declarators like:
12352   //   ^ * { ... }
12353   // If the answer is "apply template argument deduction"....
12354   if (RetTy != Context.DependentTy) {
12355     CurBlock->ReturnType = RetTy;
12356     CurBlock->TheDecl->setBlockMissingReturnType(false);
12357     CurBlock->HasImplicitReturnType = false;
12358   }
12359
12360   // Push block parameters from the declarator if we had them.
12361   SmallVector<ParmVarDecl*, 8> Params;
12362   if (ExplicitSignature) {
12363     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12364       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12365       if (Param->getIdentifier() == nullptr &&
12366           !Param->isImplicit() &&
12367           !Param->isInvalidDecl() &&
12368           !getLangOpts().CPlusPlus)
12369         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12370       Params.push_back(Param);
12371     }
12372
12373   // Fake up parameter variables if we have a typedef, like
12374   //   ^ fntype { ... }
12375   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12376     for (const auto &I : Fn->param_types()) {
12377       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12378           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12379       Params.push_back(Param);
12380     }
12381   }
12382
12383   // Set the parameters on the block decl.
12384   if (!Params.empty()) {
12385     CurBlock->TheDecl->setParams(Params);
12386     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12387                              /*CheckParameterNames=*/false);
12388   }
12389   
12390   // Finally we can process decl attributes.
12391   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12392
12393   // Put the parameter variables in scope.
12394   for (auto AI : CurBlock->TheDecl->parameters()) {
12395     AI->setOwningFunction(CurBlock->TheDecl);
12396
12397     // If this has an identifier, add it to the scope stack.
12398     if (AI->getIdentifier()) {
12399       CheckShadow(CurBlock->TheScope, AI);
12400
12401       PushOnScopeChains(AI, CurBlock->TheScope);
12402     }
12403   }
12404 }
12405
12406 /// ActOnBlockError - If there is an error parsing a block, this callback
12407 /// is invoked to pop the information about the block from the action impl.
12408 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12409   // Leave the expression-evaluation context.
12410   DiscardCleanupsInEvaluationContext();
12411   PopExpressionEvaluationContext();
12412
12413   // Pop off CurBlock, handle nested blocks.
12414   PopDeclContext();
12415   PopFunctionScopeInfo();
12416 }
12417
12418 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12419 /// literal was successfully completed.  ^(int x){...}
12420 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12421                                     Stmt *Body, Scope *CurScope) {
12422   // If blocks are disabled, emit an error.
12423   if (!LangOpts.Blocks)
12424     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12425
12426   // Leave the expression-evaluation context.
12427   if (hasAnyUnrecoverableErrorsInThisFunction())
12428     DiscardCleanupsInEvaluationContext();
12429   assert(!Cleanup.exprNeedsCleanups() &&
12430          "cleanups within block not correctly bound!");
12431   PopExpressionEvaluationContext();
12432
12433   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12434
12435   if (BSI->HasImplicitReturnType)
12436     deduceClosureReturnType(*BSI);
12437
12438   PopDeclContext();
12439
12440   QualType RetTy = Context.VoidTy;
12441   if (!BSI->ReturnType.isNull())
12442     RetTy = BSI->ReturnType;
12443
12444   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12445   QualType BlockTy;
12446
12447   // Set the captured variables on the block.
12448   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12449   SmallVector<BlockDecl::Capture, 4> Captures;
12450   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12451     if (Cap.isThisCapture())
12452       continue;
12453     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12454                               Cap.isNested(), Cap.getInitExpr());
12455     Captures.push_back(NewCap);
12456   }
12457   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12458
12459   // If the user wrote a function type in some form, try to use that.
12460   if (!BSI->FunctionType.isNull()) {
12461     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12462
12463     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12464     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12465     
12466     // Turn protoless block types into nullary block types.
12467     if (isa<FunctionNoProtoType>(FTy)) {
12468       FunctionProtoType::ExtProtoInfo EPI;
12469       EPI.ExtInfo = Ext;
12470       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12471
12472     // Otherwise, if we don't need to change anything about the function type,
12473     // preserve its sugar structure.
12474     } else if (FTy->getReturnType() == RetTy &&
12475                (!NoReturn || FTy->getNoReturnAttr())) {
12476       BlockTy = BSI->FunctionType;
12477
12478     // Otherwise, make the minimal modifications to the function type.
12479     } else {
12480       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12481       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12482       EPI.TypeQuals = 0; // FIXME: silently?
12483       EPI.ExtInfo = Ext;
12484       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12485     }
12486
12487   // If we don't have a function type, just build one from nothing.
12488   } else {
12489     FunctionProtoType::ExtProtoInfo EPI;
12490     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12491     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12492   }
12493
12494   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12495   BlockTy = Context.getBlockPointerType(BlockTy);
12496
12497   // If needed, diagnose invalid gotos and switches in the block.
12498   if (getCurFunction()->NeedsScopeChecking() &&
12499       !PP.isCodeCompletionEnabled())
12500     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12501
12502   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12503
12504   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12505     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12506
12507   // Try to apply the named return value optimization. We have to check again
12508   // if we can do this, though, because blocks keep return statements around
12509   // to deduce an implicit return type.
12510   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12511       !BSI->TheDecl->isDependentContext())
12512     computeNRVO(Body, BSI);
12513   
12514   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12515   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12516   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12517
12518   // If the block isn't obviously global, i.e. it captures anything at
12519   // all, then we need to do a few things in the surrounding context:
12520   if (Result->getBlockDecl()->hasCaptures()) {
12521     // First, this expression has a new cleanup object.
12522     ExprCleanupObjects.push_back(Result->getBlockDecl());
12523     Cleanup.setExprNeedsCleanups(true);
12524
12525     // It also gets a branch-protected scope if any of the captured
12526     // variables needs destruction.
12527     for (const auto &CI : Result->getBlockDecl()->captures()) {
12528       const VarDecl *var = CI.getVariable();
12529       if (var->getType().isDestructedType() != QualType::DK_none) {
12530         getCurFunction()->setHasBranchProtectedScope();
12531         break;
12532       }
12533     }
12534   }
12535
12536   return Result;
12537 }
12538
12539 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12540                             SourceLocation RPLoc) {
12541   TypeSourceInfo *TInfo;
12542   GetTypeFromParser(Ty, &TInfo);
12543   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12544 }
12545
12546 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12547                                 Expr *E, TypeSourceInfo *TInfo,
12548                                 SourceLocation RPLoc) {
12549   Expr *OrigExpr = E;
12550   bool IsMS = false;
12551
12552   // CUDA device code does not support varargs.
12553   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12554     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12555       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12556       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12557         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12558     }
12559   }
12560
12561   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12562   // as Microsoft ABI on an actual Microsoft platform, where
12563   // __builtin_ms_va_list and __builtin_va_list are the same.)
12564   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12565       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12566     QualType MSVaListType = Context.getBuiltinMSVaListType();
12567     if (Context.hasSameType(MSVaListType, E->getType())) {
12568       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12569         return ExprError();
12570       IsMS = true;
12571     }
12572   }
12573
12574   // Get the va_list type
12575   QualType VaListType = Context.getBuiltinVaListType();
12576   if (!IsMS) {
12577     if (VaListType->isArrayType()) {
12578       // Deal with implicit array decay; for example, on x86-64,
12579       // va_list is an array, but it's supposed to decay to
12580       // a pointer for va_arg.
12581       VaListType = Context.getArrayDecayedType(VaListType);
12582       // Make sure the input expression also decays appropriately.
12583       ExprResult Result = UsualUnaryConversions(E);
12584       if (Result.isInvalid())
12585         return ExprError();
12586       E = Result.get();
12587     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12588       // If va_list is a record type and we are compiling in C++ mode,
12589       // check the argument using reference binding.
12590       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12591           Context, Context.getLValueReferenceType(VaListType), false);
12592       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12593       if (Init.isInvalid())
12594         return ExprError();
12595       E = Init.getAs<Expr>();
12596     } else {
12597       // Otherwise, the va_list argument must be an l-value because
12598       // it is modified by va_arg.
12599       if (!E->isTypeDependent() &&
12600           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12601         return ExprError();
12602     }
12603   }
12604
12605   if (!IsMS && !E->isTypeDependent() &&
12606       !Context.hasSameType(VaListType, E->getType()))
12607     return ExprError(Diag(E->getLocStart(),
12608                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12609       << OrigExpr->getType() << E->getSourceRange());
12610
12611   if (!TInfo->getType()->isDependentType()) {
12612     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12613                             diag::err_second_parameter_to_va_arg_incomplete,
12614                             TInfo->getTypeLoc()))
12615       return ExprError();
12616
12617     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12618                                TInfo->getType(),
12619                                diag::err_second_parameter_to_va_arg_abstract,
12620                                TInfo->getTypeLoc()))
12621       return ExprError();
12622
12623     if (!TInfo->getType().isPODType(Context)) {
12624       Diag(TInfo->getTypeLoc().getBeginLoc(),
12625            TInfo->getType()->isObjCLifetimeType()
12626              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12627              : diag::warn_second_parameter_to_va_arg_not_pod)
12628         << TInfo->getType()
12629         << TInfo->getTypeLoc().getSourceRange();
12630     }
12631
12632     // Check for va_arg where arguments of the given type will be promoted
12633     // (i.e. this va_arg is guaranteed to have undefined behavior).
12634     QualType PromoteType;
12635     if (TInfo->getType()->isPromotableIntegerType()) {
12636       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12637       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12638         PromoteType = QualType();
12639     }
12640     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12641       PromoteType = Context.DoubleTy;
12642     if (!PromoteType.isNull())
12643       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12644                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12645                           << TInfo->getType()
12646                           << PromoteType
12647                           << TInfo->getTypeLoc().getSourceRange());
12648   }
12649
12650   QualType T = TInfo->getType().getNonLValueExprType(Context);
12651   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12652 }
12653
12654 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12655   // The type of __null will be int or long, depending on the size of
12656   // pointers on the target.
12657   QualType Ty;
12658   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12659   if (pw == Context.getTargetInfo().getIntWidth())
12660     Ty = Context.IntTy;
12661   else if (pw == Context.getTargetInfo().getLongWidth())
12662     Ty = Context.LongTy;
12663   else if (pw == Context.getTargetInfo().getLongLongWidth())
12664     Ty = Context.LongLongTy;
12665   else {
12666     llvm_unreachable("I don't know size of pointer!");
12667   }
12668
12669   return new (Context) GNUNullExpr(Ty, TokenLoc);
12670 }
12671
12672 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12673                                               bool Diagnose) {
12674   if (!getLangOpts().ObjC1)
12675     return false;
12676
12677   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12678   if (!PT)
12679     return false;
12680
12681   if (!PT->isObjCIdType()) {
12682     // Check if the destination is the 'NSString' interface.
12683     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12684     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12685       return false;
12686   }
12687   
12688   // Ignore any parens, implicit casts (should only be
12689   // array-to-pointer decays), and not-so-opaque values.  The last is
12690   // important for making this trigger for property assignments.
12691   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12692   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12693     if (OV->getSourceExpr())
12694       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12695
12696   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12697   if (!SL || !SL->isAscii())
12698     return false;
12699   if (Diagnose) {
12700     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12701       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12702     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12703   }
12704   return true;
12705 }
12706
12707 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12708                                               const Expr *SrcExpr) {
12709   if (!DstType->isFunctionPointerType() ||
12710       !SrcExpr->getType()->isFunctionType())
12711     return false;
12712
12713   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12714   if (!DRE)
12715     return false;
12716
12717   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12718   if (!FD)
12719     return false;
12720
12721   return !S.checkAddressOfFunctionIsAvailable(FD,
12722                                               /*Complain=*/true,
12723                                               SrcExpr->getLocStart());
12724 }
12725
12726 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12727                                     SourceLocation Loc,
12728                                     QualType DstType, QualType SrcType,
12729                                     Expr *SrcExpr, AssignmentAction Action,
12730                                     bool *Complained) {
12731   if (Complained)
12732     *Complained = false;
12733
12734   // Decode the result (notice that AST's are still created for extensions).
12735   bool CheckInferredResultType = false;
12736   bool isInvalid = false;
12737   unsigned DiagKind = 0;
12738   FixItHint Hint;
12739   ConversionFixItGenerator ConvHints;
12740   bool MayHaveConvFixit = false;
12741   bool MayHaveFunctionDiff = false;
12742   const ObjCInterfaceDecl *IFace = nullptr;
12743   const ObjCProtocolDecl *PDecl = nullptr;
12744
12745   switch (ConvTy) {
12746   case Compatible:
12747       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12748       return false;
12749
12750   case PointerToInt:
12751     DiagKind = diag::ext_typecheck_convert_pointer_int;
12752     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12753     MayHaveConvFixit = true;
12754     break;
12755   case IntToPointer:
12756     DiagKind = diag::ext_typecheck_convert_int_pointer;
12757     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12758     MayHaveConvFixit = true;
12759     break;
12760   case IncompatiblePointer:
12761     if (Action == AA_Passing_CFAudited)
12762       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12763     else if (SrcType->isFunctionPointerType() &&
12764              DstType->isFunctionPointerType())
12765       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12766     else
12767       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12768
12769     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12770       SrcType->isObjCObjectPointerType();
12771     if (Hint.isNull() && !CheckInferredResultType) {
12772       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12773     }
12774     else if (CheckInferredResultType) {
12775       SrcType = SrcType.getUnqualifiedType();
12776       DstType = DstType.getUnqualifiedType();
12777     }
12778     MayHaveConvFixit = true;
12779     break;
12780   case IncompatiblePointerSign:
12781     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12782     break;
12783   case FunctionVoidPointer:
12784     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12785     break;
12786   case IncompatiblePointerDiscardsQualifiers: {
12787     // Perform array-to-pointer decay if necessary.
12788     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12789
12790     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12791     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12792     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12793       DiagKind = diag::err_typecheck_incompatible_address_space;
12794       break;
12795
12796
12797     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12798       DiagKind = diag::err_typecheck_incompatible_ownership;
12799       break;
12800     }
12801
12802     llvm_unreachable("unknown error case for discarding qualifiers!");
12803     // fallthrough
12804   }
12805   case CompatiblePointerDiscardsQualifiers:
12806     // If the qualifiers lost were because we were applying the
12807     // (deprecated) C++ conversion from a string literal to a char*
12808     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12809     // Ideally, this check would be performed in
12810     // checkPointerTypesForAssignment. However, that would require a
12811     // bit of refactoring (so that the second argument is an
12812     // expression, rather than a type), which should be done as part
12813     // of a larger effort to fix checkPointerTypesForAssignment for
12814     // C++ semantics.
12815     if (getLangOpts().CPlusPlus &&
12816         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12817       return false;
12818     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12819     break;
12820   case IncompatibleNestedPointerQualifiers:
12821     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12822     break;
12823   case IntToBlockPointer:
12824     DiagKind = diag::err_int_to_block_pointer;
12825     break;
12826   case IncompatibleBlockPointer:
12827     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12828     break;
12829   case IncompatibleObjCQualifiedId: {
12830     if (SrcType->isObjCQualifiedIdType()) {
12831       const ObjCObjectPointerType *srcOPT =
12832                 SrcType->getAs<ObjCObjectPointerType>();
12833       for (auto *srcProto : srcOPT->quals()) {
12834         PDecl = srcProto;
12835         break;
12836       }
12837       if (const ObjCInterfaceType *IFaceT =
12838             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12839         IFace = IFaceT->getDecl();
12840     }
12841     else if (DstType->isObjCQualifiedIdType()) {
12842       const ObjCObjectPointerType *dstOPT =
12843         DstType->getAs<ObjCObjectPointerType>();
12844       for (auto *dstProto : dstOPT->quals()) {
12845         PDecl = dstProto;
12846         break;
12847       }
12848       if (const ObjCInterfaceType *IFaceT =
12849             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12850         IFace = IFaceT->getDecl();
12851     }
12852     DiagKind = diag::warn_incompatible_qualified_id;
12853     break;
12854   }
12855   case IncompatibleVectors:
12856     DiagKind = diag::warn_incompatible_vectors;
12857     break;
12858   case IncompatibleObjCWeakRef:
12859     DiagKind = diag::err_arc_weak_unavailable_assign;
12860     break;
12861   case Incompatible:
12862     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12863       if (Complained)
12864         *Complained = true;
12865       return true;
12866     }
12867
12868     DiagKind = diag::err_typecheck_convert_incompatible;
12869     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12870     MayHaveConvFixit = true;
12871     isInvalid = true;
12872     MayHaveFunctionDiff = true;
12873     break;
12874   }
12875
12876   QualType FirstType, SecondType;
12877   switch (Action) {
12878   case AA_Assigning:
12879   case AA_Initializing:
12880     // The destination type comes first.
12881     FirstType = DstType;
12882     SecondType = SrcType;
12883     break;
12884
12885   case AA_Returning:
12886   case AA_Passing:
12887   case AA_Passing_CFAudited:
12888   case AA_Converting:
12889   case AA_Sending:
12890   case AA_Casting:
12891     // The source type comes first.
12892     FirstType = SrcType;
12893     SecondType = DstType;
12894     break;
12895   }
12896
12897   PartialDiagnostic FDiag = PDiag(DiagKind);
12898   if (Action == AA_Passing_CFAudited)
12899     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12900   else
12901     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12902
12903   // If we can fix the conversion, suggest the FixIts.
12904   assert(ConvHints.isNull() || Hint.isNull());
12905   if (!ConvHints.isNull()) {
12906     for (FixItHint &H : ConvHints.Hints)
12907       FDiag << H;
12908   } else {
12909     FDiag << Hint;
12910   }
12911   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12912
12913   if (MayHaveFunctionDiff)
12914     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12915
12916   Diag(Loc, FDiag);
12917   if (DiagKind == diag::warn_incompatible_qualified_id &&
12918       PDecl && IFace && !IFace->hasDefinition())
12919       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12920         << IFace->getName() << PDecl->getName();
12921     
12922   if (SecondType == Context.OverloadTy)
12923     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12924                               FirstType, /*TakingAddress=*/true);
12925
12926   if (CheckInferredResultType)
12927     EmitRelatedResultTypeNote(SrcExpr);
12928
12929   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12930     EmitRelatedResultTypeNoteForReturn(DstType);
12931   
12932   if (Complained)
12933     *Complained = true;
12934   return isInvalid;
12935 }
12936
12937 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12938                                                  llvm::APSInt *Result) {
12939   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12940   public:
12941     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12942       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12943     }
12944   } Diagnoser;
12945   
12946   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12947 }
12948
12949 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12950                                                  llvm::APSInt *Result,
12951                                                  unsigned DiagID,
12952                                                  bool AllowFold) {
12953   class IDDiagnoser : public VerifyICEDiagnoser {
12954     unsigned DiagID;
12955     
12956   public:
12957     IDDiagnoser(unsigned DiagID)
12958       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12959     
12960     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12961       S.Diag(Loc, DiagID) << SR;
12962     }
12963   } Diagnoser(DiagID);
12964   
12965   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12966 }
12967
12968 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12969                                             SourceRange SR) {
12970   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12971 }
12972
12973 ExprResult
12974 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12975                                       VerifyICEDiagnoser &Diagnoser,
12976                                       bool AllowFold) {
12977   SourceLocation DiagLoc = E->getLocStart();
12978
12979   if (getLangOpts().CPlusPlus11) {
12980     // C++11 [expr.const]p5:
12981     //   If an expression of literal class type is used in a context where an
12982     //   integral constant expression is required, then that class type shall
12983     //   have a single non-explicit conversion function to an integral or
12984     //   unscoped enumeration type
12985     ExprResult Converted;
12986     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12987     public:
12988       CXX11ConvertDiagnoser(bool Silent)
12989           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12990                                 Silent, true) {}
12991
12992       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12993                                            QualType T) override {
12994         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12995       }
12996
12997       SemaDiagnosticBuilder diagnoseIncomplete(
12998           Sema &S, SourceLocation Loc, QualType T) override {
12999         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13000       }
13001
13002       SemaDiagnosticBuilder diagnoseExplicitConv(
13003           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13004         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13005       }
13006
13007       SemaDiagnosticBuilder noteExplicitConv(
13008           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13009         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13010                  << ConvTy->isEnumeralType() << ConvTy;
13011       }
13012
13013       SemaDiagnosticBuilder diagnoseAmbiguous(
13014           Sema &S, SourceLocation Loc, QualType T) override {
13015         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13016       }
13017
13018       SemaDiagnosticBuilder noteAmbiguous(
13019           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13020         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13021                  << ConvTy->isEnumeralType() << ConvTy;
13022       }
13023
13024       SemaDiagnosticBuilder diagnoseConversion(
13025           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13026         llvm_unreachable("conversion functions are permitted");
13027       }
13028     } ConvertDiagnoser(Diagnoser.Suppress);
13029
13030     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13031                                                     ConvertDiagnoser);
13032     if (Converted.isInvalid())
13033       return Converted;
13034     E = Converted.get();
13035     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13036       return ExprError();
13037   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13038     // An ICE must be of integral or unscoped enumeration type.
13039     if (!Diagnoser.Suppress)
13040       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13041     return ExprError();
13042   }
13043
13044   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13045   // in the non-ICE case.
13046   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13047     if (Result)
13048       *Result = E->EvaluateKnownConstInt(Context);
13049     return E;
13050   }
13051
13052   Expr::EvalResult EvalResult;
13053   SmallVector<PartialDiagnosticAt, 8> Notes;
13054   EvalResult.Diag = &Notes;
13055
13056   // Try to evaluate the expression, and produce diagnostics explaining why it's
13057   // not a constant expression as a side-effect.
13058   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13059                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13060
13061   // In C++11, we can rely on diagnostics being produced for any expression
13062   // which is not a constant expression. If no diagnostics were produced, then
13063   // this is a constant expression.
13064   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13065     if (Result)
13066       *Result = EvalResult.Val.getInt();
13067     return E;
13068   }
13069
13070   // If our only note is the usual "invalid subexpression" note, just point
13071   // the caret at its location rather than producing an essentially
13072   // redundant note.
13073   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13074         diag::note_invalid_subexpr_in_const_expr) {
13075     DiagLoc = Notes[0].first;
13076     Notes.clear();
13077   }
13078
13079   if (!Folded || !AllowFold) {
13080     if (!Diagnoser.Suppress) {
13081       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13082       for (const PartialDiagnosticAt &Note : Notes)
13083         Diag(Note.first, Note.second);
13084     }
13085
13086     return ExprError();
13087   }
13088
13089   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13090   for (const PartialDiagnosticAt &Note : Notes)
13091     Diag(Note.first, Note.second);
13092
13093   if (Result)
13094     *Result = EvalResult.Val.getInt();
13095   return E;
13096 }
13097
13098 namespace {
13099   // Handle the case where we conclude a expression which we speculatively
13100   // considered to be unevaluated is actually evaluated.
13101   class TransformToPE : public TreeTransform<TransformToPE> {
13102     typedef TreeTransform<TransformToPE> BaseTransform;
13103
13104   public:
13105     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13106
13107     // Make sure we redo semantic analysis
13108     bool AlwaysRebuild() { return true; }
13109
13110     // Make sure we handle LabelStmts correctly.
13111     // FIXME: This does the right thing, but maybe we need a more general
13112     // fix to TreeTransform?
13113     StmtResult TransformLabelStmt(LabelStmt *S) {
13114       S->getDecl()->setStmt(nullptr);
13115       return BaseTransform::TransformLabelStmt(S);
13116     }
13117
13118     // We need to special-case DeclRefExprs referring to FieldDecls which
13119     // are not part of a member pointer formation; normal TreeTransforming
13120     // doesn't catch this case because of the way we represent them in the AST.
13121     // FIXME: This is a bit ugly; is it really the best way to handle this
13122     // case?
13123     //
13124     // Error on DeclRefExprs referring to FieldDecls.
13125     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13126       if (isa<FieldDecl>(E->getDecl()) &&
13127           !SemaRef.isUnevaluatedContext())
13128         return SemaRef.Diag(E->getLocation(),
13129                             diag::err_invalid_non_static_member_use)
13130             << E->getDecl() << E->getSourceRange();
13131
13132       return BaseTransform::TransformDeclRefExpr(E);
13133     }
13134
13135     // Exception: filter out member pointer formation
13136     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13137       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13138         return E;
13139
13140       return BaseTransform::TransformUnaryOperator(E);
13141     }
13142
13143     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13144       // Lambdas never need to be transformed.
13145       return E;
13146     }
13147   };
13148 }
13149
13150 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13151   assert(isUnevaluatedContext() &&
13152          "Should only transform unevaluated expressions");
13153   ExprEvalContexts.back().Context =
13154       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13155   if (isUnevaluatedContext())
13156     return E;
13157   return TransformToPE(*this).TransformExpr(E);
13158 }
13159
13160 void
13161 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13162                                       Decl *LambdaContextDecl,
13163                                       bool IsDecltype) {
13164   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13165                                 LambdaContextDecl, IsDecltype);
13166   Cleanup.reset();
13167   if (!MaybeODRUseExprs.empty())
13168     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13169 }
13170
13171 void
13172 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13173                                       ReuseLambdaContextDecl_t,
13174                                       bool IsDecltype) {
13175   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13176   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13177 }
13178
13179 void Sema::PopExpressionEvaluationContext() {
13180   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13181   unsigned NumTypos = Rec.NumTypos;
13182
13183   if (!Rec.Lambdas.empty()) {
13184     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13185       unsigned D;
13186       if (Rec.isUnevaluated()) {
13187         // C++11 [expr.prim.lambda]p2:
13188         //   A lambda-expression shall not appear in an unevaluated operand
13189         //   (Clause 5).
13190         D = diag::err_lambda_unevaluated_operand;
13191       } else {
13192         // C++1y [expr.const]p2:
13193         //   A conditional-expression e is a core constant expression unless the
13194         //   evaluation of e, following the rules of the abstract machine, would
13195         //   evaluate [...] a lambda-expression.
13196         D = diag::err_lambda_in_constant_expression;
13197       }
13198
13199       // C++1z allows lambda expressions as core constant expressions.
13200       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13201       // 1607) from appearing within template-arguments and array-bounds that
13202       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13203       // unevaluated contexts) might lift some of these restrictions in a 
13204       // future version.
13205       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13206         for (const auto *L : Rec.Lambdas)
13207           Diag(L->getLocStart(), D);
13208     } else {
13209       // Mark the capture expressions odr-used. This was deferred
13210       // during lambda expression creation.
13211       for (auto *Lambda : Rec.Lambdas) {
13212         for (auto *C : Lambda->capture_inits())
13213           MarkDeclarationsReferencedInExpr(C);
13214       }
13215     }
13216   }
13217
13218   // When are coming out of an unevaluated context, clear out any
13219   // temporaries that we may have created as part of the evaluation of
13220   // the expression in that context: they aren't relevant because they
13221   // will never be constructed.
13222   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13223     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13224                              ExprCleanupObjects.end());
13225     Cleanup = Rec.ParentCleanup;
13226     CleanupVarDeclMarking();
13227     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13228   // Otherwise, merge the contexts together.
13229   } else {
13230     Cleanup.mergeFrom(Rec.ParentCleanup);
13231     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13232                             Rec.SavedMaybeODRUseExprs.end());
13233   }
13234
13235   // Pop the current expression evaluation context off the stack.
13236   ExprEvalContexts.pop_back();
13237
13238   if (!ExprEvalContexts.empty())
13239     ExprEvalContexts.back().NumTypos += NumTypos;
13240   else
13241     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13242                             "last ExpressionEvaluationContextRecord");
13243 }
13244
13245 void Sema::DiscardCleanupsInEvaluationContext() {
13246   ExprCleanupObjects.erase(
13247          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13248          ExprCleanupObjects.end());
13249   Cleanup.reset();
13250   MaybeODRUseExprs.clear();
13251 }
13252
13253 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13254   if (!E->getType()->isVariablyModifiedType())
13255     return E;
13256   return TransformToPotentiallyEvaluated(E);
13257 }
13258
13259 /// Are we within a context in which some evaluation could be performed (be it
13260 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13261 /// captured by C++'s idea of an "unevaluated context".
13262 static bool isEvaluatableContext(Sema &SemaRef) {
13263   switch (SemaRef.ExprEvalContexts.back().Context) {
13264     case Sema::ExpressionEvaluationContext::Unevaluated:
13265     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13266     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13267       // Expressions in this context are never evaluated.
13268       return false;
13269
13270     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13271     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13272     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13273       // Expressions in this context could be evaluated.
13274       return true;
13275
13276     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13277       // Referenced declarations will only be used if the construct in the
13278       // containing expression is used, at which point we'll be given another
13279       // turn to mark them.
13280       return false;
13281   }
13282   llvm_unreachable("Invalid context");
13283 }
13284
13285 /// Are we within a context in which references to resolved functions or to
13286 /// variables result in odr-use?
13287 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13288   // An expression in a template is not really an expression until it's been
13289   // instantiated, so it doesn't trigger odr-use.
13290   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13291     return false;
13292
13293   switch (SemaRef.ExprEvalContexts.back().Context) {
13294     case Sema::ExpressionEvaluationContext::Unevaluated:
13295     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13296     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13297     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13298       return false;
13299
13300     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13301     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13302       return true;
13303
13304     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13305       return false;
13306   }
13307   llvm_unreachable("Invalid context");
13308 }
13309
13310 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13311   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13312   return Func->isConstexpr() &&
13313          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13314 }
13315
13316 /// \brief Mark a function referenced, and check whether it is odr-used
13317 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13318 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13319                                   bool MightBeOdrUse) {
13320   assert(Func && "No function?");
13321
13322   Func->setReferenced();
13323
13324   // C++11 [basic.def.odr]p3:
13325   //   A function whose name appears as a potentially-evaluated expression is
13326   //   odr-used if it is the unique lookup result or the selected member of a
13327   //   set of overloaded functions [...].
13328   //
13329   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13330   // can just check that here.
13331   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13332
13333   // Determine whether we require a function definition to exist, per
13334   // C++11 [temp.inst]p3:
13335   //   Unless a function template specialization has been explicitly
13336   //   instantiated or explicitly specialized, the function template
13337   //   specialization is implicitly instantiated when the specialization is
13338   //   referenced in a context that requires a function definition to exist.
13339   //
13340   // That is either when this is an odr-use, or when a usage of a constexpr
13341   // function occurs within an evaluatable context.
13342   bool NeedDefinition =
13343       OdrUse || (isEvaluatableContext(*this) &&
13344                  isImplicitlyDefinableConstexprFunction(Func));
13345
13346   // C++14 [temp.expl.spec]p6:
13347   //   If a template [...] is explicitly specialized then that specialization
13348   //   shall be declared before the first use of that specialization that would
13349   //   cause an implicit instantiation to take place, in every translation unit
13350   //   in which such a use occurs
13351   if (NeedDefinition &&
13352       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13353        Func->getMemberSpecializationInfo()))
13354     checkSpecializationVisibility(Loc, Func);
13355
13356   // C++14 [except.spec]p17:
13357   //   An exception-specification is considered to be needed when:
13358   //   - the function is odr-used or, if it appears in an unevaluated operand,
13359   //     would be odr-used if the expression were potentially-evaluated;
13360   //
13361   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13362   // function is a pure virtual function we're calling, and in that case the
13363   // function was selected by overload resolution and we need to resolve its
13364   // exception specification for a different reason.
13365   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13366   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13367     ResolveExceptionSpec(Loc, FPT);
13368
13369   // If we don't need to mark the function as used, and we don't need to
13370   // try to provide a definition, there's nothing more to do.
13371   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13372       (!NeedDefinition || Func->getBody()))
13373     return;
13374
13375   // Note that this declaration has been used.
13376   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13377     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13378     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13379       if (Constructor->isDefaultConstructor()) {
13380         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13381           return;
13382         DefineImplicitDefaultConstructor(Loc, Constructor);
13383       } else if (Constructor->isCopyConstructor()) {
13384         DefineImplicitCopyConstructor(Loc, Constructor);
13385       } else if (Constructor->isMoveConstructor()) {
13386         DefineImplicitMoveConstructor(Loc, Constructor);
13387       }
13388     } else if (Constructor->getInheritedConstructor()) {
13389       DefineInheritingConstructor(Loc, Constructor);
13390     }
13391   } else if (CXXDestructorDecl *Destructor =
13392                  dyn_cast<CXXDestructorDecl>(Func)) {
13393     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13394     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13395       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13396         return;
13397       DefineImplicitDestructor(Loc, Destructor);
13398     }
13399     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13400       MarkVTableUsed(Loc, Destructor->getParent());
13401   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13402     if (MethodDecl->isOverloadedOperator() &&
13403         MethodDecl->getOverloadedOperator() == OO_Equal) {
13404       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13405       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13406         if (MethodDecl->isCopyAssignmentOperator())
13407           DefineImplicitCopyAssignment(Loc, MethodDecl);
13408         else if (MethodDecl->isMoveAssignmentOperator())
13409           DefineImplicitMoveAssignment(Loc, MethodDecl);
13410       }
13411     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13412                MethodDecl->getParent()->isLambda()) {
13413       CXXConversionDecl *Conversion =
13414           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13415       if (Conversion->isLambdaToBlockPointerConversion())
13416         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13417       else
13418         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13419     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13420       MarkVTableUsed(Loc, MethodDecl->getParent());
13421   }
13422
13423   // Recursive functions should be marked when used from another function.
13424   // FIXME: Is this really right?
13425   if (CurContext == Func) return;
13426
13427   // Implicit instantiation of function templates and member functions of
13428   // class templates.
13429   if (Func->isImplicitlyInstantiable()) {
13430     bool AlreadyInstantiated = false;
13431     SourceLocation PointOfInstantiation = Loc;
13432     if (FunctionTemplateSpecializationInfo *SpecInfo
13433                               = Func->getTemplateSpecializationInfo()) {
13434       if (SpecInfo->getPointOfInstantiation().isInvalid())
13435         SpecInfo->setPointOfInstantiation(Loc);
13436       else if (SpecInfo->getTemplateSpecializationKind()
13437                  == TSK_ImplicitInstantiation) {
13438         AlreadyInstantiated = true;
13439         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13440       }
13441     } else if (MemberSpecializationInfo *MSInfo
13442                                 = Func->getMemberSpecializationInfo()) {
13443       if (MSInfo->getPointOfInstantiation().isInvalid())
13444         MSInfo->setPointOfInstantiation(Loc);
13445       else if (MSInfo->getTemplateSpecializationKind()
13446                  == TSK_ImplicitInstantiation) {
13447         AlreadyInstantiated = true;
13448         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13449       }
13450     }
13451
13452     if (!AlreadyInstantiated || Func->isConstexpr()) {
13453       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13454           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13455           CodeSynthesisContexts.size())
13456         PendingLocalImplicitInstantiations.push_back(
13457             std::make_pair(Func, PointOfInstantiation));
13458       else if (Func->isConstexpr())
13459         // Do not defer instantiations of constexpr functions, to avoid the
13460         // expression evaluator needing to call back into Sema if it sees a
13461         // call to such a function.
13462         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13463       else {
13464         PendingInstantiations.push_back(std::make_pair(Func,
13465                                                        PointOfInstantiation));
13466         // Notify the consumer that a function was implicitly instantiated.
13467         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13468       }
13469     }
13470   } else {
13471     // Walk redefinitions, as some of them may be instantiable.
13472     for (auto i : Func->redecls()) {
13473       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13474         MarkFunctionReferenced(Loc, i, OdrUse);
13475     }
13476   }
13477
13478   if (!OdrUse) return;
13479
13480   // Keep track of used but undefined functions.
13481   if (!Func->isDefined()) {
13482     if (mightHaveNonExternalLinkage(Func))
13483       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13484     else if (Func->getMostRecentDecl()->isInlined() &&
13485              !LangOpts.GNUInline &&
13486              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13487       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13488   }
13489
13490   Func->markUsed(Context);
13491 }
13492
13493 static void
13494 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13495                                    ValueDecl *var, DeclContext *DC) {
13496   DeclContext *VarDC = var->getDeclContext();
13497
13498   //  If the parameter still belongs to the translation unit, then
13499   //  we're actually just using one parameter in the declaration of
13500   //  the next.
13501   if (isa<ParmVarDecl>(var) &&
13502       isa<TranslationUnitDecl>(VarDC))
13503     return;
13504
13505   // For C code, don't diagnose about capture if we're not actually in code
13506   // right now; it's impossible to write a non-constant expression outside of
13507   // function context, so we'll get other (more useful) diagnostics later.
13508   //
13509   // For C++, things get a bit more nasty... it would be nice to suppress this
13510   // diagnostic for certain cases like using a local variable in an array bound
13511   // for a member of a local class, but the correct predicate is not obvious.
13512   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13513     return;
13514
13515   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13516   unsigned ContextKind = 3; // unknown
13517   if (isa<CXXMethodDecl>(VarDC) &&
13518       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13519     ContextKind = 2;
13520   } else if (isa<FunctionDecl>(VarDC)) {
13521     ContextKind = 0;
13522   } else if (isa<BlockDecl>(VarDC)) {
13523     ContextKind = 1;
13524   }
13525
13526   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13527     << var << ValueKind << ContextKind << VarDC;
13528   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13529       << var;
13530
13531   // FIXME: Add additional diagnostic info about class etc. which prevents
13532   // capture.
13533 }
13534
13535  
13536 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
13537                                       bool &SubCapturesAreNested,
13538                                       QualType &CaptureType, 
13539                                       QualType &DeclRefType) {
13540    // Check whether we've already captured it.
13541   if (CSI->CaptureMap.count(Var)) {
13542     // If we found a capture, any subcaptures are nested.
13543     SubCapturesAreNested = true;
13544       
13545     // Retrieve the capture type for this variable.
13546     CaptureType = CSI->getCapture(Var).getCaptureType();
13547       
13548     // Compute the type of an expression that refers to this variable.
13549     DeclRefType = CaptureType.getNonReferenceType();
13550
13551     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13552     // are mutable in the sense that user can change their value - they are
13553     // private instances of the captured declarations.
13554     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13555     if (Cap.isCopyCapture() &&
13556         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13557         !(isa<CapturedRegionScopeInfo>(CSI) &&
13558           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13559       DeclRefType.addConst();
13560     return true;
13561   }
13562   return false;
13563 }
13564
13565 // Only block literals, captured statements, and lambda expressions can
13566 // capture; other scopes don't work.
13567 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
13568                                  SourceLocation Loc, 
13569                                  const bool Diagnose, Sema &S) {
13570   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13571     return getLambdaAwareParentOfDeclContext(DC);
13572   else if (Var->hasLocalStorage()) {
13573     if (Diagnose)
13574        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13575   }
13576   return nullptr;
13577 }
13578
13579 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13580 // certain types of variables (unnamed, variably modified types etc.)
13581 // so check for eligibility.
13582 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
13583                                  SourceLocation Loc, 
13584                                  const bool Diagnose, Sema &S) {
13585
13586   bool IsBlock = isa<BlockScopeInfo>(CSI);
13587   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13588
13589   // Lambdas are not allowed to capture unnamed variables
13590   // (e.g. anonymous unions).
13591   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13592   // assuming that's the intent.
13593   if (IsLambda && !Var->getDeclName()) {
13594     if (Diagnose) {
13595       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13596       S.Diag(Var->getLocation(), diag::note_declared_at);
13597     }
13598     return false;
13599   }
13600
13601   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13602   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13603     if (Diagnose) {
13604       S.Diag(Loc, diag::err_ref_vm_type);
13605       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13606         << Var->getDeclName();
13607     }
13608     return false;
13609   }
13610   // Prohibit structs with flexible array members too.
13611   // We cannot capture what is in the tail end of the struct.
13612   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13613     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13614       if (Diagnose) {
13615         if (IsBlock)
13616           S.Diag(Loc, diag::err_ref_flexarray_type);
13617         else
13618           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13619             << Var->getDeclName();
13620         S.Diag(Var->getLocation(), diag::note_previous_decl)
13621           << Var->getDeclName();
13622       }
13623       return false;
13624     }
13625   }
13626   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13627   // Lambdas and captured statements are not allowed to capture __block
13628   // variables; they don't support the expected semantics.
13629   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13630     if (Diagnose) {
13631       S.Diag(Loc, diag::err_capture_block_variable)
13632         << Var->getDeclName() << !IsLambda;
13633       S.Diag(Var->getLocation(), diag::note_previous_decl)
13634         << Var->getDeclName();
13635     }
13636     return false;
13637   }
13638   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13639   if (S.getLangOpts().OpenCL && IsBlock &&
13640       Var->getType()->isBlockPointerType()) {
13641     if (Diagnose)
13642       S.Diag(Loc, diag::err_opencl_block_ref_block);
13643     return false;
13644   }
13645
13646   return true;
13647 }
13648
13649 // Returns true if the capture by block was successful.
13650 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
13651                                  SourceLocation Loc, 
13652                                  const bool BuildAndDiagnose, 
13653                                  QualType &CaptureType,
13654                                  QualType &DeclRefType, 
13655                                  const bool Nested,
13656                                  Sema &S) {
13657   Expr *CopyExpr = nullptr;
13658   bool ByRef = false;
13659       
13660   // Blocks are not allowed to capture arrays.
13661   if (CaptureType->isArrayType()) {
13662     if (BuildAndDiagnose) {
13663       S.Diag(Loc, diag::err_ref_array_type);
13664       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13665       << Var->getDeclName();
13666     }
13667     return false;
13668   }
13669
13670   // Forbid the block-capture of autoreleasing variables.
13671   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13672     if (BuildAndDiagnose) {
13673       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13674         << /*block*/ 0;
13675       S.Diag(Var->getLocation(), diag::note_previous_decl)
13676         << Var->getDeclName();
13677     }
13678     return false;
13679   }
13680
13681   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13682   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13683     // This function finds out whether there is an AttributedType of kind
13684     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13685     // attr_objc_ownership implies __autoreleasing was explicitly specified
13686     // rather than being added implicitly by the compiler.
13687     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13688       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13689         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13690           return true;
13691
13692         // Peel off AttributedTypes that are not of kind objc_ownership.
13693         Ty = AttrTy->getModifiedType();
13694       }
13695
13696       return false;
13697     };
13698
13699     QualType PointeeTy = PT->getPointeeType();
13700
13701     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13702         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13703         !IsObjCOwnershipAttributedType(PointeeTy)) {
13704       if (BuildAndDiagnose) {
13705         SourceLocation VarLoc = Var->getLocation();
13706         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13707         {
13708           auto AddAutoreleaseNote =
13709               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13710           // Provide a fix-it for the '__autoreleasing' keyword at the
13711           // appropriate location in the variable's type.
13712           if (const auto *TSI = Var->getTypeSourceInfo()) {
13713             PointerTypeLoc PTL =
13714                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13715             if (PTL) {
13716               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13717               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13718                                                S.getLangOpts());
13719               if (Loc.isValid()) {
13720                 StringRef CharAtLoc = Lexer::getSourceText(
13721                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13722                     S.getSourceManager(), S.getLangOpts());
13723                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13724                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13725                              ? " __autoreleasing "
13726                              : " __autoreleasing");
13727               }
13728             }
13729           }
13730         }
13731         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13732       }
13733     }
13734   }
13735
13736   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13737   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13738       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13739     // Block capture by reference does not change the capture or
13740     // declaration reference types.
13741     ByRef = true;
13742   } else {
13743     // Block capture by copy introduces 'const'.
13744     CaptureType = CaptureType.getNonReferenceType().withConst();
13745     DeclRefType = CaptureType;
13746                 
13747     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13748       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13749         // The capture logic needs the destructor, so make sure we mark it.
13750         // Usually this is unnecessary because most local variables have
13751         // their destructors marked at declaration time, but parameters are
13752         // an exception because it's technically only the call site that
13753         // actually requires the destructor.
13754         if (isa<ParmVarDecl>(Var))
13755           S.FinalizeVarWithDestructor(Var, Record);
13756
13757         // Enter a new evaluation context to insulate the copy
13758         // full-expression.
13759         EnterExpressionEvaluationContext scope(
13760             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13761
13762         // According to the blocks spec, the capture of a variable from
13763         // the stack requires a const copy constructor.  This is not true
13764         // of the copy/move done to move a __block variable to the heap.
13765         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13766                                                   DeclRefType.withConst(), 
13767                                                   VK_LValue, Loc);
13768             
13769         ExprResult Result
13770           = S.PerformCopyInitialization(
13771               InitializedEntity::InitializeBlock(Var->getLocation(),
13772                                                   CaptureType, false),
13773               Loc, DeclRef);
13774             
13775         // Build a full-expression copy expression if initialization
13776         // succeeded and used a non-trivial constructor.  Recover from
13777         // errors by pretending that the copy isn't necessary.
13778         if (!Result.isInvalid() &&
13779             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13780                 ->isTrivial()) {
13781           Result = S.MaybeCreateExprWithCleanups(Result);
13782           CopyExpr = Result.get();
13783         }
13784       }
13785     }
13786   }
13787
13788   // Actually capture the variable.
13789   if (BuildAndDiagnose)
13790     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
13791                     SourceLocation(), CaptureType, CopyExpr);
13792
13793   return true;
13794
13795 }
13796
13797
13798 /// \brief Capture the given variable in the captured region.
13799 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13800                                     VarDecl *Var, 
13801                                     SourceLocation Loc, 
13802                                     const bool BuildAndDiagnose, 
13803                                     QualType &CaptureType,
13804                                     QualType &DeclRefType, 
13805                                     const bool RefersToCapturedVariable,
13806                                     Sema &S) {
13807   // By default, capture variables by reference.
13808   bool ByRef = true;
13809   // Using an LValue reference type is consistent with Lambdas (see below).
13810   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13811     if (S.IsOpenMPCapturedDecl(Var))
13812       DeclRefType = DeclRefType.getUnqualifiedType();
13813     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13814   }
13815
13816   if (ByRef)
13817     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13818   else
13819     CaptureType = DeclRefType;
13820
13821   Expr *CopyExpr = nullptr;
13822   if (BuildAndDiagnose) {
13823     // The current implementation assumes that all variables are captured
13824     // by references. Since there is no capture by copy, no expression
13825     // evaluation will be needed.
13826     RecordDecl *RD = RSI->TheRecordDecl;
13827
13828     FieldDecl *Field
13829       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13830                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13831                           nullptr, false, ICIS_NoInit);
13832     Field->setImplicit(true);
13833     Field->setAccess(AS_private);
13834     RD->addDecl(Field);
13835  
13836     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13837                                             DeclRefType, VK_LValue, Loc);
13838     Var->setReferenced(true);
13839     Var->markUsed(S.Context);
13840   }
13841
13842   // Actually capture the variable.
13843   if (BuildAndDiagnose)
13844     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13845                     SourceLocation(), CaptureType, CopyExpr);
13846   
13847   
13848   return true;
13849 }
13850
13851 /// \brief Create a field within the lambda class for the variable
13852 /// being captured.
13853 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 
13854                                     QualType FieldType, QualType DeclRefType,
13855                                     SourceLocation Loc,
13856                                     bool RefersToCapturedVariable) {
13857   CXXRecordDecl *Lambda = LSI->Lambda;
13858
13859   // Build the non-static data member.
13860   FieldDecl *Field
13861     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13862                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13863                         nullptr, false, ICIS_NoInit);
13864   Field->setImplicit(true);
13865   Field->setAccess(AS_private);
13866   Lambda->addDecl(Field);
13867 }
13868
13869 /// \brief Capture the given variable in the lambda.
13870 static bool captureInLambda(LambdaScopeInfo *LSI,
13871                             VarDecl *Var, 
13872                             SourceLocation Loc, 
13873                             const bool BuildAndDiagnose, 
13874                             QualType &CaptureType,
13875                             QualType &DeclRefType, 
13876                             const bool RefersToCapturedVariable,
13877                             const Sema::TryCaptureKind Kind, 
13878                             SourceLocation EllipsisLoc,
13879                             const bool IsTopScope,
13880                             Sema &S) {
13881
13882   // Determine whether we are capturing by reference or by value.
13883   bool ByRef = false;
13884   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13885     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13886   } else {
13887     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13888   }
13889     
13890   // Compute the type of the field that will capture this variable.
13891   if (ByRef) {
13892     // C++11 [expr.prim.lambda]p15:
13893     //   An entity is captured by reference if it is implicitly or
13894     //   explicitly captured but not captured by copy. It is
13895     //   unspecified whether additional unnamed non-static data
13896     //   members are declared in the closure type for entities
13897     //   captured by reference.
13898     //
13899     // FIXME: It is not clear whether we want to build an lvalue reference
13900     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13901     // to do the former, while EDG does the latter. Core issue 1249 will 
13902     // clarify, but for now we follow GCC because it's a more permissive and
13903     // easily defensible position.
13904     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13905   } else {
13906     // C++11 [expr.prim.lambda]p14:
13907     //   For each entity captured by copy, an unnamed non-static
13908     //   data member is declared in the closure type. The
13909     //   declaration order of these members is unspecified. The type
13910     //   of such a data member is the type of the corresponding
13911     //   captured entity if the entity is not a reference to an
13912     //   object, or the referenced type otherwise. [Note: If the
13913     //   captured entity is a reference to a function, the
13914     //   corresponding data member is also a reference to a
13915     //   function. - end note ]
13916     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13917       if (!RefType->getPointeeType()->isFunctionType())
13918         CaptureType = RefType->getPointeeType();
13919     }
13920
13921     // Forbid the lambda copy-capture of autoreleasing variables.
13922     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13923       if (BuildAndDiagnose) {
13924         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13925         S.Diag(Var->getLocation(), diag::note_previous_decl)
13926           << Var->getDeclName();
13927       }
13928       return false;
13929     }
13930
13931     // Make sure that by-copy captures are of a complete and non-abstract type.
13932     if (BuildAndDiagnose) {
13933       if (!CaptureType->isDependentType() &&
13934           S.RequireCompleteType(Loc, CaptureType,
13935                                 diag::err_capture_of_incomplete_type,
13936                                 Var->getDeclName()))
13937         return false;
13938
13939       if (S.RequireNonAbstractType(Loc, CaptureType,
13940                                    diag::err_capture_of_abstract_type))
13941         return false;
13942     }
13943   }
13944
13945   // Capture this variable in the lambda.
13946   if (BuildAndDiagnose)
13947     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13948                             RefersToCapturedVariable);
13949     
13950   // Compute the type of a reference to this captured variable.
13951   if (ByRef)
13952     DeclRefType = CaptureType.getNonReferenceType();
13953   else {
13954     // C++ [expr.prim.lambda]p5:
13955     //   The closure type for a lambda-expression has a public inline 
13956     //   function call operator [...]. This function call operator is 
13957     //   declared const (9.3.1) if and only if the lambda-expression's 
13958     //   parameter-declaration-clause is not followed by mutable.
13959     DeclRefType = CaptureType.getNonReferenceType();
13960     if (!LSI->Mutable && !CaptureType->isReferenceType())
13961       DeclRefType.addConst();      
13962   }
13963     
13964   // Add the capture.
13965   if (BuildAndDiagnose)
13966     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
13967                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13968       
13969   return true;
13970 }
13971
13972 bool Sema::tryCaptureVariable(
13973     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13974     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13975     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13976   // An init-capture is notionally from the context surrounding its
13977   // declaration, but its parent DC is the lambda class.
13978   DeclContext *VarDC = Var->getDeclContext();
13979   if (Var->isInitCapture())
13980     VarDC = VarDC->getParent();
13981   
13982   DeclContext *DC = CurContext;
13983   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
13984       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
13985   // We need to sync up the Declaration Context with the
13986   // FunctionScopeIndexToStopAt
13987   if (FunctionScopeIndexToStopAt) {
13988     unsigned FSIndex = FunctionScopes.size() - 1;
13989     while (FSIndex != MaxFunctionScopesIndex) {
13990       DC = getLambdaAwareParentOfDeclContext(DC);
13991       --FSIndex;
13992     }
13993   }
13994
13995   
13996   // If the variable is declared in the current context, there is no need to
13997   // capture it.
13998   if (VarDC == DC) return true;
13999
14000   // Capture global variables if it is required to use private copy of this
14001   // variable.
14002   bool IsGlobal = !Var->hasLocalStorage();
14003   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14004     return true;
14005
14006   // Walk up the stack to determine whether we can capture the variable,
14007   // performing the "simple" checks that don't depend on type. We stop when
14008   // we've either hit the declared scope of the variable or find an existing
14009   // capture of that variable.  We start from the innermost capturing-entity
14010   // (the DC) and ensure that all intervening capturing-entities 
14011   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14012   // declcontext can either capture the variable or have already captured
14013   // the variable.
14014   CaptureType = Var->getType();
14015   DeclRefType = CaptureType.getNonReferenceType();
14016   bool Nested = false;
14017   bool Explicit = (Kind != TryCapture_Implicit);
14018   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14019   do {
14020     // Only block literals, captured statements, and lambda expressions can
14021     // capture; other scopes don't work.
14022     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
14023                                                               ExprLoc, 
14024                                                               BuildAndDiagnose,
14025                                                               *this);
14026     // We need to check for the parent *first* because, if we *have*
14027     // private-captured a global variable, we need to recursively capture it in
14028     // intermediate blocks, lambdas, etc.
14029     if (!ParentDC) {
14030       if (IsGlobal) {
14031         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14032         break;
14033       }
14034       return true;
14035     }
14036
14037     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14038     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14039
14040
14041     // Check whether we've already captured it.
14042     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
14043                                              DeclRefType)) {
14044       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14045       break;
14046     }
14047     // If we are instantiating a generic lambda call operator body, 
14048     // we do not want to capture new variables.  What was captured
14049     // during either a lambdas transformation or initial parsing
14050     // should be used. 
14051     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14052       if (BuildAndDiagnose) {
14053         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
14054         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14055           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14056           Diag(Var->getLocation(), diag::note_previous_decl) 
14057              << Var->getDeclName();
14058           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
14059         } else
14060           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14061       }
14062       return true;
14063     }
14064     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
14065     // certain types of variables (unnamed, variably modified types etc.)
14066     // so check for eligibility.
14067     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14068        return true;
14069
14070     // Try to capture variable-length arrays types.
14071     if (Var->getType()->isVariablyModifiedType()) {
14072       // We're going to walk down into the type and look for VLA
14073       // expressions.
14074       QualType QTy = Var->getType();
14075       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14076         QTy = PVD->getOriginalType();
14077       captureVariablyModifiedType(Context, QTy, CSI);
14078     }
14079
14080     if (getLangOpts().OpenMP) {
14081       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14082         // OpenMP private variables should not be captured in outer scope, so
14083         // just break here. Similarly, global variables that are captured in a
14084         // target region should not be captured outside the scope of the region.
14085         if (RSI->CapRegionKind == CR_OpenMP) {
14086           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14087           // When we detect target captures we are looking from inside the
14088           // target region, therefore we need to propagate the capture from the
14089           // enclosing region. Therefore, the capture is not initially nested.
14090           if (IsTargetCap)
14091             FunctionScopesIndex--;
14092
14093           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14094             Nested = !IsTargetCap;
14095             DeclRefType = DeclRefType.getUnqualifiedType();
14096             CaptureType = Context.getLValueReferenceType(DeclRefType);
14097             break;
14098           }
14099         }
14100       }
14101     }
14102     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14103       // No capture-default, and this is not an explicit capture 
14104       // so cannot capture this variable.  
14105       if (BuildAndDiagnose) {
14106         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14107         Diag(Var->getLocation(), diag::note_previous_decl) 
14108           << Var->getDeclName();
14109         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14110           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14111                diag::note_lambda_decl);
14112         // FIXME: If we error out because an outer lambda can not implicitly
14113         // capture a variable that an inner lambda explicitly captures, we
14114         // should have the inner lambda do the explicit capture - because
14115         // it makes for cleaner diagnostics later.  This would purely be done
14116         // so that the diagnostic does not misleadingly claim that a variable 
14117         // can not be captured by a lambda implicitly even though it is captured 
14118         // explicitly.  Suggestion:
14119         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
14120         //    at the function head
14121         //  - cache the StartingDeclContext - this must be a lambda 
14122         //  - captureInLambda in the innermost lambda the variable.
14123       }
14124       return true;
14125     }
14126
14127     FunctionScopesIndex--;
14128     DC = ParentDC;
14129     Explicit = false;
14130   } while (!VarDC->Equals(DC));
14131
14132   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14133   // computing the type of the capture at each step, checking type-specific 
14134   // requirements, and adding captures if requested. 
14135   // If the variable had already been captured previously, we start capturing 
14136   // at the lambda nested within that one.   
14137   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
14138        ++I) {
14139     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14140     
14141     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14142       if (!captureInBlock(BSI, Var, ExprLoc, 
14143                           BuildAndDiagnose, CaptureType, 
14144                           DeclRefType, Nested, *this))
14145         return true;
14146       Nested = true;
14147     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14148       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
14149                                    BuildAndDiagnose, CaptureType, 
14150                                    DeclRefType, Nested, *this))
14151         return true;
14152       Nested = true;
14153     } else {
14154       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14155       if (!captureInLambda(LSI, Var, ExprLoc, 
14156                            BuildAndDiagnose, CaptureType, 
14157                            DeclRefType, Nested, Kind, EllipsisLoc, 
14158                             /*IsTopScope*/I == N - 1, *this))
14159         return true;
14160       Nested = true;
14161     }
14162   }
14163   return false;
14164 }
14165
14166 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14167                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
14168   QualType CaptureType;
14169   QualType DeclRefType;
14170   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14171                             /*BuildAndDiagnose=*/true, CaptureType,
14172                             DeclRefType, nullptr);
14173 }
14174
14175 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14176   QualType CaptureType;
14177   QualType DeclRefType;
14178   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14179                              /*BuildAndDiagnose=*/false, CaptureType,
14180                              DeclRefType, nullptr);
14181 }
14182
14183 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14184   QualType CaptureType;
14185   QualType DeclRefType;
14186   
14187   // Determine whether we can capture this variable.
14188   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14189                          /*BuildAndDiagnose=*/false, CaptureType, 
14190                          DeclRefType, nullptr))
14191     return QualType();
14192
14193   return DeclRefType;
14194 }
14195
14196
14197
14198 // If either the type of the variable or the initializer is dependent, 
14199 // return false. Otherwise, determine whether the variable is a constant
14200 // expression. Use this if you need to know if a variable that might or
14201 // might not be dependent is truly a constant expression.
14202 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
14203     ASTContext &Context) {
14204  
14205   if (Var->getType()->isDependentType()) 
14206     return false;
14207   const VarDecl *DefVD = nullptr;
14208   Var->getAnyInitializer(DefVD);
14209   if (!DefVD) 
14210     return false;
14211   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14212   Expr *Init = cast<Expr>(Eval->Value);
14213   if (Init->isValueDependent()) 
14214     return false;
14215   return IsVariableAConstantExpression(Var, Context); 
14216 }
14217
14218
14219 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14220   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
14221   // an object that satisfies the requirements for appearing in a
14222   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14223   // is immediately applied."  This function handles the lvalue-to-rvalue
14224   // conversion part.
14225   MaybeODRUseExprs.erase(E->IgnoreParens());
14226   
14227   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14228   // to a variable that is a constant expression, and if so, identify it as
14229   // a reference to a variable that does not involve an odr-use of that 
14230   // variable. 
14231   if (LambdaScopeInfo *LSI = getCurLambda()) {
14232     Expr *SansParensExpr = E->IgnoreParens();
14233     VarDecl *Var = nullptr;
14234     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
14235       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14236     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14237       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14238     
14239     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
14240       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
14241   }
14242 }
14243
14244 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14245   Res = CorrectDelayedTyposInExpr(Res);
14246
14247   if (!Res.isUsable())
14248     return Res;
14249
14250   // If a constant-expression is a reference to a variable where we delay
14251   // deciding whether it is an odr-use, just assume we will apply the
14252   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14253   // (a non-type template argument), we have special handling anyway.
14254   UpdateMarkingForLValueToRValue(Res.get());
14255   return Res;
14256 }
14257
14258 void Sema::CleanupVarDeclMarking() {
14259   for (Expr *E : MaybeODRUseExprs) {
14260     VarDecl *Var;
14261     SourceLocation Loc;
14262     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14263       Var = cast<VarDecl>(DRE->getDecl());
14264       Loc = DRE->getLocation();
14265     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14266       Var = cast<VarDecl>(ME->getMemberDecl());
14267       Loc = ME->getMemberLoc();
14268     } else {
14269       llvm_unreachable("Unexpected expression");
14270     }
14271
14272     MarkVarDeclODRUsed(Var, Loc, *this,
14273                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14274   }
14275
14276   MaybeODRUseExprs.clear();
14277 }
14278
14279
14280 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14281                                     VarDecl *Var, Expr *E) {
14282   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14283          "Invalid Expr argument to DoMarkVarDeclReferenced");
14284   Var->setReferenced();
14285
14286   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14287
14288   bool OdrUseContext = isOdrUseContext(SemaRef);
14289   bool NeedDefinition =
14290       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14291                         Var->isUsableInConstantExpressions(SemaRef.Context));
14292
14293   VarTemplateSpecializationDecl *VarSpec =
14294       dyn_cast<VarTemplateSpecializationDecl>(Var);
14295   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14296          "Can't instantiate a partial template specialization.");
14297
14298   // If this might be a member specialization of a static data member, check
14299   // the specialization is visible. We already did the checks for variable
14300   // template specializations when we created them.
14301   if (NeedDefinition && TSK != TSK_Undeclared &&
14302       !isa<VarTemplateSpecializationDecl>(Var))
14303     SemaRef.checkSpecializationVisibility(Loc, Var);
14304
14305   // Perform implicit instantiation of static data members, static data member
14306   // templates of class templates, and variable template specializations. Delay
14307   // instantiations of variable templates, except for those that could be used
14308   // in a constant expression.
14309   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14310     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14311
14312     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14313       if (Var->getPointOfInstantiation().isInvalid()) {
14314         // This is a modification of an existing AST node. Notify listeners.
14315         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14316           L->StaticDataMemberInstantiated(Var);
14317       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14318         // Don't bother trying to instantiate it again, unless we might need
14319         // its initializer before we get to the end of the TU.
14320         TryInstantiating = false;
14321     }
14322
14323     if (Var->getPointOfInstantiation().isInvalid())
14324       Var->setTemplateSpecializationKind(TSK, Loc);
14325
14326     if (TryInstantiating) {
14327       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14328       bool InstantiationDependent = false;
14329       bool IsNonDependent =
14330           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14331                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14332                   : true;
14333
14334       // Do not instantiate specializations that are still type-dependent.
14335       if (IsNonDependent) {
14336         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14337           // Do not defer instantiations of variables which could be used in a
14338           // constant expression.
14339           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14340         } else {
14341           SemaRef.PendingInstantiations
14342               .push_back(std::make_pair(Var, PointOfInstantiation));
14343         }
14344       }
14345     }
14346   }
14347
14348   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14349   // the requirements for appearing in a constant expression (5.19) and, if
14350   // it is an object, the lvalue-to-rvalue conversion (4.1)
14351   // is immediately applied."  We check the first part here, and
14352   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14353   // Note that we use the C++11 definition everywhere because nothing in
14354   // C++03 depends on whether we get the C++03 version correct. The second
14355   // part does not apply to references, since they are not objects.
14356   if (OdrUseContext && E &&
14357       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14358     // A reference initialized by a constant expression can never be
14359     // odr-used, so simply ignore it.
14360     if (!Var->getType()->isReferenceType())
14361       SemaRef.MaybeODRUseExprs.insert(E);
14362   } else if (OdrUseContext) {
14363     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14364                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14365   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14366     // If this is a dependent context, we don't need to mark variables as
14367     // odr-used, but we may still need to track them for lambda capture.
14368     // FIXME: Do we also need to do this inside dependent typeid expressions
14369     // (which are modeled as unevaluated at this point)?
14370     const bool RefersToEnclosingScope =
14371         (SemaRef.CurContext != Var->getDeclContext() &&
14372          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14373     if (RefersToEnclosingScope) {
14374       LambdaScopeInfo *const LSI =
14375           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14376       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14377         // If a variable could potentially be odr-used, defer marking it so
14378         // until we finish analyzing the full expression for any
14379         // lvalue-to-rvalue
14380         // or discarded value conversions that would obviate odr-use.
14381         // Add it to the list of potential captures that will be analyzed
14382         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14383         // unless the variable is a reference that was initialized by a constant
14384         // expression (this will never need to be captured or odr-used).
14385         assert(E && "Capture variable should be used in an expression.");
14386         if (!Var->getType()->isReferenceType() ||
14387             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14388           LSI->addPotentialCapture(E->IgnoreParens());
14389       }
14390     }
14391   }
14392 }
14393
14394 /// \brief Mark a variable referenced, and check whether it is odr-used
14395 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14396 /// used directly for normal expressions referring to VarDecl.
14397 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14398   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14399 }
14400
14401 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14402                                Decl *D, Expr *E, bool MightBeOdrUse) {
14403   if (SemaRef.isInOpenMPDeclareTargetContext())
14404     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14405
14406   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14407     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14408     return;
14409   }
14410
14411   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14412
14413   // If this is a call to a method via a cast, also mark the method in the
14414   // derived class used in case codegen can devirtualize the call.
14415   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14416   if (!ME)
14417     return;
14418   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14419   if (!MD)
14420     return;
14421   // Only attempt to devirtualize if this is truly a virtual call.
14422   bool IsVirtualCall = MD->isVirtual() &&
14423                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14424   if (!IsVirtualCall)
14425     return;
14426   const Expr *Base = ME->getBase();
14427   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14428   if (!MostDerivedClassDecl)
14429     return;
14430   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14431   if (!DM || DM->isPure())
14432     return;
14433   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14434
14435
14436 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14437 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14438   // TODO: update this with DR# once a defect report is filed.
14439   // C++11 defect. The address of a pure member should not be an ODR use, even
14440   // if it's a qualified reference.
14441   bool OdrUse = true;
14442   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14443     if (Method->isVirtual())
14444       OdrUse = false;
14445   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14446 }
14447
14448 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14449 void Sema::MarkMemberReferenced(MemberExpr *E) {
14450   // C++11 [basic.def.odr]p2:
14451   //   A non-overloaded function whose name appears as a potentially-evaluated
14452   //   expression or a member of a set of candidate functions, if selected by
14453   //   overload resolution when referred to from a potentially-evaluated
14454   //   expression, is odr-used, unless it is a pure virtual function and its
14455   //   name is not explicitly qualified.
14456   bool MightBeOdrUse = true;
14457   if (E->performsVirtualDispatch(getLangOpts())) {
14458     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14459       if (Method->isPure())
14460         MightBeOdrUse = false;
14461   }
14462   SourceLocation Loc = E->getMemberLoc().isValid() ?
14463                             E->getMemberLoc() : E->getLocStart();
14464   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14465 }
14466
14467 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14468 /// marks the declaration referenced, and performs odr-use checking for
14469 /// functions and variables. This method should not be used when building a
14470 /// normal expression which refers to a variable.
14471 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14472                                  bool MightBeOdrUse) {
14473   if (MightBeOdrUse) {
14474     if (auto *VD = dyn_cast<VarDecl>(D)) {
14475       MarkVariableReferenced(Loc, VD);
14476       return;
14477     }
14478   }
14479   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14480     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14481     return;
14482   }
14483   D->setReferenced();
14484 }
14485
14486 namespace {
14487   // Mark all of the declarations used by a type as referenced.
14488   // FIXME: Not fully implemented yet! We need to have a better understanding
14489   // of when we're entering a context we should not recurse into.
14490   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14491   // TreeTransforms rebuilding the type in a new context. Rather than
14492   // duplicating the TreeTransform logic, we should consider reusing it here.
14493   // Currently that causes problems when rebuilding LambdaExprs.
14494   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14495     Sema &S;
14496     SourceLocation Loc;
14497
14498   public:
14499     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14500
14501     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14502
14503     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14504   };
14505 }
14506
14507 bool MarkReferencedDecls::TraverseTemplateArgument(
14508     const TemplateArgument &Arg) {
14509   {
14510     // A non-type template argument is a constant-evaluated context.
14511     EnterExpressionEvaluationContext Evaluated(
14512         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14513     if (Arg.getKind() == TemplateArgument::Declaration) {
14514       if (Decl *D = Arg.getAsDecl())
14515         S.MarkAnyDeclReferenced(Loc, D, true);
14516     } else if (Arg.getKind() == TemplateArgument::Expression) {
14517       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14518     }
14519   }
14520
14521   return Inherited::TraverseTemplateArgument(Arg);
14522 }
14523
14524 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14525   MarkReferencedDecls Marker(*this, Loc);
14526   Marker.TraverseType(T);
14527 }
14528
14529 namespace {
14530   /// \brief Helper class that marks all of the declarations referenced by
14531   /// potentially-evaluated subexpressions as "referenced".
14532   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14533     Sema &S;
14534     bool SkipLocalVariables;
14535     
14536   public:
14537     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14538     
14539     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
14540       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14541     
14542     void VisitDeclRefExpr(DeclRefExpr *E) {
14543       // If we were asked not to visit local variables, don't.
14544       if (SkipLocalVariables) {
14545         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14546           if (VD->hasLocalStorage())
14547             return;
14548       }
14549       
14550       S.MarkDeclRefReferenced(E);
14551     }
14552
14553     void VisitMemberExpr(MemberExpr *E) {
14554       S.MarkMemberReferenced(E);
14555       Inherited::VisitMemberExpr(E);
14556     }
14557     
14558     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14559       S.MarkFunctionReferenced(E->getLocStart(),
14560             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14561       Visit(E->getSubExpr());
14562     }
14563     
14564     void VisitCXXNewExpr(CXXNewExpr *E) {
14565       if (E->getOperatorNew())
14566         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14567       if (E->getOperatorDelete())
14568         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14569       Inherited::VisitCXXNewExpr(E);
14570     }
14571
14572     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14573       if (E->getOperatorDelete())
14574         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14575       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14576       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14577         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14578         S.MarkFunctionReferenced(E->getLocStart(), 
14579                                     S.LookupDestructor(Record));
14580       }
14581       
14582       Inherited::VisitCXXDeleteExpr(E);
14583     }
14584     
14585     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14586       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14587       Inherited::VisitCXXConstructExpr(E);
14588     }
14589     
14590     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14591       Visit(E->getExpr());
14592     }
14593
14594     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14595       Inherited::VisitImplicitCastExpr(E);
14596
14597       if (E->getCastKind() == CK_LValueToRValue)
14598         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14599     }
14600   };
14601 }
14602
14603 /// \brief Mark any declarations that appear within this expression or any
14604 /// potentially-evaluated subexpressions as "referenced".
14605 ///
14606 /// \param SkipLocalVariables If true, don't mark local variables as 
14607 /// 'referenced'.
14608 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
14609                                             bool SkipLocalVariables) {
14610   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14611 }
14612
14613 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14614 /// of the program being compiled.
14615 ///
14616 /// This routine emits the given diagnostic when the code currently being
14617 /// type-checked is "potentially evaluated", meaning that there is a
14618 /// possibility that the code will actually be executable. Code in sizeof()
14619 /// expressions, code used only during overload resolution, etc., are not
14620 /// potentially evaluated. This routine will suppress such diagnostics or,
14621 /// in the absolutely nutty case of potentially potentially evaluated
14622 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14623 /// later.
14624 ///
14625 /// This routine should be used for all diagnostics that describe the run-time
14626 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14627 /// Failure to do so will likely result in spurious diagnostics or failures
14628 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14629 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14630                                const PartialDiagnostic &PD) {
14631   switch (ExprEvalContexts.back().Context) {
14632   case ExpressionEvaluationContext::Unevaluated:
14633   case ExpressionEvaluationContext::UnevaluatedList:
14634   case ExpressionEvaluationContext::UnevaluatedAbstract:
14635   case ExpressionEvaluationContext::DiscardedStatement:
14636     // The argument will never be evaluated, so don't complain.
14637     break;
14638
14639   case ExpressionEvaluationContext::ConstantEvaluated:
14640     // Relevant diagnostics should be produced by constant evaluation.
14641     break;
14642
14643   case ExpressionEvaluationContext::PotentiallyEvaluated:
14644   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14645     if (Statement && getCurFunctionOrMethodDecl()) {
14646       FunctionScopes.back()->PossiblyUnreachableDiags.
14647         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14648     }
14649     else
14650       Diag(Loc, PD);
14651       
14652     return true;
14653   }
14654
14655   return false;
14656 }
14657
14658 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14659                                CallExpr *CE, FunctionDecl *FD) {
14660   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14661     return false;
14662
14663   // If we're inside a decltype's expression, don't check for a valid return
14664   // type or construct temporaries until we know whether this is the last call.
14665   if (ExprEvalContexts.back().IsDecltype) {
14666     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14667     return false;
14668   }
14669
14670   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14671     FunctionDecl *FD;
14672     CallExpr *CE;
14673     
14674   public:
14675     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14676       : FD(FD), CE(CE) { }
14677
14678     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14679       if (!FD) {
14680         S.Diag(Loc, diag::err_call_incomplete_return)
14681           << T << CE->getSourceRange();
14682         return;
14683       }
14684       
14685       S.Diag(Loc, diag::err_call_function_incomplete_return)
14686         << CE->getSourceRange() << FD->getDeclName() << T;
14687       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14688           << FD->getDeclName();
14689     }
14690   } Diagnoser(FD, CE);
14691   
14692   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14693     return true;
14694
14695   return false;
14696 }
14697
14698 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14699 // will prevent this condition from triggering, which is what we want.
14700 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14701   SourceLocation Loc;
14702
14703   unsigned diagnostic = diag::warn_condition_is_assignment;
14704   bool IsOrAssign = false;
14705
14706   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14707     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14708       return;
14709
14710     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14711
14712     // Greylist some idioms by putting them into a warning subcategory.
14713     if (ObjCMessageExpr *ME
14714           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14715       Selector Sel = ME->getSelector();
14716
14717       // self = [<foo> init...]
14718       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14719         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14720
14721       // <foo> = [<bar> nextObject]
14722       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14723         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14724     }
14725
14726     Loc = Op->getOperatorLoc();
14727   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14728     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14729       return;
14730
14731     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14732     Loc = Op->getOperatorLoc();
14733   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14734     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14735   else {
14736     // Not an assignment.
14737     return;
14738   }
14739
14740   Diag(Loc, diagnostic) << E->getSourceRange();
14741
14742   SourceLocation Open = E->getLocStart();
14743   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14744   Diag(Loc, diag::note_condition_assign_silence)
14745         << FixItHint::CreateInsertion(Open, "(")
14746         << FixItHint::CreateInsertion(Close, ")");
14747
14748   if (IsOrAssign)
14749     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14750       << FixItHint::CreateReplacement(Loc, "!=");
14751   else
14752     Diag(Loc, diag::note_condition_assign_to_comparison)
14753       << FixItHint::CreateReplacement(Loc, "==");
14754 }
14755
14756 /// \brief Redundant parentheses over an equality comparison can indicate
14757 /// that the user intended an assignment used as condition.
14758 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14759   // Don't warn if the parens came from a macro.
14760   SourceLocation parenLoc = ParenE->getLocStart();
14761   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14762     return;
14763   // Don't warn for dependent expressions.
14764   if (ParenE->isTypeDependent())
14765     return;
14766
14767   Expr *E = ParenE->IgnoreParens();
14768
14769   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14770     if (opE->getOpcode() == BO_EQ &&
14771         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14772                                                            == Expr::MLV_Valid) {
14773       SourceLocation Loc = opE->getOperatorLoc();
14774       
14775       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14776       SourceRange ParenERange = ParenE->getSourceRange();
14777       Diag(Loc, diag::note_equality_comparison_silence)
14778         << FixItHint::CreateRemoval(ParenERange.getBegin())
14779         << FixItHint::CreateRemoval(ParenERange.getEnd());
14780       Diag(Loc, diag::note_equality_comparison_to_assign)
14781         << FixItHint::CreateReplacement(Loc, "=");
14782     }
14783 }
14784
14785 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14786                                        bool IsConstexpr) {
14787   DiagnoseAssignmentAsCondition(E);
14788   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14789     DiagnoseEqualityWithExtraParens(parenE);
14790
14791   ExprResult result = CheckPlaceholderExpr(E);
14792   if (result.isInvalid()) return ExprError();
14793   E = result.get();
14794
14795   if (!E->isTypeDependent()) {
14796     if (getLangOpts().CPlusPlus)
14797       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14798
14799     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14800     if (ERes.isInvalid())
14801       return ExprError();
14802     E = ERes.get();
14803
14804     QualType T = E->getType();
14805     if (!T->isScalarType()) { // C99 6.8.4.1p1
14806       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14807         << T << E->getSourceRange();
14808       return ExprError();
14809     }
14810     CheckBoolLikeConversion(E, Loc);
14811   }
14812
14813   return E;
14814 }
14815
14816 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14817                                            Expr *SubExpr, ConditionKind CK) {
14818   // Empty conditions are valid in for-statements.
14819   if (!SubExpr)
14820     return ConditionResult();
14821
14822   ExprResult Cond;
14823   switch (CK) {
14824   case ConditionKind::Boolean:
14825     Cond = CheckBooleanCondition(Loc, SubExpr);
14826     break;
14827
14828   case ConditionKind::ConstexprIf:
14829     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14830     break;
14831
14832   case ConditionKind::Switch:
14833     Cond = CheckSwitchCondition(Loc, SubExpr);
14834     break;
14835   }
14836   if (Cond.isInvalid())
14837     return ConditionError();
14838
14839   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14840   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14841   if (!FullExpr.get())
14842     return ConditionError();
14843
14844   return ConditionResult(*this, nullptr, FullExpr,
14845                          CK == ConditionKind::ConstexprIf);
14846 }
14847
14848 namespace {
14849   /// A visitor for rebuilding a call to an __unknown_any expression
14850   /// to have an appropriate type.
14851   struct RebuildUnknownAnyFunction
14852     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14853
14854     Sema &S;
14855
14856     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14857
14858     ExprResult VisitStmt(Stmt *S) {
14859       llvm_unreachable("unexpected statement!");
14860     }
14861
14862     ExprResult VisitExpr(Expr *E) {
14863       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14864         << E->getSourceRange();
14865       return ExprError();
14866     }
14867
14868     /// Rebuild an expression which simply semantically wraps another
14869     /// expression which it shares the type and value kind of.
14870     template <class T> ExprResult rebuildSugarExpr(T *E) {
14871       ExprResult SubResult = Visit(E->getSubExpr());
14872       if (SubResult.isInvalid()) return ExprError();
14873
14874       Expr *SubExpr = SubResult.get();
14875       E->setSubExpr(SubExpr);
14876       E->setType(SubExpr->getType());
14877       E->setValueKind(SubExpr->getValueKind());
14878       assert(E->getObjectKind() == OK_Ordinary);
14879       return E;
14880     }
14881
14882     ExprResult VisitParenExpr(ParenExpr *E) {
14883       return rebuildSugarExpr(E);
14884     }
14885
14886     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14887       return rebuildSugarExpr(E);
14888     }
14889
14890     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14891       ExprResult SubResult = Visit(E->getSubExpr());
14892       if (SubResult.isInvalid()) return ExprError();
14893
14894       Expr *SubExpr = SubResult.get();
14895       E->setSubExpr(SubExpr);
14896       E->setType(S.Context.getPointerType(SubExpr->getType()));
14897       assert(E->getValueKind() == VK_RValue);
14898       assert(E->getObjectKind() == OK_Ordinary);
14899       return E;
14900     }
14901
14902     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14903       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14904
14905       E->setType(VD->getType());
14906
14907       assert(E->getValueKind() == VK_RValue);
14908       if (S.getLangOpts().CPlusPlus &&
14909           !(isa<CXXMethodDecl>(VD) &&
14910             cast<CXXMethodDecl>(VD)->isInstance()))
14911         E->setValueKind(VK_LValue);
14912
14913       return E;
14914     }
14915
14916     ExprResult VisitMemberExpr(MemberExpr *E) {
14917       return resolveDecl(E, E->getMemberDecl());
14918     }
14919
14920     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14921       return resolveDecl(E, E->getDecl());
14922     }
14923   };
14924 }
14925
14926 /// Given a function expression of unknown-any type, try to rebuild it
14927 /// to have a function type.
14928 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14929   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14930   if (Result.isInvalid()) return ExprError();
14931   return S.DefaultFunctionArrayConversion(Result.get());
14932 }
14933
14934 namespace {
14935   /// A visitor for rebuilding an expression of type __unknown_anytype
14936   /// into one which resolves the type directly on the referring
14937   /// expression.  Strict preservation of the original source
14938   /// structure is not a goal.
14939   struct RebuildUnknownAnyExpr
14940     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14941
14942     Sema &S;
14943
14944     /// The current destination type.
14945     QualType DestType;
14946
14947     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14948       : S(S), DestType(CastType) {}
14949
14950     ExprResult VisitStmt(Stmt *S) {
14951       llvm_unreachable("unexpected statement!");
14952     }
14953
14954     ExprResult VisitExpr(Expr *E) {
14955       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14956         << E->getSourceRange();
14957       return ExprError();
14958     }
14959
14960     ExprResult VisitCallExpr(CallExpr *E);
14961     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14962
14963     /// Rebuild an expression which simply semantically wraps another
14964     /// expression which it shares the type and value kind of.
14965     template <class T> ExprResult rebuildSugarExpr(T *E) {
14966       ExprResult SubResult = Visit(E->getSubExpr());
14967       if (SubResult.isInvalid()) return ExprError();
14968       Expr *SubExpr = SubResult.get();
14969       E->setSubExpr(SubExpr);
14970       E->setType(SubExpr->getType());
14971       E->setValueKind(SubExpr->getValueKind());
14972       assert(E->getObjectKind() == OK_Ordinary);
14973       return E;
14974     }
14975
14976     ExprResult VisitParenExpr(ParenExpr *E) {
14977       return rebuildSugarExpr(E);
14978     }
14979
14980     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14981       return rebuildSugarExpr(E);
14982     }
14983
14984     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14985       const PointerType *Ptr = DestType->getAs<PointerType>();
14986       if (!Ptr) {
14987         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14988           << E->getSourceRange();
14989         return ExprError();
14990       }
14991
14992       if (isa<CallExpr>(E->getSubExpr())) {
14993         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14994           << E->getSourceRange();
14995         return ExprError();
14996       }
14997
14998       assert(E->getValueKind() == VK_RValue);
14999       assert(E->getObjectKind() == OK_Ordinary);
15000       E->setType(DestType);
15001
15002       // Build the sub-expression as if it were an object of the pointee type.
15003       DestType = Ptr->getPointeeType();
15004       ExprResult SubResult = Visit(E->getSubExpr());
15005       if (SubResult.isInvalid()) return ExprError();
15006       E->setSubExpr(SubResult.get());
15007       return E;
15008     }
15009
15010     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15011
15012     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15013
15014     ExprResult VisitMemberExpr(MemberExpr *E) {
15015       return resolveDecl(E, E->getMemberDecl());
15016     }
15017
15018     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15019       return resolveDecl(E, E->getDecl());
15020     }
15021   };
15022 }
15023
15024 /// Rebuilds a call expression which yielded __unknown_anytype.
15025 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15026   Expr *CalleeExpr = E->getCallee();
15027
15028   enum FnKind {
15029     FK_MemberFunction,
15030     FK_FunctionPointer,
15031     FK_BlockPointer
15032   };
15033
15034   FnKind Kind;
15035   QualType CalleeType = CalleeExpr->getType();
15036   if (CalleeType == S.Context.BoundMemberTy) {
15037     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15038     Kind = FK_MemberFunction;
15039     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15040   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15041     CalleeType = Ptr->getPointeeType();
15042     Kind = FK_FunctionPointer;
15043   } else {
15044     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15045     Kind = FK_BlockPointer;
15046   }
15047   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15048
15049   // Verify that this is a legal result type of a function.
15050   if (DestType->isArrayType() || DestType->isFunctionType()) {
15051     unsigned diagID = diag::err_func_returning_array_function;
15052     if (Kind == FK_BlockPointer)
15053       diagID = diag::err_block_returning_array_function;
15054
15055     S.Diag(E->getExprLoc(), diagID)
15056       << DestType->isFunctionType() << DestType;
15057     return ExprError();
15058   }
15059
15060   // Otherwise, go ahead and set DestType as the call's result.
15061   E->setType(DestType.getNonLValueExprType(S.Context));
15062   E->setValueKind(Expr::getValueKindForType(DestType));
15063   assert(E->getObjectKind() == OK_Ordinary);
15064
15065   // Rebuild the function type, replacing the result type with DestType.
15066   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15067   if (Proto) {
15068     // __unknown_anytype(...) is a special case used by the debugger when
15069     // it has no idea what a function's signature is.
15070     //
15071     // We want to build this call essentially under the K&R
15072     // unprototyped rules, but making a FunctionNoProtoType in C++
15073     // would foul up all sorts of assumptions.  However, we cannot
15074     // simply pass all arguments as variadic arguments, nor can we
15075     // portably just call the function under a non-variadic type; see
15076     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15077     // However, it turns out that in practice it is generally safe to
15078     // call a function declared as "A foo(B,C,D);" under the prototype
15079     // "A foo(B,C,D,...);".  The only known exception is with the
15080     // Windows ABI, where any variadic function is implicitly cdecl
15081     // regardless of its normal CC.  Therefore we change the parameter
15082     // types to match the types of the arguments.
15083     //
15084     // This is a hack, but it is far superior to moving the
15085     // corresponding target-specific code from IR-gen to Sema/AST.
15086
15087     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15088     SmallVector<QualType, 8> ArgTypes;
15089     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15090       ArgTypes.reserve(E->getNumArgs());
15091       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15092         Expr *Arg = E->getArg(i);
15093         QualType ArgType = Arg->getType();
15094         if (E->isLValue()) {
15095           ArgType = S.Context.getLValueReferenceType(ArgType);
15096         } else if (E->isXValue()) {
15097           ArgType = S.Context.getRValueReferenceType(ArgType);
15098         }
15099         ArgTypes.push_back(ArgType);
15100       }
15101       ParamTypes = ArgTypes;
15102     }
15103     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15104                                          Proto->getExtProtoInfo());
15105   } else {
15106     DestType = S.Context.getFunctionNoProtoType(DestType,
15107                                                 FnType->getExtInfo());
15108   }
15109
15110   // Rebuild the appropriate pointer-to-function type.
15111   switch (Kind) { 
15112   case FK_MemberFunction:
15113     // Nothing to do.
15114     break;
15115
15116   case FK_FunctionPointer:
15117     DestType = S.Context.getPointerType(DestType);
15118     break;
15119
15120   case FK_BlockPointer:
15121     DestType = S.Context.getBlockPointerType(DestType);
15122     break;
15123   }
15124
15125   // Finally, we can recurse.
15126   ExprResult CalleeResult = Visit(CalleeExpr);
15127   if (!CalleeResult.isUsable()) return ExprError();
15128   E->setCallee(CalleeResult.get());
15129
15130   // Bind a temporary if necessary.
15131   return S.MaybeBindToTemporary(E);
15132 }
15133
15134 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15135   // Verify that this is a legal result type of a call.
15136   if (DestType->isArrayType() || DestType->isFunctionType()) {
15137     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15138       << DestType->isFunctionType() << DestType;
15139     return ExprError();
15140   }
15141
15142   // Rewrite the method result type if available.
15143   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15144     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15145     Method->setReturnType(DestType);
15146   }
15147
15148   // Change the type of the message.
15149   E->setType(DestType.getNonReferenceType());
15150   E->setValueKind(Expr::getValueKindForType(DestType));
15151
15152   return S.MaybeBindToTemporary(E);
15153 }
15154
15155 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15156   // The only case we should ever see here is a function-to-pointer decay.
15157   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15158     assert(E->getValueKind() == VK_RValue);
15159     assert(E->getObjectKind() == OK_Ordinary);
15160   
15161     E->setType(DestType);
15162   
15163     // Rebuild the sub-expression as the pointee (function) type.
15164     DestType = DestType->castAs<PointerType>()->getPointeeType();
15165   
15166     ExprResult Result = Visit(E->getSubExpr());
15167     if (!Result.isUsable()) return ExprError();
15168   
15169     E->setSubExpr(Result.get());
15170     return E;
15171   } else if (E->getCastKind() == CK_LValueToRValue) {
15172     assert(E->getValueKind() == VK_RValue);
15173     assert(E->getObjectKind() == OK_Ordinary);
15174
15175     assert(isa<BlockPointerType>(E->getType()));
15176
15177     E->setType(DestType);
15178
15179     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15180     DestType = S.Context.getLValueReferenceType(DestType);
15181
15182     ExprResult Result = Visit(E->getSubExpr());
15183     if (!Result.isUsable()) return ExprError();
15184
15185     E->setSubExpr(Result.get());
15186     return E;
15187   } else {
15188     llvm_unreachable("Unhandled cast type!");
15189   }
15190 }
15191
15192 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15193   ExprValueKind ValueKind = VK_LValue;
15194   QualType Type = DestType;
15195
15196   // We know how to make this work for certain kinds of decls:
15197
15198   //  - functions
15199   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15200     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15201       DestType = Ptr->getPointeeType();
15202       ExprResult Result = resolveDecl(E, VD);
15203       if (Result.isInvalid()) return ExprError();
15204       return S.ImpCastExprToType(Result.get(), Type,
15205                                  CK_FunctionToPointerDecay, VK_RValue);
15206     }
15207
15208     if (!Type->isFunctionType()) {
15209       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15210         << VD << E->getSourceRange();
15211       return ExprError();
15212     }
15213     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15214       // We must match the FunctionDecl's type to the hack introduced in
15215       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15216       // type. See the lengthy commentary in that routine.
15217       QualType FDT = FD->getType();
15218       const FunctionType *FnType = FDT->castAs<FunctionType>();
15219       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15220       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15221       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15222         SourceLocation Loc = FD->getLocation();
15223         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15224                                       FD->getDeclContext(),
15225                                       Loc, Loc, FD->getNameInfo().getName(),
15226                                       DestType, FD->getTypeSourceInfo(),
15227                                       SC_None, false/*isInlineSpecified*/,
15228                                       FD->hasPrototype(),
15229                                       false/*isConstexprSpecified*/);
15230           
15231         if (FD->getQualifier())
15232           NewFD->setQualifierInfo(FD->getQualifierLoc());
15233
15234         SmallVector<ParmVarDecl*, 16> Params;
15235         for (const auto &AI : FT->param_types()) {
15236           ParmVarDecl *Param =
15237             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15238           Param->setScopeInfo(0, Params.size());
15239           Params.push_back(Param);
15240         }
15241         NewFD->setParams(Params);
15242         DRE->setDecl(NewFD);
15243         VD = DRE->getDecl();
15244       }
15245     }
15246
15247     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15248       if (MD->isInstance()) {
15249         ValueKind = VK_RValue;
15250         Type = S.Context.BoundMemberTy;
15251       }
15252
15253     // Function references aren't l-values in C.
15254     if (!S.getLangOpts().CPlusPlus)
15255       ValueKind = VK_RValue;
15256
15257   //  - variables
15258   } else if (isa<VarDecl>(VD)) {
15259     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15260       Type = RefTy->getPointeeType();
15261     } else if (Type->isFunctionType()) {
15262       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15263         << VD << E->getSourceRange();
15264       return ExprError();
15265     }
15266
15267   //  - nothing else
15268   } else {
15269     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15270       << VD << E->getSourceRange();
15271     return ExprError();
15272   }
15273
15274   // Modifying the declaration like this is friendly to IR-gen but
15275   // also really dangerous.
15276   VD->setType(DestType);
15277   E->setType(Type);
15278   E->setValueKind(ValueKind);
15279   return E;
15280 }
15281
15282 /// Check a cast of an unknown-any type.  We intentionally only
15283 /// trigger this for C-style casts.
15284 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15285                                      Expr *CastExpr, CastKind &CastKind,
15286                                      ExprValueKind &VK, CXXCastPath &Path) {
15287   // The type we're casting to must be either void or complete.
15288   if (!CastType->isVoidType() &&
15289       RequireCompleteType(TypeRange.getBegin(), CastType,
15290                           diag::err_typecheck_cast_to_incomplete))
15291     return ExprError();
15292
15293   // Rewrite the casted expression from scratch.
15294   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15295   if (!result.isUsable()) return ExprError();
15296
15297   CastExpr = result.get();
15298   VK = CastExpr->getValueKind();
15299   CastKind = CK_NoOp;
15300
15301   return CastExpr;
15302 }
15303
15304 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15305   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15306 }
15307
15308 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15309                                     Expr *arg, QualType &paramType) {
15310   // If the syntactic form of the argument is not an explicit cast of
15311   // any sort, just do default argument promotion.
15312   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15313   if (!castArg) {
15314     ExprResult result = DefaultArgumentPromotion(arg);
15315     if (result.isInvalid()) return ExprError();
15316     paramType = result.get()->getType();
15317     return result;
15318   }
15319
15320   // Otherwise, use the type that was written in the explicit cast.
15321   assert(!arg->hasPlaceholderType());
15322   paramType = castArg->getTypeAsWritten();
15323
15324   // Copy-initialize a parameter of that type.
15325   InitializedEntity entity =
15326     InitializedEntity::InitializeParameter(Context, paramType,
15327                                            /*consumed*/ false);
15328   return PerformCopyInitialization(entity, callLoc, arg);
15329 }
15330
15331 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15332   Expr *orig = E;
15333   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15334   while (true) {
15335     E = E->IgnoreParenImpCasts();
15336     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15337       E = call->getCallee();
15338       diagID = diag::err_uncasted_call_of_unknown_any;
15339     } else {
15340       break;
15341     }
15342   }
15343
15344   SourceLocation loc;
15345   NamedDecl *d;
15346   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15347     loc = ref->getLocation();
15348     d = ref->getDecl();
15349   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15350     loc = mem->getMemberLoc();
15351     d = mem->getMemberDecl();
15352   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15353     diagID = diag::err_uncasted_call_of_unknown_any;
15354     loc = msg->getSelectorStartLoc();
15355     d = msg->getMethodDecl();
15356     if (!d) {
15357       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15358         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15359         << orig->getSourceRange();
15360       return ExprError();
15361     }
15362   } else {
15363     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15364       << E->getSourceRange();
15365     return ExprError();
15366   }
15367
15368   S.Diag(loc, diagID) << d << orig->getSourceRange();
15369
15370   // Never recoverable.
15371   return ExprError();
15372 }
15373
15374 /// Check for operands with placeholder types and complain if found.
15375 /// Returns ExprError() if there was an error and no recovery was possible.
15376 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15377   if (!getLangOpts().CPlusPlus) {
15378     // C cannot handle TypoExpr nodes on either side of a binop because it
15379     // doesn't handle dependent types properly, so make sure any TypoExprs have
15380     // been dealt with before checking the operands.
15381     ExprResult Result = CorrectDelayedTyposInExpr(E);
15382     if (!Result.isUsable()) return ExprError();
15383     E = Result.get();
15384   }
15385
15386   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15387   if (!placeholderType) return E;
15388
15389   switch (placeholderType->getKind()) {
15390
15391   // Overloaded expressions.
15392   case BuiltinType::Overload: {
15393     // Try to resolve a single function template specialization.
15394     // This is obligatory.
15395     ExprResult Result = E;
15396     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15397       return Result;
15398
15399     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15400     // leaves Result unchanged on failure.
15401     Result = E;
15402     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15403       return Result;
15404
15405     // If that failed, try to recover with a call.
15406     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15407                          /*complain*/ true);
15408     return Result;
15409   }
15410
15411   // Bound member functions.
15412   case BuiltinType::BoundMember: {
15413     ExprResult result = E;
15414     const Expr *BME = E->IgnoreParens();
15415     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15416     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15417     if (isa<CXXPseudoDestructorExpr>(BME)) {
15418       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15419     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15420       if (ME->getMemberNameInfo().getName().getNameKind() ==
15421           DeclarationName::CXXDestructorName)
15422         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15423     }
15424     tryToRecoverWithCall(result, PD,
15425                          /*complain*/ true);
15426     return result;
15427   }
15428
15429   // ARC unbridged casts.
15430   case BuiltinType::ARCUnbridgedCast: {
15431     Expr *realCast = stripARCUnbridgedCast(E);
15432     diagnoseARCUnbridgedCast(realCast);
15433     return realCast;
15434   }
15435
15436   // Expressions of unknown type.
15437   case BuiltinType::UnknownAny:
15438     return diagnoseUnknownAnyExpr(*this, E);
15439
15440   // Pseudo-objects.
15441   case BuiltinType::PseudoObject:
15442     return checkPseudoObjectRValue(E);
15443
15444   case BuiltinType::BuiltinFn: {
15445     // Accept __noop without parens by implicitly converting it to a call expr.
15446     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15447     if (DRE) {
15448       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15449       if (FD->getBuiltinID() == Builtin::BI__noop) {
15450         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15451                               CK_BuiltinFnToFnPtr).get();
15452         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15453                                       VK_RValue, SourceLocation());
15454       }
15455     }
15456
15457     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15458     return ExprError();
15459   }
15460
15461   // Expressions of unknown type.
15462   case BuiltinType::OMPArraySection:
15463     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15464     return ExprError();
15465
15466   // Everything else should be impossible.
15467 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15468   case BuiltinType::Id:
15469 #include "clang/Basic/OpenCLImageTypes.def"
15470 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15471 #define PLACEHOLDER_TYPE(Id, SingletonId)
15472 #include "clang/AST/BuiltinTypes.def"
15473     break;
15474   }
15475
15476   llvm_unreachable("invalid placeholder type!");
15477 }
15478
15479 bool Sema::CheckCaseExpression(Expr *E) {
15480   if (E->isTypeDependent())
15481     return true;
15482   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15483     return E->getType()->isIntegralOrEnumerationType();
15484   return false;
15485 }
15486
15487 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15488 ExprResult
15489 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15490   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15491          "Unknown Objective-C Boolean value!");
15492   QualType BoolT = Context.ObjCBuiltinBoolTy;
15493   if (!Context.getBOOLDecl()) {
15494     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15495                         Sema::LookupOrdinaryName);
15496     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15497       NamedDecl *ND = Result.getFoundDecl();
15498       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
15499         Context.setBOOLDecl(TD);
15500     }
15501   }
15502   if (Context.getBOOLDecl())
15503     BoolT = Context.getBOOLType();
15504   return new (Context)
15505       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15506 }
15507
15508 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15509     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15510     SourceLocation RParen) {
15511
15512   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15513
15514   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15515                            [&](const AvailabilitySpec &Spec) {
15516                              return Spec.getPlatform() == Platform;
15517                            });
15518
15519   VersionTuple Version;
15520   if (Spec != AvailSpecs.end())
15521     Version = Spec->getVersion();
15522
15523   return new (Context)
15524       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15525 }