]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
MFV r315875:
[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 && S.getCurFunctionOrMethodDecl()) {
175       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
176       return;
177     }
178
179     const ObjCPropertyDecl *ObjCPDecl = nullptr;
180     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183         if (PDeclResult == Result)
184           ObjCPDecl = PD;
185       }
186     }
187
188     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189                               ObjCPDecl, ObjCPropertyAccess);
190   }
191 }
192
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195   assert(Decl->isDeleted());
196
197   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
198
199   if (Method && Method->isDeleted() && Method->isDefaulted()) {
200     // If the method was explicitly defaulted, point at that declaration.
201     if (!Method->isImplicit())
202       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
203
204     // Try to diagnose why this special member function was implicitly
205     // deleted. This might fail, if that reason no longer applies.
206     CXXSpecialMember CSM = getSpecialMember(Method);
207     if (CSM != CXXInvalid)
208       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
209
210     return;
211   }
212
213   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214   if (Ctor && Ctor->isInheritingConstructor())
215     return NoteDeletedInheritingConstructor(Ctor);
216
217   Diag(Decl->getLocation(), diag::note_availability_specified_here)
218     << Decl << true;
219 }
220
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224   for (auto I : D->redecls()) {
225     if (I->getStorageClass() != SC_None)
226       return true;
227   }
228   return false;
229 }
230
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
233 ///
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
240                                                       const NamedDecl *D,
241                                                       SourceLocation Loc) {
242   // This is disabled under C++; there are too many ways for this to fire in
243   // contexts where the warning is a false positive, or where it is technically
244   // correct but benign.
245   if (S.getLangOpts().CPlusPlus)
246     return;
247
248   // Check if this is an inlined function or method.
249   FunctionDecl *Current = S.getCurFunctionDecl();
250   if (!Current)
251     return;
252   if (!Current->isInlined())
253     return;
254   if (!Current->isExternallyVisible())
255     return;
256
257   // Check if the decl has internal linkage.
258   if (D->getFormalLinkage() != InternalLinkage)
259     return;
260
261   // Downgrade from ExtWarn to Extension if
262   //  (1) the supposedly external inline function is in the main file,
263   //      and probably won't be included anywhere else.
264   //  (2) the thing we're referencing is a pure function.
265   //  (3) the thing we're referencing is another inline function.
266   // This last can give us false negatives, but it's better than warning on
267   // wrappers for simple C library functions.
268   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270   if (!DowngradeWarning && UsedFn)
271     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
272
273   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274                                : diag::ext_internal_in_extern_inline)
275     << /*IsVar=*/!UsedFn << D;
276
277   S.MaybeSuggestAddingStaticToDecl(Current);
278
279   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
280       << D;
281 }
282
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284   const FunctionDecl *First = Cur->getFirstDecl();
285
286   // Suggest "static" on the function, if possible.
287   if (!hasAnyExplicitStorageClass(First)) {
288     SourceLocation DeclBegin = First->getSourceRange().getBegin();
289     Diag(DeclBegin, diag::note_convert_inline_to_static)
290       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
291   }
292 }
293
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
296 ///
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
302 ///
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
305 ///
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307                              const ObjCInterfaceDecl *UnknownObjCClass,
308                              bool ObjCPropertyAccess) {
309   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310     // If there were any diagnostics suppressed by template argument deduction,
311     // emit them now.
312     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313     if (Pos != SuppressedDiagnostics.end()) {
314       for (const PartialDiagnosticAt &Suppressed : Pos->second)
315         Diag(Suppressed.first, Suppressed.second);
316
317       // Clear out the list of suppressed diagnostics, so that we don't emit
318       // them again for this specialization. However, we don't obsolete this
319       // entry from the table, because we want to avoid ever emitting these
320       // diagnostics again.
321       Pos->second.clear();
322     }
323
324     // C++ [basic.start.main]p3:
325     //   The function 'main' shall not be used within a program.
326     if (cast<FunctionDecl>(D)->isMain())
327       Diag(Loc, diag::ext_main_used);
328   }
329
330   // See if this is an auto-typed variable whose initializer we are parsing.
331   if (ParsingInitForAutoVars.count(D)) {
332     if (isa<BindingDecl>(D)) {
333       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
334         << D->getDeclName();
335     } else {
336       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
337
338       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339         << D->getDeclName() << (unsigned)AT->getKeyword();
340     }
341     return true;
342   }
343
344   // See if this is a deleted function.
345   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346     if (FD->isDeleted()) {
347       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
348       if (Ctor && Ctor->isInheritingConstructor())
349         Diag(Loc, diag::err_deleted_inherited_ctor_use)
350             << Ctor->getParent()
351             << Ctor->getInheritedConstructor().getConstructor()->getParent();
352       else 
353         Diag(Loc, diag::err_deleted_function_use);
354       NoteDeletedFunction(FD);
355       return true;
356     }
357
358     // If the function has a deduced return type, and we can't deduce it,
359     // then we can't use it either.
360     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
361         DeduceReturnType(FD, Loc))
362       return true;
363
364     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
365       return true;
366
367     if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
368       return true;
369   }
370
371   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
372   // Only the variables omp_in and omp_out are allowed in the combiner.
373   // Only the variables omp_priv and omp_orig are allowed in the
374   // initializer-clause.
375   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
376   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
377       isa<VarDecl>(D)) {
378     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
379         << getCurFunction()->HasOMPDeclareReductionCombiner;
380     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
381     return true;
382   }
383
384   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
385                              ObjCPropertyAccess);
386
387   DiagnoseUnusedOfDecl(*this, D, Loc);
388
389   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
390
391   return false;
392 }
393
394 /// \brief Retrieve the message suffix that should be added to a
395 /// diagnostic complaining about the given function being deleted or
396 /// unavailable.
397 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
398   std::string Message;
399   if (FD->getAvailability(&Message))
400     return ": " + Message;
401
402   return std::string();
403 }
404
405 /// DiagnoseSentinelCalls - This routine checks whether a call or
406 /// message-send is to a declaration with the sentinel attribute, and
407 /// if so, it checks that the requirements of the sentinel are
408 /// satisfied.
409 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
410                                  ArrayRef<Expr *> Args) {
411   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
412   if (!attr)
413     return;
414
415   // The number of formal parameters of the declaration.
416   unsigned numFormalParams;
417
418   // The kind of declaration.  This is also an index into a %select in
419   // the diagnostic.
420   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
421
422   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
423     numFormalParams = MD->param_size();
424     calleeType = CT_Method;
425   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
426     numFormalParams = FD->param_size();
427     calleeType = CT_Function;
428   } else if (isa<VarDecl>(D)) {
429     QualType type = cast<ValueDecl>(D)->getType();
430     const FunctionType *fn = nullptr;
431     if (const PointerType *ptr = type->getAs<PointerType>()) {
432       fn = ptr->getPointeeType()->getAs<FunctionType>();
433       if (!fn) return;
434       calleeType = CT_Function;
435     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
436       fn = ptr->getPointeeType()->castAs<FunctionType>();
437       calleeType = CT_Block;
438     } else {
439       return;
440     }
441
442     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
443       numFormalParams = proto->getNumParams();
444     } else {
445       numFormalParams = 0;
446     }
447   } else {
448     return;
449   }
450
451   // "nullPos" is the number of formal parameters at the end which
452   // effectively count as part of the variadic arguments.  This is
453   // useful if you would prefer to not have *any* formal parameters,
454   // but the language forces you to have at least one.
455   unsigned nullPos = attr->getNullPos();
456   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
457   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
458
459   // The number of arguments which should follow the sentinel.
460   unsigned numArgsAfterSentinel = attr->getSentinel();
461
462   // If there aren't enough arguments for all the formal parameters,
463   // the sentinel, and the args after the sentinel, complain.
464   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
465     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
466     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
467     return;
468   }
469
470   // Otherwise, find the sentinel expression.
471   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
472   if (!sentinelExpr) return;
473   if (sentinelExpr->isValueDependent()) return;
474   if (Context.isSentinelNullExpr(sentinelExpr)) return;
475
476   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
477   // or 'NULL' if those are actually defined in the context.  Only use
478   // 'nil' for ObjC methods, where it's much more likely that the
479   // variadic arguments form a list of object pointers.
480   SourceLocation MissingNilLoc
481     = getLocForEndOfToken(sentinelExpr->getLocEnd());
482   std::string NullValue;
483   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
484     NullValue = "nil";
485   else if (getLangOpts().CPlusPlus11)
486     NullValue = "nullptr";
487   else if (PP.isMacroDefined("NULL"))
488     NullValue = "NULL";
489   else
490     NullValue = "(void*) 0";
491
492   if (MissingNilLoc.isInvalid())
493     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
494   else
495     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
496       << int(calleeType)
497       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
498   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
499 }
500
501 SourceRange Sema::getExprRange(Expr *E) const {
502   return E ? E->getSourceRange() : SourceRange();
503 }
504
505 //===----------------------------------------------------------------------===//
506 //  Standard Promotions and Conversions
507 //===----------------------------------------------------------------------===//
508
509 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
510 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
511   // Handle any placeholder expressions which made it here.
512   if (E->getType()->isPlaceholderType()) {
513     ExprResult result = CheckPlaceholderExpr(E);
514     if (result.isInvalid()) return ExprError();
515     E = result.get();
516   }
517   
518   QualType Ty = E->getType();
519   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
520
521   if (Ty->isFunctionType()) {
522     // If we are here, we are not calling a function but taking
523     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
524     if (getLangOpts().OpenCL) {
525       if (Diagnose)
526         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
527       return ExprError();
528     }
529
530     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
531       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
532         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
533           return ExprError();
534
535     E = ImpCastExprToType(E, Context.getPointerType(Ty),
536                           CK_FunctionToPointerDecay).get();
537   } else if (Ty->isArrayType()) {
538     // In C90 mode, arrays only promote to pointers if the array expression is
539     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
540     // type 'array of type' is converted to an expression that has type 'pointer
541     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
542     // that has type 'array of type' ...".  The relevant change is "an lvalue"
543     // (C90) to "an expression" (C99).
544     //
545     // C++ 4.2p1:
546     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
547     // T" can be converted to an rvalue of type "pointer to T".
548     //
549     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
550       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
551                             CK_ArrayToPointerDecay).get();
552   }
553   return E;
554 }
555
556 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
557   // Check to see if we are dereferencing a null pointer.  If so,
558   // and if not volatile-qualified, this is undefined behavior that the
559   // optimizer will delete, so warn about it.  People sometimes try to use this
560   // to get a deterministic trap and are surprised by clang's behavior.  This
561   // only handles the pattern "*null", which is a very syntactic check.
562   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
563     if (UO->getOpcode() == UO_Deref &&
564         UO->getSubExpr()->IgnoreParenCasts()->
565           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
566         !UO->getType().isVolatileQualified()) {
567     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568                           S.PDiag(diag::warn_indirection_through_null)
569                             << UO->getSubExpr()->getSourceRange());
570     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571                         S.PDiag(diag::note_indirection_through_null));
572   }
573 }
574
575 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
576                                     SourceLocation AssignLoc,
577                                     const Expr* RHS) {
578   const ObjCIvarDecl *IV = OIRE->getDecl();
579   if (!IV)
580     return;
581   
582   DeclarationName MemberName = IV->getDeclName();
583   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
584   if (!Member || !Member->isStr("isa"))
585     return;
586   
587   const Expr *Base = OIRE->getBase();
588   QualType BaseType = Base->getType();
589   if (OIRE->isArrow())
590     BaseType = BaseType->getPointeeType();
591   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
592     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
593       ObjCInterfaceDecl *ClassDeclared = nullptr;
594       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
595       if (!ClassDeclared->getSuperClass()
596           && (*ClassDeclared->ivar_begin()) == IV) {
597         if (RHS) {
598           NamedDecl *ObjectSetClass =
599             S.LookupSingleName(S.TUScope,
600                                &S.Context.Idents.get("object_setClass"),
601                                SourceLocation(), S.LookupOrdinaryName);
602           if (ObjectSetClass) {
603             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
604             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
605             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
606             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
607                                                      AssignLoc), ",") <<
608             FixItHint::CreateInsertion(RHSLocEnd, ")");
609           }
610           else
611             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
612         } else {
613           NamedDecl *ObjectGetClass =
614             S.LookupSingleName(S.TUScope,
615                                &S.Context.Idents.get("object_getClass"),
616                                SourceLocation(), S.LookupOrdinaryName);
617           if (ObjectGetClass)
618             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
619             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
620             FixItHint::CreateReplacement(
621                                          SourceRange(OIRE->getOpLoc(),
622                                                      OIRE->getLocEnd()), ")");
623           else
624             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
625         }
626         S.Diag(IV->getLocation(), diag::note_ivar_decl);
627       }
628     }
629 }
630
631 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
632   // Handle any placeholder expressions which made it here.
633   if (E->getType()->isPlaceholderType()) {
634     ExprResult result = CheckPlaceholderExpr(E);
635     if (result.isInvalid()) return ExprError();
636     E = result.get();
637   }
638   
639   // C++ [conv.lval]p1:
640   //   A glvalue of a non-function, non-array type T can be
641   //   converted to a prvalue.
642   if (!E->isGLValue()) return E;
643
644   QualType T = E->getType();
645   assert(!T.isNull() && "r-value conversion on typeless expression?");
646
647   // We don't want to throw lvalue-to-rvalue casts on top of
648   // expressions of certain types in C++.
649   if (getLangOpts().CPlusPlus &&
650       (E->getType() == Context.OverloadTy ||
651        T->isDependentType() ||
652        T->isRecordType()))
653     return E;
654
655   // The C standard is actually really unclear on this point, and
656   // DR106 tells us what the result should be but not why.  It's
657   // generally best to say that void types just doesn't undergo
658   // lvalue-to-rvalue at all.  Note that expressions of unqualified
659   // 'void' type are never l-values, but qualified void can be.
660   if (T->isVoidType())
661     return E;
662
663   // OpenCL usually rejects direct accesses to values of 'half' type.
664   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
665       T->isHalfType()) {
666     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667       << 0 << T;
668     return ExprError();
669   }
670
671   CheckForNullPointerDereference(*this, E);
672   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674                                      &Context.Idents.get("object_getClass"),
675                                      SourceLocation(), LookupOrdinaryName);
676     if (ObjectGetClass)
677       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
678         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
679         FixItHint::CreateReplacement(
680                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681     else
682       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683   }
684   else if (const ObjCIvarRefExpr *OIRE =
685             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687
688   // C++ [conv.lval]p1:
689   //   [...] If T is a non-class type, the type of the prvalue is the
690   //   cv-unqualified version of T. Otherwise, the type of the
691   //   rvalue is T.
692   //
693   // C99 6.3.2.1p2:
694   //   If the lvalue has qualified type, the value has the unqualified
695   //   version of the type of the lvalue; otherwise, the value has the
696   //   type of the lvalue.
697   if (T.hasQualifiers())
698     T = T.getUnqualifiedType();
699
700   // Under the MS ABI, lock down the inheritance model now.
701   if (T->isMemberPointerType() &&
702       Context.getTargetInfo().getCXXABI().isMicrosoft())
703     (void)isCompleteType(E->getExprLoc(), T);
704
705   UpdateMarkingForLValueToRValue(E);
706   
707   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
708   // balance that.
709   if (getLangOpts().ObjCAutoRefCount &&
710       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
711     Cleanup.setExprNeedsCleanups(true);
712
713   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
714                                             nullptr, VK_RValue);
715
716   // C11 6.3.2.1p2:
717   //   ... if the lvalue has atomic type, the value has the non-atomic version 
718   //   of the type of the lvalue ...
719   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
720     T = Atomic->getValueType().getUnqualifiedType();
721     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
722                                    nullptr, VK_RValue);
723   }
724   
725   return Res;
726 }
727
728 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
729   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
730   if (Res.isInvalid())
731     return ExprError();
732   Res = DefaultLvalueConversion(Res.get());
733   if (Res.isInvalid())
734     return ExprError();
735   return Res;
736 }
737
738 /// CallExprUnaryConversions - a special case of an unary conversion
739 /// performed on a function designator of a call expression.
740 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
741   QualType Ty = E->getType();
742   ExprResult Res = E;
743   // Only do implicit cast for a function type, but not for a pointer
744   // to function type.
745   if (Ty->isFunctionType()) {
746     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
747                             CK_FunctionToPointerDecay).get();
748     if (Res.isInvalid())
749       return ExprError();
750   }
751   Res = DefaultLvalueConversion(Res.get());
752   if (Res.isInvalid())
753     return ExprError();
754   return Res.get();
755 }
756
757 /// UsualUnaryConversions - Performs various conversions that are common to most
758 /// operators (C99 6.3). The conversions of array and function types are
759 /// sometimes suppressed. For example, the array->pointer conversion doesn't
760 /// apply if the array is an argument to the sizeof or address (&) operators.
761 /// In these instances, this routine should *not* be called.
762 ExprResult Sema::UsualUnaryConversions(Expr *E) {
763   // First, convert to an r-value.
764   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
765   if (Res.isInvalid())
766     return ExprError();
767   E = Res.get();
768
769   QualType Ty = E->getType();
770   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
771
772   // Half FP have to be promoted to float unless it is natively supported
773   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
774     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
775
776   // Try to perform integral promotions if the object has a theoretically
777   // promotable type.
778   if (Ty->isIntegralOrUnscopedEnumerationType()) {
779     // C99 6.3.1.1p2:
780     //
781     //   The following may be used in an expression wherever an int or
782     //   unsigned int may be used:
783     //     - an object or expression with an integer type whose integer
784     //       conversion rank is less than or equal to the rank of int
785     //       and unsigned int.
786     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
787     //
788     //   If an int can represent all values of the original type, the
789     //   value is converted to an int; otherwise, it is converted to an
790     //   unsigned int. These are called the integer promotions. All
791     //   other types are unchanged by the integer promotions.
792
793     QualType PTy = Context.isPromotableBitField(E);
794     if (!PTy.isNull()) {
795       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
796       return E;
797     }
798     if (Ty->isPromotableIntegerType()) {
799       QualType PT = Context.getPromotedIntegerType(Ty);
800       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
801       return E;
802     }
803   }
804   return E;
805 }
806
807 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
808 /// do not have a prototype. Arguments that have type float or __fp16
809 /// are promoted to double. All other argument types are converted by
810 /// UsualUnaryConversions().
811 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
812   QualType Ty = E->getType();
813   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
814
815   ExprResult Res = UsualUnaryConversions(E);
816   if (Res.isInvalid())
817     return ExprError();
818   E = Res.get();
819
820   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
821   // double.
822   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
823   if (BTy && (BTy->getKind() == BuiltinType::Half ||
824               BTy->getKind() == BuiltinType::Float)) {
825     if (getLangOpts().OpenCL &&
826         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
827         if (BTy->getKind() == BuiltinType::Half) {
828             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
829         }
830     } else {
831       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
832     }
833   }
834
835   // C++ performs lvalue-to-rvalue conversion as a default argument
836   // promotion, even on class types, but note:
837   //   C++11 [conv.lval]p2:
838   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
839   //     operand or a subexpression thereof the value contained in the
840   //     referenced object is not accessed. Otherwise, if the glvalue
841   //     has a class type, the conversion copy-initializes a temporary
842   //     of type T from the glvalue and the result of the conversion
843   //     is a prvalue for the temporary.
844   // FIXME: add some way to gate this entire thing for correctness in
845   // potentially potentially evaluated contexts.
846   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
847     ExprResult Temp = PerformCopyInitialization(
848                        InitializedEntity::InitializeTemporary(E->getType()),
849                                                 E->getExprLoc(), E);
850     if (Temp.isInvalid())
851       return ExprError();
852     E = Temp.get();
853   }
854
855   return E;
856 }
857
858 /// Determine the degree of POD-ness for an expression.
859 /// Incomplete types are considered POD, since this check can be performed
860 /// when we're in an unevaluated context.
861 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
862   if (Ty->isIncompleteType()) {
863     // C++11 [expr.call]p7:
864     //   After these conversions, if the argument does not have arithmetic,
865     //   enumeration, pointer, pointer to member, or class type, the program
866     //   is ill-formed.
867     //
868     // Since we've already performed array-to-pointer and function-to-pointer
869     // decay, the only such type in C++ is cv void. This also handles
870     // initializer lists as variadic arguments.
871     if (Ty->isVoidType())
872       return VAK_Invalid;
873
874     if (Ty->isObjCObjectType())
875       return VAK_Invalid;
876     return VAK_Valid;
877   }
878
879   if (Ty.isCXX98PODType(Context))
880     return VAK_Valid;
881
882   // C++11 [expr.call]p7:
883   //   Passing a potentially-evaluated argument of class type (Clause 9)
884   //   having a non-trivial copy constructor, a non-trivial move constructor,
885   //   or a non-trivial destructor, with no corresponding parameter,
886   //   is conditionally-supported with implementation-defined semantics.
887   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
888     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
889       if (!Record->hasNonTrivialCopyConstructor() &&
890           !Record->hasNonTrivialMoveConstructor() &&
891           !Record->hasNonTrivialDestructor())
892         return VAK_ValidInCXX11;
893
894   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
895     return VAK_Valid;
896
897   if (Ty->isObjCObjectType())
898     return VAK_Invalid;
899
900   if (getLangOpts().MSVCCompat)
901     return VAK_MSVCUndefined;
902
903   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
904   // permitted to reject them. We should consider doing so.
905   return VAK_Undefined;
906 }
907
908 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
909   // Don't allow one to pass an Objective-C interface to a vararg.
910   const QualType &Ty = E->getType();
911   VarArgKind VAK = isValidVarArgType(Ty);
912
913   // Complain about passing non-POD types through varargs.
914   switch (VAK) {
915   case VAK_ValidInCXX11:
916     DiagRuntimeBehavior(
917         E->getLocStart(), nullptr,
918         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
919           << Ty << CT);
920     // Fall through.
921   case VAK_Valid:
922     if (Ty->isRecordType()) {
923       // This is unlikely to be what the user intended. If the class has a
924       // 'c_str' member function, the user probably meant to call that.
925       DiagRuntimeBehavior(E->getLocStart(), nullptr,
926                           PDiag(diag::warn_pass_class_arg_to_vararg)
927                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
928     }
929     break;
930
931   case VAK_Undefined:
932   case VAK_MSVCUndefined:
933     DiagRuntimeBehavior(
934         E->getLocStart(), nullptr,
935         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
936           << getLangOpts().CPlusPlus11 << Ty << CT);
937     break;
938
939   case VAK_Invalid:
940     if (Ty->isObjCObjectType())
941       DiagRuntimeBehavior(
942           E->getLocStart(), nullptr,
943           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
944             << Ty << CT);
945     else
946       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
947         << isa<InitListExpr>(E) << Ty << CT;
948     break;
949   }
950 }
951
952 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
953 /// will create a trap if the resulting type is not a POD type.
954 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
955                                                   FunctionDecl *FDecl) {
956   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
957     // Strip the unbridged-cast placeholder expression off, if applicable.
958     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
959         (CT == VariadicMethod ||
960          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
961       E = stripARCUnbridgedCast(E);
962
963     // Otherwise, do normal placeholder checking.
964     } else {
965       ExprResult ExprRes = CheckPlaceholderExpr(E);
966       if (ExprRes.isInvalid())
967         return ExprError();
968       E = ExprRes.get();
969     }
970   }
971   
972   ExprResult ExprRes = DefaultArgumentPromotion(E);
973   if (ExprRes.isInvalid())
974     return ExprError();
975   E = ExprRes.get();
976
977   // Diagnostics regarding non-POD argument types are
978   // emitted along with format string checking in Sema::CheckFunctionCall().
979   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
980     // Turn this into a trap.
981     CXXScopeSpec SS;
982     SourceLocation TemplateKWLoc;
983     UnqualifiedId Name;
984     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
985                        E->getLocStart());
986     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
987                                           Name, true, false);
988     if (TrapFn.isInvalid())
989       return ExprError();
990
991     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
992                                     E->getLocStart(), None,
993                                     E->getLocEnd());
994     if (Call.isInvalid())
995       return ExprError();
996
997     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
998                                   Call.get(), E);
999     if (Comma.isInvalid())
1000       return ExprError();
1001     return Comma.get();
1002   }
1003
1004   if (!getLangOpts().CPlusPlus &&
1005       RequireCompleteType(E->getExprLoc(), E->getType(),
1006                           diag::err_call_incomplete_argument))
1007     return ExprError();
1008
1009   return E;
1010 }
1011
1012 /// \brief Converts an integer to complex float type.  Helper function of
1013 /// UsualArithmeticConversions()
1014 ///
1015 /// \return false if the integer expression is an integer type and is
1016 /// successfully converted to the complex type.
1017 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1018                                                   ExprResult &ComplexExpr,
1019                                                   QualType IntTy,
1020                                                   QualType ComplexTy,
1021                                                   bool SkipCast) {
1022   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1023   if (SkipCast) return false;
1024   if (IntTy->isIntegerType()) {
1025     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1026     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_FloatingRealToComplex);
1029   } else {
1030     assert(IntTy->isComplexIntegerType());
1031     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1032                                   CK_IntegralComplexToFloatingComplex);
1033   }
1034   return false;
1035 }
1036
1037 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1038 /// UsualArithmeticConversions()
1039 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1040                                              ExprResult &RHS, QualType LHSType,
1041                                              QualType RHSType,
1042                                              bool IsCompAssign) {
1043   // if we have an integer operand, the result is the complex type.
1044   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1045                                              /*skipCast*/false))
1046     return LHSType;
1047   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1048                                              /*skipCast*/IsCompAssign))
1049     return RHSType;
1050
1051   // This handles complex/complex, complex/float, or float/complex.
1052   // When both operands are complex, the shorter operand is converted to the
1053   // type of the longer, and that is the type of the result. This corresponds
1054   // to what is done when combining two real floating-point operands.
1055   // The fun begins when size promotion occur across type domains.
1056   // From H&S 6.3.4: When one operand is complex and the other is a real
1057   // floating-point type, the less precise type is converted, within it's
1058   // real or complex domain, to the precision of the other type. For example,
1059   // when combining a "long double" with a "double _Complex", the
1060   // "double _Complex" is promoted to "long double _Complex".
1061
1062   // Compute the rank of the two types, regardless of whether they are complex.
1063   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1064
1065   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1066   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1067   QualType LHSElementType =
1068       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1069   QualType RHSElementType =
1070       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1071
1072   QualType ResultType = S.Context.getComplexType(LHSElementType);
1073   if (Order < 0) {
1074     // Promote the precision of the LHS if not an assignment.
1075     ResultType = S.Context.getComplexType(RHSElementType);
1076     if (!IsCompAssign) {
1077       if (LHSComplexType)
1078         LHS =
1079             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1080       else
1081         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1082     }
1083   } else if (Order > 0) {
1084     // Promote the precision of the RHS.
1085     if (RHSComplexType)
1086       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1087     else
1088       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1089   }
1090   return ResultType;
1091 }
1092
1093 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1094 /// of UsualArithmeticConversions()
1095 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1096                                            ExprResult &IntExpr,
1097                                            QualType FloatTy, QualType IntTy,
1098                                            bool ConvertFloat, bool ConvertInt) {
1099   if (IntTy->isIntegerType()) {
1100     if (ConvertInt)
1101       // Convert intExpr to the lhs floating point type.
1102       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1103                                     CK_IntegralToFloating);
1104     return FloatTy;
1105   }
1106      
1107   // Convert both sides to the appropriate complex float.
1108   assert(IntTy->isComplexIntegerType());
1109   QualType result = S.Context.getComplexType(FloatTy);
1110
1111   // _Complex int -> _Complex float
1112   if (ConvertInt)
1113     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1114                                   CK_IntegralComplexToFloatingComplex);
1115
1116   // float -> _Complex float
1117   if (ConvertFloat)
1118     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1119                                     CK_FloatingRealToComplex);
1120
1121   return result;
1122 }
1123
1124 /// \brief Handle arithmethic conversion with floating point types.  Helper
1125 /// function of UsualArithmeticConversions()
1126 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1127                                       ExprResult &RHS, QualType LHSType,
1128                                       QualType RHSType, bool IsCompAssign) {
1129   bool LHSFloat = LHSType->isRealFloatingType();
1130   bool RHSFloat = RHSType->isRealFloatingType();
1131
1132   // If we have two real floating types, convert the smaller operand
1133   // to the bigger result.
1134   if (LHSFloat && RHSFloat) {
1135     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1136     if (order > 0) {
1137       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1138       return LHSType;
1139     }
1140
1141     assert(order < 0 && "illegal float comparison");
1142     if (!IsCompAssign)
1143       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1144     return RHSType;
1145   }
1146
1147   if (LHSFloat) {
1148     // Half FP has to be promoted to float unless it is natively supported
1149     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1150       LHSType = S.Context.FloatTy;
1151
1152     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1153                                       /*convertFloat=*/!IsCompAssign,
1154                                       /*convertInt=*/ true);
1155   }
1156   assert(RHSFloat);
1157   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1158                                     /*convertInt=*/ true,
1159                                     /*convertFloat=*/!IsCompAssign);
1160 }
1161
1162 /// \brief Diagnose attempts to convert between __float128 and long double if
1163 /// there is no support for such conversion. Helper function of
1164 /// UsualArithmeticConversions().
1165 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1166                                       QualType RHSType) {
1167   /*  No issue converting if at least one of the types is not a floating point
1168       type or the two types have the same rank.
1169   */
1170   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1171       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1172     return false;
1173
1174   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1175          "The remaining types must be floating point types.");
1176
1177   auto *LHSComplex = LHSType->getAs<ComplexType>();
1178   auto *RHSComplex = RHSType->getAs<ComplexType>();
1179
1180   QualType LHSElemType = LHSComplex ?
1181     LHSComplex->getElementType() : LHSType;
1182   QualType RHSElemType = RHSComplex ?
1183     RHSComplex->getElementType() : RHSType;
1184
1185   // No issue if the two types have the same representation
1186   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1187       &S.Context.getFloatTypeSemantics(RHSElemType))
1188     return false;
1189
1190   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1191                                 RHSElemType == S.Context.LongDoubleTy);
1192   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1193                             RHSElemType == S.Context.Float128Ty);
1194
1195   /* We've handled the situation where __float128 and long double have the same
1196      representation. The only other allowable conversion is if long double is
1197      really just double.
1198   */
1199   return Float128AndLongDouble &&
1200     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1201      &llvm::APFloat::IEEEdouble());
1202 }
1203
1204 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1205
1206 namespace {
1207 /// These helper callbacks are placed in an anonymous namespace to
1208 /// permit their use as function template parameters.
1209 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1211 }
1212
1213 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1214   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1215                              CK_IntegralComplexCast);
1216 }
1217 }
1218
1219 /// \brief Handle integer arithmetic conversions.  Helper function of
1220 /// UsualArithmeticConversions()
1221 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1222 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1223                                         ExprResult &RHS, QualType LHSType,
1224                                         QualType RHSType, bool IsCompAssign) {
1225   // The rules for this case are in C99 6.3.1.8
1226   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1227   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1228   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1229   if (LHSSigned == RHSSigned) {
1230     // Same signedness; use the higher-ranked type
1231     if (order >= 0) {
1232       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1233       return LHSType;
1234     } else if (!IsCompAssign)
1235       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1236     return RHSType;
1237   } else if (order != (LHSSigned ? 1 : -1)) {
1238     // The unsigned type has greater than or equal rank to the
1239     // signed type, so use the unsigned type
1240     if (RHSSigned) {
1241       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1242       return LHSType;
1243     } else if (!IsCompAssign)
1244       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1245     return RHSType;
1246   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1247     // The two types are different widths; if we are here, that
1248     // means the signed type is larger than the unsigned type, so
1249     // use the signed type.
1250     if (LHSSigned) {
1251       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1252       return LHSType;
1253     } else if (!IsCompAssign)
1254       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1255     return RHSType;
1256   } else {
1257     // The signed type is higher-ranked than the unsigned type,
1258     // but isn't actually any bigger (like unsigned int and long
1259     // on most 32-bit systems).  Use the unsigned type corresponding
1260     // to the signed type.
1261     QualType result =
1262       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1263     RHS = (*doRHSCast)(S, RHS.get(), result);
1264     if (!IsCompAssign)
1265       LHS = (*doLHSCast)(S, LHS.get(), result);
1266     return result;
1267   }
1268 }
1269
1270 /// \brief Handle conversions with GCC complex int extension.  Helper function
1271 /// of UsualArithmeticConversions()
1272 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1273                                            ExprResult &RHS, QualType LHSType,
1274                                            QualType RHSType,
1275                                            bool IsCompAssign) {
1276   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1277   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1278
1279   if (LHSComplexInt && RHSComplexInt) {
1280     QualType LHSEltType = LHSComplexInt->getElementType();
1281     QualType RHSEltType = RHSComplexInt->getElementType();
1282     QualType ScalarType =
1283       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1284         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1285
1286     return S.Context.getComplexType(ScalarType);
1287   }
1288
1289   if (LHSComplexInt) {
1290     QualType LHSEltType = LHSComplexInt->getElementType();
1291     QualType ScalarType =
1292       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1293         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1294     QualType ComplexType = S.Context.getComplexType(ScalarType);
1295     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1296                               CK_IntegralRealToComplex);
1297  
1298     return ComplexType;
1299   }
1300
1301   assert(RHSComplexInt);
1302
1303   QualType RHSEltType = RHSComplexInt->getElementType();
1304   QualType ScalarType =
1305     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1306       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1307   QualType ComplexType = S.Context.getComplexType(ScalarType);
1308   
1309   if (!IsCompAssign)
1310     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1311                               CK_IntegralRealToComplex);
1312   return ComplexType;
1313 }
1314
1315 /// UsualArithmeticConversions - Performs various conversions that are common to
1316 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1317 /// routine returns the first non-arithmetic type found. The client is
1318 /// responsible for emitting appropriate error diagnostics.
1319 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1320                                           bool IsCompAssign) {
1321   if (!IsCompAssign) {
1322     LHS = UsualUnaryConversions(LHS.get());
1323     if (LHS.isInvalid())
1324       return QualType();
1325   }
1326
1327   RHS = UsualUnaryConversions(RHS.get());
1328   if (RHS.isInvalid())
1329     return QualType();
1330
1331   // For conversion purposes, we ignore any qualifiers.
1332   // For example, "const float" and "float" are equivalent.
1333   QualType LHSType =
1334     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1335   QualType RHSType =
1336     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1337
1338   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1339   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1340     LHSType = AtomicLHS->getValueType();
1341
1342   // If both types are identical, no conversion is needed.
1343   if (LHSType == RHSType)
1344     return LHSType;
1345
1346   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1347   // The caller can deal with this (e.g. pointer + int).
1348   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1349     return QualType();
1350
1351   // Apply unary and bitfield promotions to the LHS's type.
1352   QualType LHSUnpromotedType = LHSType;
1353   if (LHSType->isPromotableIntegerType())
1354     LHSType = Context.getPromotedIntegerType(LHSType);
1355   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1356   if (!LHSBitfieldPromoteTy.isNull())
1357     LHSType = LHSBitfieldPromoteTy;
1358   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1359     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1360
1361   // If both types are identical, no conversion is needed.
1362   if (LHSType == RHSType)
1363     return LHSType;
1364
1365   // At this point, we have two different arithmetic types.
1366
1367   // Diagnose attempts to convert between __float128 and long double where
1368   // such conversions currently can't be handled.
1369   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1370     return QualType();
1371
1372   // Handle complex types first (C99 6.3.1.8p1).
1373   if (LHSType->isComplexType() || RHSType->isComplexType())
1374     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1375                                         IsCompAssign);
1376
1377   // Now handle "real" floating types (i.e. float, double, long double).
1378   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1379     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1380                                  IsCompAssign);
1381
1382   // Handle GCC complex int extension.
1383   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1384     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1385                                       IsCompAssign);
1386
1387   // Finally, we have two differing integer types.
1388   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1389            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1390 }
1391
1392
1393 //===----------------------------------------------------------------------===//
1394 //  Semantic Analysis for various Expression Types
1395 //===----------------------------------------------------------------------===//
1396
1397
1398 ExprResult
1399 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1400                                 SourceLocation DefaultLoc,
1401                                 SourceLocation RParenLoc,
1402                                 Expr *ControllingExpr,
1403                                 ArrayRef<ParsedType> ArgTypes,
1404                                 ArrayRef<Expr *> ArgExprs) {
1405   unsigned NumAssocs = ArgTypes.size();
1406   assert(NumAssocs == ArgExprs.size());
1407
1408   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1409   for (unsigned i = 0; i < NumAssocs; ++i) {
1410     if (ArgTypes[i])
1411       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1412     else
1413       Types[i] = nullptr;
1414   }
1415
1416   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1417                                              ControllingExpr,
1418                                              llvm::makeArrayRef(Types, NumAssocs),
1419                                              ArgExprs);
1420   delete [] Types;
1421   return ER;
1422 }
1423
1424 ExprResult
1425 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1426                                  SourceLocation DefaultLoc,
1427                                  SourceLocation RParenLoc,
1428                                  Expr *ControllingExpr,
1429                                  ArrayRef<TypeSourceInfo *> Types,
1430                                  ArrayRef<Expr *> Exprs) {
1431   unsigned NumAssocs = Types.size();
1432   assert(NumAssocs == Exprs.size());
1433
1434   // Decay and strip qualifiers for the controlling expression type, and handle
1435   // placeholder type replacement. See committee discussion from WG14 DR423.
1436   {
1437     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1438     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1439     if (R.isInvalid())
1440       return ExprError();
1441     ControllingExpr = R.get();
1442   }
1443
1444   // The controlling expression is an unevaluated operand, so side effects are
1445   // likely unintended.
1446   if (ActiveTemplateInstantiations.empty() &&
1447       ControllingExpr->HasSideEffects(Context, false))
1448     Diag(ControllingExpr->getExprLoc(),
1449          diag::warn_side_effects_unevaluated_context);
1450
1451   bool TypeErrorFound = false,
1452        IsResultDependent = ControllingExpr->isTypeDependent(),
1453        ContainsUnexpandedParameterPack
1454          = ControllingExpr->containsUnexpandedParameterPack();
1455
1456   for (unsigned i = 0; i < NumAssocs; ++i) {
1457     if (Exprs[i]->containsUnexpandedParameterPack())
1458       ContainsUnexpandedParameterPack = true;
1459
1460     if (Types[i]) {
1461       if (Types[i]->getType()->containsUnexpandedParameterPack())
1462         ContainsUnexpandedParameterPack = true;
1463
1464       if (Types[i]->getType()->isDependentType()) {
1465         IsResultDependent = true;
1466       } else {
1467         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1468         // complete object type other than a variably modified type."
1469         unsigned D = 0;
1470         if (Types[i]->getType()->isIncompleteType())
1471           D = diag::err_assoc_type_incomplete;
1472         else if (!Types[i]->getType()->isObjectType())
1473           D = diag::err_assoc_type_nonobject;
1474         else if (Types[i]->getType()->isVariablyModifiedType())
1475           D = diag::err_assoc_type_variably_modified;
1476
1477         if (D != 0) {
1478           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1479             << Types[i]->getTypeLoc().getSourceRange()
1480             << Types[i]->getType();
1481           TypeErrorFound = true;
1482         }
1483
1484         // C11 6.5.1.1p2 "No two generic associations in the same generic
1485         // selection shall specify compatible types."
1486         for (unsigned j = i+1; j < NumAssocs; ++j)
1487           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1488               Context.typesAreCompatible(Types[i]->getType(),
1489                                          Types[j]->getType())) {
1490             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1491                  diag::err_assoc_compatible_types)
1492               << Types[j]->getTypeLoc().getSourceRange()
1493               << Types[j]->getType()
1494               << Types[i]->getType();
1495             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1496                  diag::note_compat_assoc)
1497               << Types[i]->getTypeLoc().getSourceRange()
1498               << Types[i]->getType();
1499             TypeErrorFound = true;
1500           }
1501       }
1502     }
1503   }
1504   if (TypeErrorFound)
1505     return ExprError();
1506
1507   // If we determined that the generic selection is result-dependent, don't
1508   // try to compute the result expression.
1509   if (IsResultDependent)
1510     return new (Context) GenericSelectionExpr(
1511         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1512         ContainsUnexpandedParameterPack);
1513
1514   SmallVector<unsigned, 1> CompatIndices;
1515   unsigned DefaultIndex = -1U;
1516   for (unsigned i = 0; i < NumAssocs; ++i) {
1517     if (!Types[i])
1518       DefaultIndex = i;
1519     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1520                                         Types[i]->getType()))
1521       CompatIndices.push_back(i);
1522   }
1523
1524   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1525   // type compatible with at most one of the types named in its generic
1526   // association list."
1527   if (CompatIndices.size() > 1) {
1528     // We strip parens here because the controlling expression is typically
1529     // parenthesized in macro definitions.
1530     ControllingExpr = ControllingExpr->IgnoreParens();
1531     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1532       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1533       << (unsigned) CompatIndices.size();
1534     for (unsigned I : CompatIndices) {
1535       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1536            diag::note_compat_assoc)
1537         << Types[I]->getTypeLoc().getSourceRange()
1538         << Types[I]->getType();
1539     }
1540     return ExprError();
1541   }
1542
1543   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1544   // its controlling expression shall have type compatible with exactly one of
1545   // the types named in its generic association list."
1546   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1547     // We strip parens here because the controlling expression is typically
1548     // parenthesized in macro definitions.
1549     ControllingExpr = ControllingExpr->IgnoreParens();
1550     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1551       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1552     return ExprError();
1553   }
1554
1555   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1556   // type name that is compatible with the type of the controlling expression,
1557   // then the result expression of the generic selection is the expression
1558   // in that generic association. Otherwise, the result expression of the
1559   // generic selection is the expression in the default generic association."
1560   unsigned ResultIndex =
1561     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1562
1563   return new (Context) GenericSelectionExpr(
1564       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1565       ContainsUnexpandedParameterPack, ResultIndex);
1566 }
1567
1568 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1569 /// location of the token and the offset of the ud-suffix within it.
1570 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1571                                      unsigned Offset) {
1572   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1573                                         S.getLangOpts());
1574 }
1575
1576 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1577 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1578 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1579                                                  IdentifierInfo *UDSuffix,
1580                                                  SourceLocation UDSuffixLoc,
1581                                                  ArrayRef<Expr*> Args,
1582                                                  SourceLocation LitEndLoc) {
1583   assert(Args.size() <= 2 && "too many arguments for literal operator");
1584
1585   QualType ArgTy[2];
1586   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1587     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1588     if (ArgTy[ArgIdx]->isArrayType())
1589       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1590   }
1591
1592   DeclarationName OpName =
1593     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1594   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1595   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1596
1597   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1598   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1599                               /*AllowRaw*/false, /*AllowTemplate*/false,
1600                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1601     return ExprError();
1602
1603   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1604 }
1605
1606 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1607 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1608 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1609 /// multiple tokens.  However, the common case is that StringToks points to one
1610 /// string.
1611 ///
1612 ExprResult
1613 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1614   assert(!StringToks.empty() && "Must have at least one string!");
1615
1616   StringLiteralParser Literal(StringToks, PP);
1617   if (Literal.hadError)
1618     return ExprError();
1619
1620   SmallVector<SourceLocation, 4> StringTokLocs;
1621   for (const Token &Tok : StringToks)
1622     StringTokLocs.push_back(Tok.getLocation());
1623
1624   QualType CharTy = Context.CharTy;
1625   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1626   if (Literal.isWide()) {
1627     CharTy = Context.getWideCharType();
1628     Kind = StringLiteral::Wide;
1629   } else if (Literal.isUTF8()) {
1630     Kind = StringLiteral::UTF8;
1631   } else if (Literal.isUTF16()) {
1632     CharTy = Context.Char16Ty;
1633     Kind = StringLiteral::UTF16;
1634   } else if (Literal.isUTF32()) {
1635     CharTy = Context.Char32Ty;
1636     Kind = StringLiteral::UTF32;
1637   } else if (Literal.isPascal()) {
1638     CharTy = Context.UnsignedCharTy;
1639   }
1640
1641   QualType CharTyConst = CharTy;
1642   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1643   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1644     CharTyConst.addConst();
1645
1646   // Get an array type for the string, according to C99 6.4.5.  This includes
1647   // the nul terminator character as well as the string length for pascal
1648   // strings.
1649   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1650                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1651                                  ArrayType::Normal, 0);
1652
1653   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1654   if (getLangOpts().OpenCL) {
1655     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1656   }
1657
1658   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1659   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1660                                              Kind, Literal.Pascal, StrTy,
1661                                              &StringTokLocs[0],
1662                                              StringTokLocs.size());
1663   if (Literal.getUDSuffix().empty())
1664     return Lit;
1665
1666   // We're building a user-defined literal.
1667   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1668   SourceLocation UDSuffixLoc =
1669     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1670                    Literal.getUDSuffixOffset());
1671
1672   // Make sure we're allowed user-defined literals here.
1673   if (!UDLScope)
1674     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1675
1676   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1677   //   operator "" X (str, len)
1678   QualType SizeType = Context.getSizeType();
1679
1680   DeclarationName OpName =
1681     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1682   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1683   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1684
1685   QualType ArgTy[] = {
1686     Context.getArrayDecayedType(StrTy), SizeType
1687   };
1688
1689   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1690   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1691                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1692                                 /*AllowStringTemplate*/true)) {
1693
1694   case LOLR_Cooked: {
1695     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1696     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1697                                                     StringTokLocs[0]);
1698     Expr *Args[] = { Lit, LenArg };
1699
1700     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1701   }
1702
1703   case LOLR_StringTemplate: {
1704     TemplateArgumentListInfo ExplicitArgs;
1705
1706     unsigned CharBits = Context.getIntWidth(CharTy);
1707     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1708     llvm::APSInt Value(CharBits, CharIsUnsigned);
1709
1710     TemplateArgument TypeArg(CharTy);
1711     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1712     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1713
1714     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1715       Value = Lit->getCodeUnit(I);
1716       TemplateArgument Arg(Context, Value, CharTy);
1717       TemplateArgumentLocInfo ArgInfo;
1718       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1719     }
1720     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1721                                     &ExplicitArgs);
1722   }
1723   case LOLR_Raw:
1724   case LOLR_Template:
1725     llvm_unreachable("unexpected literal operator lookup result");
1726   case LOLR_Error:
1727     return ExprError();
1728   }
1729   llvm_unreachable("unexpected literal operator lookup result");
1730 }
1731
1732 ExprResult
1733 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1734                        SourceLocation Loc,
1735                        const CXXScopeSpec *SS) {
1736   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1737   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1738 }
1739
1740 /// BuildDeclRefExpr - Build an expression that references a
1741 /// declaration that does not require a closure capture.
1742 ExprResult
1743 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1744                        const DeclarationNameInfo &NameInfo,
1745                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1746                        const TemplateArgumentListInfo *TemplateArgs) {
1747   bool RefersToCapturedVariable =
1748       isa<VarDecl>(D) &&
1749       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1750
1751   DeclRefExpr *E;
1752   if (isa<VarTemplateSpecializationDecl>(D)) {
1753     VarTemplateSpecializationDecl *VarSpec =
1754         cast<VarTemplateSpecializationDecl>(D);
1755
1756     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1757                                         : NestedNameSpecifierLoc(),
1758                             VarSpec->getTemplateKeywordLoc(), D,
1759                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1760                             FoundD, TemplateArgs);
1761   } else {
1762     assert(!TemplateArgs && "No template arguments for non-variable"
1763                             " template specialization references");
1764     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1765                                         : NestedNameSpecifierLoc(),
1766                             SourceLocation(), D, RefersToCapturedVariable,
1767                             NameInfo, Ty, VK, FoundD);
1768   }
1769
1770   MarkDeclRefReferenced(E);
1771
1772   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1773       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1774       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1775       recordUseOfEvaluatedWeak(E);
1776
1777   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1778     UnusedPrivateFields.remove(FD);
1779     // Just in case we're building an illegal pointer-to-member.
1780     if (FD->isBitField())
1781       E->setObjectKind(OK_BitField);
1782   }
1783
1784   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1785   // designates a bit-field.
1786   if (auto *BD = dyn_cast<BindingDecl>(D))
1787     if (auto *BE = BD->getBinding())
1788       E->setObjectKind(BE->getObjectKind());
1789
1790   return E;
1791 }
1792
1793 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1794 /// possibly a list of template arguments.
1795 ///
1796 /// If this produces template arguments, it is permitted to call
1797 /// DecomposeTemplateName.
1798 ///
1799 /// This actually loses a lot of source location information for
1800 /// non-standard name kinds; we should consider preserving that in
1801 /// some way.
1802 void
1803 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1804                              TemplateArgumentListInfo &Buffer,
1805                              DeclarationNameInfo &NameInfo,
1806                              const TemplateArgumentListInfo *&TemplateArgs) {
1807   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1808     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1809     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1810
1811     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1812                                        Id.TemplateId->NumArgs);
1813     translateTemplateArguments(TemplateArgsPtr, Buffer);
1814
1815     TemplateName TName = Id.TemplateId->Template.get();
1816     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1817     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1818     TemplateArgs = &Buffer;
1819   } else {
1820     NameInfo = GetNameFromUnqualifiedId(Id);
1821     TemplateArgs = nullptr;
1822   }
1823 }
1824
1825 static void emitEmptyLookupTypoDiagnostic(
1826     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1827     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1828     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1829   DeclContext *Ctx =
1830       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1831   if (!TC) {
1832     // Emit a special diagnostic for failed member lookups.
1833     // FIXME: computing the declaration context might fail here (?)
1834     if (Ctx)
1835       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1836                                                  << SS.getRange();
1837     else
1838       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1839     return;
1840   }
1841
1842   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1843   bool DroppedSpecifier =
1844       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1845   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1846                         ? diag::note_implicit_param_decl
1847                         : diag::note_previous_decl;
1848   if (!Ctx)
1849     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1850                          SemaRef.PDiag(NoteID));
1851   else
1852     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1853                                  << Typo << Ctx << DroppedSpecifier
1854                                  << SS.getRange(),
1855                          SemaRef.PDiag(NoteID));
1856 }
1857
1858 /// Diagnose an empty lookup.
1859 ///
1860 /// \return false if new lookup candidates were found
1861 bool
1862 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1863                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1864                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1865                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1866   DeclarationName Name = R.getLookupName();
1867
1868   unsigned diagnostic = diag::err_undeclared_var_use;
1869   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1870   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1871       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1872       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1873     diagnostic = diag::err_undeclared_use;
1874     diagnostic_suggest = diag::err_undeclared_use_suggest;
1875   }
1876
1877   // If the original lookup was an unqualified lookup, fake an
1878   // unqualified lookup.  This is useful when (for example) the
1879   // original lookup would not have found something because it was a
1880   // dependent name.
1881   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1882   while (DC) {
1883     if (isa<CXXRecordDecl>(DC)) {
1884       LookupQualifiedName(R, DC);
1885
1886       if (!R.empty()) {
1887         // Don't give errors about ambiguities in this lookup.
1888         R.suppressDiagnostics();
1889
1890         // During a default argument instantiation the CurContext points
1891         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1892         // function parameter list, hence add an explicit check.
1893         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1894                               ActiveTemplateInstantiations.back().Kind ==
1895             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1896         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1897         bool isInstance = CurMethod &&
1898                           CurMethod->isInstance() &&
1899                           DC == CurMethod->getParent() && !isDefaultArgument;
1900
1901         // Give a code modification hint to insert 'this->'.
1902         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1903         // Actually quite difficult!
1904         if (getLangOpts().MSVCCompat)
1905           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1906         if (isInstance) {
1907           Diag(R.getNameLoc(), diagnostic) << Name
1908             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1909           CheckCXXThisCapture(R.getNameLoc());
1910         } else {
1911           Diag(R.getNameLoc(), diagnostic) << Name;
1912         }
1913
1914         // Do we really want to note all of these?
1915         for (NamedDecl *D : R)
1916           Diag(D->getLocation(), diag::note_dependent_var_use);
1917
1918         // Return true if we are inside a default argument instantiation
1919         // and the found name refers to an instance member function, otherwise
1920         // the function calling DiagnoseEmptyLookup will try to create an
1921         // implicit member call and this is wrong for default argument.
1922         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1923           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1924           return true;
1925         }
1926
1927         // Tell the callee to try to recover.
1928         return false;
1929       }
1930
1931       R.clear();
1932     }
1933
1934     // In Microsoft mode, if we are performing lookup from within a friend
1935     // function definition declared at class scope then we must set
1936     // DC to the lexical parent to be able to search into the parent
1937     // class.
1938     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1939         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1940         DC->getLexicalParent()->isRecord())
1941       DC = DC->getLexicalParent();
1942     else
1943       DC = DC->getParent();
1944   }
1945
1946   // We didn't find anything, so try to correct for a typo.
1947   TypoCorrection Corrected;
1948   if (S && Out) {
1949     SourceLocation TypoLoc = R.getNameLoc();
1950     assert(!ExplicitTemplateArgs &&
1951            "Diagnosing an empty lookup with explicit template args!");
1952     *Out = CorrectTypoDelayed(
1953         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1954         [=](const TypoCorrection &TC) {
1955           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1956                                         diagnostic, diagnostic_suggest);
1957         },
1958         nullptr, CTK_ErrorRecovery);
1959     if (*Out)
1960       return true;
1961   } else if (S && (Corrected =
1962                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1963                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1964     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1965     bool DroppedSpecifier =
1966         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1967     R.setLookupName(Corrected.getCorrection());
1968
1969     bool AcceptableWithRecovery = false;
1970     bool AcceptableWithoutRecovery = false;
1971     NamedDecl *ND = Corrected.getFoundDecl();
1972     if (ND) {
1973       if (Corrected.isOverloaded()) {
1974         OverloadCandidateSet OCS(R.getNameLoc(),
1975                                  OverloadCandidateSet::CSK_Normal);
1976         OverloadCandidateSet::iterator Best;
1977         for (NamedDecl *CD : Corrected) {
1978           if (FunctionTemplateDecl *FTD =
1979                    dyn_cast<FunctionTemplateDecl>(CD))
1980             AddTemplateOverloadCandidate(
1981                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1982                 Args, OCS);
1983           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1984             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1985               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1986                                    Args, OCS);
1987         }
1988         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1989         case OR_Success:
1990           ND = Best->FoundDecl;
1991           Corrected.setCorrectionDecl(ND);
1992           break;
1993         default:
1994           // FIXME: Arbitrarily pick the first declaration for the note.
1995           Corrected.setCorrectionDecl(ND);
1996           break;
1997         }
1998       }
1999       R.addDecl(ND);
2000       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2001         CXXRecordDecl *Record = nullptr;
2002         if (Corrected.getCorrectionSpecifier()) {
2003           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2004           Record = Ty->getAsCXXRecordDecl();
2005         }
2006         if (!Record)
2007           Record = cast<CXXRecordDecl>(
2008               ND->getDeclContext()->getRedeclContext());
2009         R.setNamingClass(Record);
2010       }
2011
2012       auto *UnderlyingND = ND->getUnderlyingDecl();
2013       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2014                                isa<FunctionTemplateDecl>(UnderlyingND);
2015       // FIXME: If we ended up with a typo for a type name or
2016       // Objective-C class name, we're in trouble because the parser
2017       // is in the wrong place to recover. Suggest the typo
2018       // correction, but don't make it a fix-it since we're not going
2019       // to recover well anyway.
2020       AcceptableWithoutRecovery =
2021           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2022     } else {
2023       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2024       // because we aren't able to recover.
2025       AcceptableWithoutRecovery = true;
2026     }
2027
2028     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2029       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2030                             ? diag::note_implicit_param_decl
2031                             : diag::note_previous_decl;
2032       if (SS.isEmpty())
2033         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2034                      PDiag(NoteID), AcceptableWithRecovery);
2035       else
2036         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2037                                   << Name << computeDeclContext(SS, false)
2038                                   << DroppedSpecifier << SS.getRange(),
2039                      PDiag(NoteID), AcceptableWithRecovery);
2040
2041       // Tell the callee whether to try to recover.
2042       return !AcceptableWithRecovery;
2043     }
2044   }
2045   R.clear();
2046
2047   // Emit a special diagnostic for failed member lookups.
2048   // FIXME: computing the declaration context might fail here (?)
2049   if (!SS.isEmpty()) {
2050     Diag(R.getNameLoc(), diag::err_no_member)
2051       << Name << computeDeclContext(SS, false)
2052       << SS.getRange();
2053     return true;
2054   }
2055
2056   // Give up, we can't recover.
2057   Diag(R.getNameLoc(), diagnostic) << Name;
2058   return true;
2059 }
2060
2061 /// In Microsoft mode, if we are inside a template class whose parent class has
2062 /// dependent base classes, and we can't resolve an unqualified identifier, then
2063 /// assume the identifier is a member of a dependent base class.  We can only
2064 /// recover successfully in static methods, instance methods, and other contexts
2065 /// where 'this' is available.  This doesn't precisely match MSVC's
2066 /// instantiation model, but it's close enough.
2067 static Expr *
2068 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2069                                DeclarationNameInfo &NameInfo,
2070                                SourceLocation TemplateKWLoc,
2071                                const TemplateArgumentListInfo *TemplateArgs) {
2072   // Only try to recover from lookup into dependent bases in static methods or
2073   // contexts where 'this' is available.
2074   QualType ThisType = S.getCurrentThisType();
2075   const CXXRecordDecl *RD = nullptr;
2076   if (!ThisType.isNull())
2077     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2078   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2079     RD = MD->getParent();
2080   if (!RD || !RD->hasAnyDependentBases())
2081     return nullptr;
2082
2083   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2084   // is available, suggest inserting 'this->' as a fixit.
2085   SourceLocation Loc = NameInfo.getLoc();
2086   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2087   DB << NameInfo.getName() << RD;
2088
2089   if (!ThisType.isNull()) {
2090     DB << FixItHint::CreateInsertion(Loc, "this->");
2091     return CXXDependentScopeMemberExpr::Create(
2092         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2093         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2094         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2095   }
2096
2097   // Synthesize a fake NNS that points to the derived class.  This will
2098   // perform name lookup during template instantiation.
2099   CXXScopeSpec SS;
2100   auto *NNS =
2101       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2102   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2103   return DependentScopeDeclRefExpr::Create(
2104       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2105       TemplateArgs);
2106 }
2107
2108 ExprResult
2109 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2110                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2111                         bool HasTrailingLParen, bool IsAddressOfOperand,
2112                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2113                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2114   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2115          "cannot be direct & operand and have a trailing lparen");
2116   if (SS.isInvalid())
2117     return ExprError();
2118
2119   TemplateArgumentListInfo TemplateArgsBuffer;
2120
2121   // Decompose the UnqualifiedId into the following data.
2122   DeclarationNameInfo NameInfo;
2123   const TemplateArgumentListInfo *TemplateArgs;
2124   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2125
2126   DeclarationName Name = NameInfo.getName();
2127   IdentifierInfo *II = Name.getAsIdentifierInfo();
2128   SourceLocation NameLoc = NameInfo.getLoc();
2129
2130   // C++ [temp.dep.expr]p3:
2131   //   An id-expression is type-dependent if it contains:
2132   //     -- an identifier that was declared with a dependent type,
2133   //        (note: handled after lookup)
2134   //     -- a template-id that is dependent,
2135   //        (note: handled in BuildTemplateIdExpr)
2136   //     -- a conversion-function-id that specifies a dependent type,
2137   //     -- a nested-name-specifier that contains a class-name that
2138   //        names a dependent type.
2139   // Determine whether this is a member of an unknown specialization;
2140   // we need to handle these differently.
2141   bool DependentID = false;
2142   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2143       Name.getCXXNameType()->isDependentType()) {
2144     DependentID = true;
2145   } else if (SS.isSet()) {
2146     if (DeclContext *DC = computeDeclContext(SS, false)) {
2147       if (RequireCompleteDeclContext(SS, DC))
2148         return ExprError();
2149     } else {
2150       DependentID = true;
2151     }
2152   }
2153
2154   if (DependentID)
2155     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2156                                       IsAddressOfOperand, TemplateArgs);
2157
2158   // Perform the required lookup.
2159   LookupResult R(*this, NameInfo, 
2160                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2161                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2162   if (TemplateArgs) {
2163     // Lookup the template name again to correctly establish the context in
2164     // which it was found. This is really unfortunate as we already did the
2165     // lookup to determine that it was a template name in the first place. If
2166     // this becomes a performance hit, we can work harder to preserve those
2167     // results until we get here but it's likely not worth it.
2168     bool MemberOfUnknownSpecialization;
2169     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2170                        MemberOfUnknownSpecialization);
2171     
2172     if (MemberOfUnknownSpecialization ||
2173         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2174       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2175                                         IsAddressOfOperand, TemplateArgs);
2176   } else {
2177     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2178     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2179
2180     // If the result might be in a dependent base class, this is a dependent 
2181     // id-expression.
2182     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2183       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2184                                         IsAddressOfOperand, TemplateArgs);
2185
2186     // If this reference is in an Objective-C method, then we need to do
2187     // some special Objective-C lookup, too.
2188     if (IvarLookupFollowUp) {
2189       ExprResult E(LookupInObjCMethod(R, S, II, true));
2190       if (E.isInvalid())
2191         return ExprError();
2192
2193       if (Expr *Ex = E.getAs<Expr>())
2194         return Ex;
2195     }
2196   }
2197
2198   if (R.isAmbiguous())
2199     return ExprError();
2200
2201   // This could be an implicitly declared function reference (legal in C90,
2202   // extension in C99, forbidden in C++).
2203   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2204     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2205     if (D) R.addDecl(D);
2206   }
2207
2208   // Determine whether this name might be a candidate for
2209   // argument-dependent lookup.
2210   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2211
2212   if (R.empty() && !ADL) {
2213     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2214       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2215                                                    TemplateKWLoc, TemplateArgs))
2216         return E;
2217     }
2218
2219     // Don't diagnose an empty lookup for inline assembly.
2220     if (IsInlineAsmIdentifier)
2221       return ExprError();
2222
2223     // If this name wasn't predeclared and if this is not a function
2224     // call, diagnose the problem.
2225     TypoExpr *TE = nullptr;
2226     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2227         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2228     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2229     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2230            "Typo correction callback misconfigured");
2231     if (CCC) {
2232       // Make sure the callback knows what the typo being diagnosed is.
2233       CCC->setTypoName(II);
2234       if (SS.isValid())
2235         CCC->setTypoNNS(SS.getScopeRep());
2236     }
2237     if (DiagnoseEmptyLookup(S, SS, R,
2238                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2239                             nullptr, None, &TE)) {
2240       if (TE && KeywordReplacement) {
2241         auto &State = getTypoExprState(TE);
2242         auto BestTC = State.Consumer->getNextCorrection();
2243         if (BestTC.isKeyword()) {
2244           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2245           if (State.DiagHandler)
2246             State.DiagHandler(BestTC);
2247           KeywordReplacement->startToken();
2248           KeywordReplacement->setKind(II->getTokenID());
2249           KeywordReplacement->setIdentifierInfo(II);
2250           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2251           // Clean up the state associated with the TypoExpr, since it has
2252           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2253           clearDelayedTypo(TE);
2254           // Signal that a correction to a keyword was performed by returning a
2255           // valid-but-null ExprResult.
2256           return (Expr*)nullptr;
2257         }
2258         State.Consumer->resetCorrectionStream();
2259       }
2260       return TE ? TE : ExprError();
2261     }
2262
2263     assert(!R.empty() &&
2264            "DiagnoseEmptyLookup returned false but added no results");
2265
2266     // If we found an Objective-C instance variable, let
2267     // LookupInObjCMethod build the appropriate expression to
2268     // reference the ivar.
2269     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2270       R.clear();
2271       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2272       // In a hopelessly buggy code, Objective-C instance variable
2273       // lookup fails and no expression will be built to reference it.
2274       if (!E.isInvalid() && !E.get())
2275         return ExprError();
2276       return E;
2277     }
2278   }
2279
2280   // This is guaranteed from this point on.
2281   assert(!R.empty() || ADL);
2282
2283   // Check whether this might be a C++ implicit instance member access.
2284   // C++ [class.mfct.non-static]p3:
2285   //   When an id-expression that is not part of a class member access
2286   //   syntax and not used to form a pointer to member is used in the
2287   //   body of a non-static member function of class X, if name lookup
2288   //   resolves the name in the id-expression to a non-static non-type
2289   //   member of some class C, the id-expression is transformed into a
2290   //   class member access expression using (*this) as the
2291   //   postfix-expression to the left of the . operator.
2292   //
2293   // But we don't actually need to do this for '&' operands if R
2294   // resolved to a function or overloaded function set, because the
2295   // expression is ill-formed if it actually works out to be a
2296   // non-static member function:
2297   //
2298   // C++ [expr.ref]p4:
2299   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2300   //   [t]he expression can be used only as the left-hand operand of a
2301   //   member function call.
2302   //
2303   // There are other safeguards against such uses, but it's important
2304   // to get this right here so that we don't end up making a
2305   // spuriously dependent expression if we're inside a dependent
2306   // instance method.
2307   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2308     bool MightBeImplicitMember;
2309     if (!IsAddressOfOperand)
2310       MightBeImplicitMember = true;
2311     else if (!SS.isEmpty())
2312       MightBeImplicitMember = false;
2313     else if (R.isOverloadedResult())
2314       MightBeImplicitMember = false;
2315     else if (R.isUnresolvableResult())
2316       MightBeImplicitMember = true;
2317     else
2318       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2319                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2320                               isa<MSPropertyDecl>(R.getFoundDecl());
2321
2322     if (MightBeImplicitMember)
2323       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2324                                              R, TemplateArgs, S);
2325   }
2326
2327   if (TemplateArgs || TemplateKWLoc.isValid()) {
2328
2329     // In C++1y, if this is a variable template id, then check it
2330     // in BuildTemplateIdExpr().
2331     // The single lookup result must be a variable template declaration.
2332     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2333         Id.TemplateId->Kind == TNK_Var_template) {
2334       assert(R.getAsSingle<VarTemplateDecl>() &&
2335              "There should only be one declaration found.");
2336     }
2337
2338     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2339   }
2340
2341   return BuildDeclarationNameExpr(SS, R, ADL);
2342 }
2343
2344 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2345 /// declaration name, generally during template instantiation.
2346 /// There's a large number of things which don't need to be done along
2347 /// this path.
2348 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2349     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2350     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2351   DeclContext *DC = computeDeclContext(SS, false);
2352   if (!DC)
2353     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2354                                      NameInfo, /*TemplateArgs=*/nullptr);
2355
2356   if (RequireCompleteDeclContext(SS, DC))
2357     return ExprError();
2358
2359   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2360   LookupQualifiedName(R, DC);
2361
2362   if (R.isAmbiguous())
2363     return ExprError();
2364
2365   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2366     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2367                                      NameInfo, /*TemplateArgs=*/nullptr);
2368
2369   if (R.empty()) {
2370     Diag(NameInfo.getLoc(), diag::err_no_member)
2371       << NameInfo.getName() << DC << SS.getRange();
2372     return ExprError();
2373   }
2374
2375   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2376     // Diagnose a missing typename if this resolved unambiguously to a type in
2377     // a dependent context.  If we can recover with a type, downgrade this to
2378     // a warning in Microsoft compatibility mode.
2379     unsigned DiagID = diag::err_typename_missing;
2380     if (RecoveryTSI && getLangOpts().MSVCCompat)
2381       DiagID = diag::ext_typename_missing;
2382     SourceLocation Loc = SS.getBeginLoc();
2383     auto D = Diag(Loc, DiagID);
2384     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2385       << SourceRange(Loc, NameInfo.getEndLoc());
2386
2387     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2388     // context.
2389     if (!RecoveryTSI)
2390       return ExprError();
2391
2392     // Only issue the fixit if we're prepared to recover.
2393     D << FixItHint::CreateInsertion(Loc, "typename ");
2394
2395     // Recover by pretending this was an elaborated type.
2396     QualType Ty = Context.getTypeDeclType(TD);
2397     TypeLocBuilder TLB;
2398     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2399
2400     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2401     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2402     QTL.setElaboratedKeywordLoc(SourceLocation());
2403     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2404
2405     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2406
2407     return ExprEmpty();
2408   }
2409
2410   // Defend against this resolving to an implicit member access. We usually
2411   // won't get here if this might be a legitimate a class member (we end up in
2412   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2413   // a pointer-to-member or in an unevaluated context in C++11.
2414   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2415     return BuildPossibleImplicitMemberExpr(SS,
2416                                            /*TemplateKWLoc=*/SourceLocation(),
2417                                            R, /*TemplateArgs=*/nullptr, S);
2418
2419   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2420 }
2421
2422 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2423 /// detected that we're currently inside an ObjC method.  Perform some
2424 /// additional lookup.
2425 ///
2426 /// Ideally, most of this would be done by lookup, but there's
2427 /// actually quite a lot of extra work involved.
2428 ///
2429 /// Returns a null sentinel to indicate trivial success.
2430 ExprResult
2431 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2432                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2433   SourceLocation Loc = Lookup.getNameLoc();
2434   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2435   
2436   // Check for error condition which is already reported.
2437   if (!CurMethod)
2438     return ExprError();
2439
2440   // There are two cases to handle here.  1) scoped lookup could have failed,
2441   // in which case we should look for an ivar.  2) scoped lookup could have
2442   // found a decl, but that decl is outside the current instance method (i.e.
2443   // a global variable).  In these two cases, we do a lookup for an ivar with
2444   // this name, if the lookup sucedes, we replace it our current decl.
2445
2446   // If we're in a class method, we don't normally want to look for
2447   // ivars.  But if we don't find anything else, and there's an
2448   // ivar, that's an error.
2449   bool IsClassMethod = CurMethod->isClassMethod();
2450
2451   bool LookForIvars;
2452   if (Lookup.empty())
2453     LookForIvars = true;
2454   else if (IsClassMethod)
2455     LookForIvars = false;
2456   else
2457     LookForIvars = (Lookup.isSingleResult() &&
2458                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2459   ObjCInterfaceDecl *IFace = nullptr;
2460   if (LookForIvars) {
2461     IFace = CurMethod->getClassInterface();
2462     ObjCInterfaceDecl *ClassDeclared;
2463     ObjCIvarDecl *IV = nullptr;
2464     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2465       // Diagnose using an ivar in a class method.
2466       if (IsClassMethod)
2467         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2468                          << IV->getDeclName());
2469
2470       // If we're referencing an invalid decl, just return this as a silent
2471       // error node.  The error diagnostic was already emitted on the decl.
2472       if (IV->isInvalidDecl())
2473         return ExprError();
2474
2475       // Check if referencing a field with __attribute__((deprecated)).
2476       if (DiagnoseUseOfDecl(IV, Loc))
2477         return ExprError();
2478
2479       // Diagnose the use of an ivar outside of the declaring class.
2480       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2481           !declaresSameEntity(ClassDeclared, IFace) &&
2482           !getLangOpts().DebuggerSupport)
2483         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2484
2485       // FIXME: This should use a new expr for a direct reference, don't
2486       // turn this into Self->ivar, just return a BareIVarExpr or something.
2487       IdentifierInfo &II = Context.Idents.get("self");
2488       UnqualifiedId SelfName;
2489       SelfName.setIdentifier(&II, SourceLocation());
2490       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2491       CXXScopeSpec SelfScopeSpec;
2492       SourceLocation TemplateKWLoc;
2493       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2494                                               SelfName, false, false);
2495       if (SelfExpr.isInvalid())
2496         return ExprError();
2497
2498       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2499       if (SelfExpr.isInvalid())
2500         return ExprError();
2501
2502       MarkAnyDeclReferenced(Loc, IV, true);
2503
2504       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2505       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2506           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2507         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2508
2509       ObjCIvarRefExpr *Result = new (Context)
2510           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2511                           IV->getLocation(), SelfExpr.get(), true, true);
2512
2513       if (getLangOpts().ObjCAutoRefCount) {
2514         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2515           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2516             recordUseOfEvaluatedWeak(Result);
2517         }
2518         if (CurContext->isClosure())
2519           Diag(Loc, diag::warn_implicitly_retains_self)
2520             << FixItHint::CreateInsertion(Loc, "self->");
2521       }
2522       
2523       return Result;
2524     }
2525   } else if (CurMethod->isInstanceMethod()) {
2526     // We should warn if a local variable hides an ivar.
2527     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2528       ObjCInterfaceDecl *ClassDeclared;
2529       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2530         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2531             declaresSameEntity(IFace, ClassDeclared))
2532           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2533       }
2534     }
2535   } else if (Lookup.isSingleResult() &&
2536              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2537     // If accessing a stand-alone ivar in a class method, this is an error.
2538     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2539       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2540                        << IV->getDeclName());
2541   }
2542
2543   if (Lookup.empty() && II && AllowBuiltinCreation) {
2544     // FIXME. Consolidate this with similar code in LookupName.
2545     if (unsigned BuiltinID = II->getBuiltinID()) {
2546       if (!(getLangOpts().CPlusPlus &&
2547             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2548         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2549                                            S, Lookup.isForRedeclaration(),
2550                                            Lookup.getNameLoc());
2551         if (D) Lookup.addDecl(D);
2552       }
2553     }
2554   }
2555   // Sentinel value saying that we didn't do anything special.
2556   return ExprResult((Expr *)nullptr);
2557 }
2558
2559 /// \brief Cast a base object to a member's actual type.
2560 ///
2561 /// Logically this happens in three phases:
2562 ///
2563 /// * First we cast from the base type to the naming class.
2564 ///   The naming class is the class into which we were looking
2565 ///   when we found the member;  it's the qualifier type if a
2566 ///   qualifier was provided, and otherwise it's the base type.
2567 ///
2568 /// * Next we cast from the naming class to the declaring class.
2569 ///   If the member we found was brought into a class's scope by
2570 ///   a using declaration, this is that class;  otherwise it's
2571 ///   the class declaring the member.
2572 ///
2573 /// * Finally we cast from the declaring class to the "true"
2574 ///   declaring class of the member.  This conversion does not
2575 ///   obey access control.
2576 ExprResult
2577 Sema::PerformObjectMemberConversion(Expr *From,
2578                                     NestedNameSpecifier *Qualifier,
2579                                     NamedDecl *FoundDecl,
2580                                     NamedDecl *Member) {
2581   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2582   if (!RD)
2583     return From;
2584
2585   QualType DestRecordType;
2586   QualType DestType;
2587   QualType FromRecordType;
2588   QualType FromType = From->getType();
2589   bool PointerConversions = false;
2590   if (isa<FieldDecl>(Member)) {
2591     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2592
2593     if (FromType->getAs<PointerType>()) {
2594       DestType = Context.getPointerType(DestRecordType);
2595       FromRecordType = FromType->getPointeeType();
2596       PointerConversions = true;
2597     } else {
2598       DestType = DestRecordType;
2599       FromRecordType = FromType;
2600     }
2601   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2602     if (Method->isStatic())
2603       return From;
2604
2605     DestType = Method->getThisType(Context);
2606     DestRecordType = DestType->getPointeeType();
2607
2608     if (FromType->getAs<PointerType>()) {
2609       FromRecordType = FromType->getPointeeType();
2610       PointerConversions = true;
2611     } else {
2612       FromRecordType = FromType;
2613       DestType = DestRecordType;
2614     }
2615   } else {
2616     // No conversion necessary.
2617     return From;
2618   }
2619
2620   if (DestType->isDependentType() || FromType->isDependentType())
2621     return From;
2622
2623   // If the unqualified types are the same, no conversion is necessary.
2624   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2625     return From;
2626
2627   SourceRange FromRange = From->getSourceRange();
2628   SourceLocation FromLoc = FromRange.getBegin();
2629
2630   ExprValueKind VK = From->getValueKind();
2631
2632   // C++ [class.member.lookup]p8:
2633   //   [...] Ambiguities can often be resolved by qualifying a name with its
2634   //   class name.
2635   //
2636   // If the member was a qualified name and the qualified referred to a
2637   // specific base subobject type, we'll cast to that intermediate type
2638   // first and then to the object in which the member is declared. That allows
2639   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2640   //
2641   //   class Base { public: int x; };
2642   //   class Derived1 : public Base { };
2643   //   class Derived2 : public Base { };
2644   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2645   //
2646   //   void VeryDerived::f() {
2647   //     x = 17; // error: ambiguous base subobjects
2648   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2649   //   }
2650   if (Qualifier && Qualifier->getAsType()) {
2651     QualType QType = QualType(Qualifier->getAsType(), 0);
2652     assert(QType->isRecordType() && "lookup done with non-record type");
2653
2654     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2655
2656     // In C++98, the qualifier type doesn't actually have to be a base
2657     // type of the object type, in which case we just ignore it.
2658     // Otherwise build the appropriate casts.
2659     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2660       CXXCastPath BasePath;
2661       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2662                                        FromLoc, FromRange, &BasePath))
2663         return ExprError();
2664
2665       if (PointerConversions)
2666         QType = Context.getPointerType(QType);
2667       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2668                                VK, &BasePath).get();
2669
2670       FromType = QType;
2671       FromRecordType = QRecordType;
2672
2673       // If the qualifier type was the same as the destination type,
2674       // we're done.
2675       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2676         return From;
2677     }
2678   }
2679
2680   bool IgnoreAccess = false;
2681
2682   // If we actually found the member through a using declaration, cast
2683   // down to the using declaration's type.
2684   //
2685   // Pointer equality is fine here because only one declaration of a
2686   // class ever has member declarations.
2687   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2688     assert(isa<UsingShadowDecl>(FoundDecl));
2689     QualType URecordType = Context.getTypeDeclType(
2690                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2691
2692     // We only need to do this if the naming-class to declaring-class
2693     // conversion is non-trivial.
2694     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2695       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2696       CXXCastPath BasePath;
2697       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2698                                        FromLoc, FromRange, &BasePath))
2699         return ExprError();
2700
2701       QualType UType = URecordType;
2702       if (PointerConversions)
2703         UType = Context.getPointerType(UType);
2704       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2705                                VK, &BasePath).get();
2706       FromType = UType;
2707       FromRecordType = URecordType;
2708     }
2709
2710     // We don't do access control for the conversion from the
2711     // declaring class to the true declaring class.
2712     IgnoreAccess = true;
2713   }
2714
2715   CXXCastPath BasePath;
2716   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2717                                    FromLoc, FromRange, &BasePath,
2718                                    IgnoreAccess))
2719     return ExprError();
2720
2721   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2722                            VK, &BasePath);
2723 }
2724
2725 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2726                                       const LookupResult &R,
2727                                       bool HasTrailingLParen) {
2728   // Only when used directly as the postfix-expression of a call.
2729   if (!HasTrailingLParen)
2730     return false;
2731
2732   // Never if a scope specifier was provided.
2733   if (SS.isSet())
2734     return false;
2735
2736   // Only in C++ or ObjC++.
2737   if (!getLangOpts().CPlusPlus)
2738     return false;
2739
2740   // Turn off ADL when we find certain kinds of declarations during
2741   // normal lookup:
2742   for (NamedDecl *D : R) {
2743     // C++0x [basic.lookup.argdep]p3:
2744     //     -- a declaration of a class member
2745     // Since using decls preserve this property, we check this on the
2746     // original decl.
2747     if (D->isCXXClassMember())
2748       return false;
2749
2750     // C++0x [basic.lookup.argdep]p3:
2751     //     -- a block-scope function declaration that is not a
2752     //        using-declaration
2753     // NOTE: we also trigger this for function templates (in fact, we
2754     // don't check the decl type at all, since all other decl types
2755     // turn off ADL anyway).
2756     if (isa<UsingShadowDecl>(D))
2757       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2758     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2759       return false;
2760
2761     // C++0x [basic.lookup.argdep]p3:
2762     //     -- a declaration that is neither a function or a function
2763     //        template
2764     // And also for builtin functions.
2765     if (isa<FunctionDecl>(D)) {
2766       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2767
2768       // But also builtin functions.
2769       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2770         return false;
2771     } else if (!isa<FunctionTemplateDecl>(D))
2772       return false;
2773   }
2774
2775   return true;
2776 }
2777
2778
2779 /// Diagnoses obvious problems with the use of the given declaration
2780 /// as an expression.  This is only actually called for lookups that
2781 /// were not overloaded, and it doesn't promise that the declaration
2782 /// will in fact be used.
2783 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2784   if (D->isInvalidDecl())
2785     return true;
2786
2787   if (isa<TypedefNameDecl>(D)) {
2788     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2789     return true;
2790   }
2791
2792   if (isa<ObjCInterfaceDecl>(D)) {
2793     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2794     return true;
2795   }
2796
2797   if (isa<NamespaceDecl>(D)) {
2798     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2799     return true;
2800   }
2801
2802   return false;
2803 }
2804
2805 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2806                                           LookupResult &R, bool NeedsADL,
2807                                           bool AcceptInvalidDecl) {
2808   // If this is a single, fully-resolved result and we don't need ADL,
2809   // just build an ordinary singleton decl ref.
2810   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2811     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2812                                     R.getRepresentativeDecl(), nullptr,
2813                                     AcceptInvalidDecl);
2814
2815   // We only need to check the declaration if there's exactly one
2816   // result, because in the overloaded case the results can only be
2817   // functions and function templates.
2818   if (R.isSingleResult() &&
2819       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2820     return ExprError();
2821
2822   // Otherwise, just build an unresolved lookup expression.  Suppress
2823   // any lookup-related diagnostics; we'll hash these out later, when
2824   // we've picked a target.
2825   R.suppressDiagnostics();
2826
2827   UnresolvedLookupExpr *ULE
2828     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2829                                    SS.getWithLocInContext(Context),
2830                                    R.getLookupNameInfo(),
2831                                    NeedsADL, R.isOverloadedResult(),
2832                                    R.begin(), R.end());
2833
2834   return ULE;
2835 }
2836
2837 static void
2838 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2839                                    ValueDecl *var, DeclContext *DC);
2840
2841 /// \brief Complete semantic analysis for a reference to the given declaration.
2842 ExprResult Sema::BuildDeclarationNameExpr(
2843     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2844     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2845     bool AcceptInvalidDecl) {
2846   assert(D && "Cannot refer to a NULL declaration");
2847   assert(!isa<FunctionTemplateDecl>(D) &&
2848          "Cannot refer unambiguously to a function template");
2849
2850   SourceLocation Loc = NameInfo.getLoc();
2851   if (CheckDeclInExpr(*this, Loc, D))
2852     return ExprError();
2853
2854   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2855     // Specifically diagnose references to class templates that are missing
2856     // a template argument list.
2857     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2858                                            << Template << SS.getRange();
2859     Diag(Template->getLocation(), diag::note_template_decl_here);
2860     return ExprError();
2861   }
2862
2863   // Make sure that we're referring to a value.
2864   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2865   if (!VD) {
2866     Diag(Loc, diag::err_ref_non_value)
2867       << D << SS.getRange();
2868     Diag(D->getLocation(), diag::note_declared_at);
2869     return ExprError();
2870   }
2871
2872   // Check whether this declaration can be used. Note that we suppress
2873   // this check when we're going to perform argument-dependent lookup
2874   // on this function name, because this might not be the function
2875   // that overload resolution actually selects.
2876   if (DiagnoseUseOfDecl(VD, Loc))
2877     return ExprError();
2878
2879   // Only create DeclRefExpr's for valid Decl's.
2880   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2881     return ExprError();
2882
2883   // Handle members of anonymous structs and unions.  If we got here,
2884   // and the reference is to a class member indirect field, then this
2885   // must be the subject of a pointer-to-member expression.
2886   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2887     if (!indirectField->isCXXClassMember())
2888       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2889                                                       indirectField);
2890
2891   {
2892     QualType type = VD->getType();
2893     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2894       // C++ [except.spec]p17:
2895       //   An exception-specification is considered to be needed when:
2896       //   - in an expression, the function is the unique lookup result or
2897       //     the selected member of a set of overloaded functions.
2898       ResolveExceptionSpec(Loc, FPT);
2899       type = VD->getType();
2900     }
2901     ExprValueKind valueKind = VK_RValue;
2902
2903     switch (D->getKind()) {
2904     // Ignore all the non-ValueDecl kinds.
2905 #define ABSTRACT_DECL(kind)
2906 #define VALUE(type, base)
2907 #define DECL(type, base) \
2908     case Decl::type:
2909 #include "clang/AST/DeclNodes.inc"
2910       llvm_unreachable("invalid value decl kind");
2911
2912     // These shouldn't make it here.
2913     case Decl::ObjCAtDefsField:
2914     case Decl::ObjCIvar:
2915       llvm_unreachable("forming non-member reference to ivar?");
2916
2917     // Enum constants are always r-values and never references.
2918     // Unresolved using declarations are dependent.
2919     case Decl::EnumConstant:
2920     case Decl::UnresolvedUsingValue:
2921     case Decl::OMPDeclareReduction:
2922       valueKind = VK_RValue;
2923       break;
2924
2925     // Fields and indirect fields that got here must be for
2926     // pointer-to-member expressions; we just call them l-values for
2927     // internal consistency, because this subexpression doesn't really
2928     // exist in the high-level semantics.
2929     case Decl::Field:
2930     case Decl::IndirectField:
2931       assert(getLangOpts().CPlusPlus &&
2932              "building reference to field in C?");
2933
2934       // These can't have reference type in well-formed programs, but
2935       // for internal consistency we do this anyway.
2936       type = type.getNonReferenceType();
2937       valueKind = VK_LValue;
2938       break;
2939
2940     // Non-type template parameters are either l-values or r-values
2941     // depending on the type.
2942     case Decl::NonTypeTemplateParm: {
2943       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2944         type = reftype->getPointeeType();
2945         valueKind = VK_LValue; // even if the parameter is an r-value reference
2946         break;
2947       }
2948
2949       // For non-references, we need to strip qualifiers just in case
2950       // the template parameter was declared as 'const int' or whatever.
2951       valueKind = VK_RValue;
2952       type = type.getUnqualifiedType();
2953       break;
2954     }
2955
2956     case Decl::Var:
2957     case Decl::VarTemplateSpecialization:
2958     case Decl::VarTemplatePartialSpecialization:
2959     case Decl::Decomposition:
2960     case Decl::OMPCapturedExpr:
2961       // In C, "extern void blah;" is valid and is an r-value.
2962       if (!getLangOpts().CPlusPlus &&
2963           !type.hasQualifiers() &&
2964           type->isVoidType()) {
2965         valueKind = VK_RValue;
2966         break;
2967       }
2968       // fallthrough
2969
2970     case Decl::ImplicitParam:
2971     case Decl::ParmVar: {
2972       // These are always l-values.
2973       valueKind = VK_LValue;
2974       type = type.getNonReferenceType();
2975
2976       // FIXME: Does the addition of const really only apply in
2977       // potentially-evaluated contexts? Since the variable isn't actually
2978       // captured in an unevaluated context, it seems that the answer is no.
2979       if (!isUnevaluatedContext()) {
2980         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2981         if (!CapturedType.isNull())
2982           type = CapturedType;
2983       }
2984       
2985       break;
2986     }
2987
2988     case Decl::Binding: {
2989       // These are always lvalues.
2990       valueKind = VK_LValue;
2991       type = type.getNonReferenceType();
2992       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2993       // decides how that's supposed to work.
2994       auto *BD = cast<BindingDecl>(VD);
2995       if (BD->getDeclContext()->isFunctionOrMethod() &&
2996           BD->getDeclContext() != CurContext)
2997         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2998       break;
2999     }
3000         
3001     case Decl::Function: {
3002       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3003         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3004           type = Context.BuiltinFnTy;
3005           valueKind = VK_RValue;
3006           break;
3007         }
3008       }
3009
3010       const FunctionType *fty = type->castAs<FunctionType>();
3011
3012       // If we're referring to a function with an __unknown_anytype
3013       // result type, make the entire expression __unknown_anytype.
3014       if (fty->getReturnType() == Context.UnknownAnyTy) {
3015         type = Context.UnknownAnyTy;
3016         valueKind = VK_RValue;
3017         break;
3018       }
3019
3020       // Functions are l-values in C++.
3021       if (getLangOpts().CPlusPlus) {
3022         valueKind = VK_LValue;
3023         break;
3024       }
3025       
3026       // C99 DR 316 says that, if a function type comes from a
3027       // function definition (without a prototype), that type is only
3028       // used for checking compatibility. Therefore, when referencing
3029       // the function, we pretend that we don't have the full function
3030       // type.
3031       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3032           isa<FunctionProtoType>(fty))
3033         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3034                                               fty->getExtInfo());
3035
3036       // Functions are r-values in C.
3037       valueKind = VK_RValue;
3038       break;
3039     }
3040
3041     case Decl::MSProperty:
3042       valueKind = VK_LValue;
3043       break;
3044
3045     case Decl::CXXMethod:
3046       // If we're referring to a method with an __unknown_anytype
3047       // result type, make the entire expression __unknown_anytype.
3048       // This should only be possible with a type written directly.
3049       if (const FunctionProtoType *proto
3050             = dyn_cast<FunctionProtoType>(VD->getType()))
3051         if (proto->getReturnType() == Context.UnknownAnyTy) {
3052           type = Context.UnknownAnyTy;
3053           valueKind = VK_RValue;
3054           break;
3055         }
3056
3057       // C++ methods are l-values if static, r-values if non-static.
3058       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3059         valueKind = VK_LValue;
3060         break;
3061       }
3062       // fallthrough
3063
3064     case Decl::CXXConversion:
3065     case Decl::CXXDestructor:
3066     case Decl::CXXConstructor:
3067       valueKind = VK_RValue;
3068       break;
3069     }
3070
3071     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3072                             TemplateArgs);
3073   }
3074 }
3075
3076 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3077                                     SmallString<32> &Target) {
3078   Target.resize(CharByteWidth * (Source.size() + 1));
3079   char *ResultPtr = &Target[0];
3080   const llvm::UTF8 *ErrorPtr;
3081   bool success =
3082       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3083   (void)success;
3084   assert(success);
3085   Target.resize(ResultPtr - &Target[0]);
3086 }
3087
3088 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3089                                      PredefinedExpr::IdentType IT) {
3090   // Pick the current block, lambda, captured statement or function.
3091   Decl *currentDecl = nullptr;
3092   if (const BlockScopeInfo *BSI = getCurBlock())
3093     currentDecl = BSI->TheDecl;
3094   else if (const LambdaScopeInfo *LSI = getCurLambda())
3095     currentDecl = LSI->CallOperator;
3096   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3097     currentDecl = CSI->TheCapturedDecl;
3098   else
3099     currentDecl = getCurFunctionOrMethodDecl();
3100
3101   if (!currentDecl) {
3102     Diag(Loc, diag::ext_predef_outside_function);
3103     currentDecl = Context.getTranslationUnitDecl();
3104   }
3105
3106   QualType ResTy;
3107   StringLiteral *SL = nullptr;
3108   if (cast<DeclContext>(currentDecl)->isDependentContext())
3109     ResTy = Context.DependentTy;
3110   else {
3111     // Pre-defined identifiers are of type char[x], where x is the length of
3112     // the string.
3113     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3114     unsigned Length = Str.length();
3115
3116     llvm::APInt LengthI(32, Length + 1);
3117     if (IT == PredefinedExpr::LFunction) {
3118       ResTy = Context.WideCharTy.withConst();
3119       SmallString<32> RawChars;
3120       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3121                               Str, RawChars);
3122       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3123                                            /*IndexTypeQuals*/ 0);
3124       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3125                                  /*Pascal*/ false, ResTy, Loc);
3126     } else {
3127       ResTy = Context.CharTy.withConst();
3128       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3129                                            /*IndexTypeQuals*/ 0);
3130       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3131                                  /*Pascal*/ false, ResTy, Loc);
3132     }
3133   }
3134
3135   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3136 }
3137
3138 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3139   PredefinedExpr::IdentType IT;
3140
3141   switch (Kind) {
3142   default: llvm_unreachable("Unknown simple primary expr!");
3143   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3144   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3145   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3146   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3147   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3148   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3149   }
3150
3151   return BuildPredefinedExpr(Loc, IT);
3152 }
3153
3154 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3155   SmallString<16> CharBuffer;
3156   bool Invalid = false;
3157   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3158   if (Invalid)
3159     return ExprError();
3160
3161   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3162                             PP, Tok.getKind());
3163   if (Literal.hadError())
3164     return ExprError();
3165
3166   QualType Ty;
3167   if (Literal.isWide())
3168     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3169   else if (Literal.isUTF16())
3170     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3171   else if (Literal.isUTF32())
3172     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3173   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3174     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3175   else
3176     Ty = Context.CharTy;  // 'x' -> char in C++
3177
3178   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3179   if (Literal.isWide())
3180     Kind = CharacterLiteral::Wide;
3181   else if (Literal.isUTF16())
3182     Kind = CharacterLiteral::UTF16;
3183   else if (Literal.isUTF32())
3184     Kind = CharacterLiteral::UTF32;
3185   else if (Literal.isUTF8())
3186     Kind = CharacterLiteral::UTF8;
3187
3188   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3189                                              Tok.getLocation());
3190
3191   if (Literal.getUDSuffix().empty())
3192     return Lit;
3193
3194   // We're building a user-defined literal.
3195   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3196   SourceLocation UDSuffixLoc =
3197     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3198
3199   // Make sure we're allowed user-defined literals here.
3200   if (!UDLScope)
3201     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3202
3203   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3204   //   operator "" X (ch)
3205   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3206                                         Lit, Tok.getLocation());
3207 }
3208
3209 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3210   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3211   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3212                                 Context.IntTy, Loc);
3213 }
3214
3215 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3216                                   QualType Ty, SourceLocation Loc) {
3217   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3218
3219   using llvm::APFloat;
3220   APFloat Val(Format);
3221
3222   APFloat::opStatus result = Literal.GetFloatValue(Val);
3223
3224   // Overflow is always an error, but underflow is only an error if
3225   // we underflowed to zero (APFloat reports denormals as underflow).
3226   if ((result & APFloat::opOverflow) ||
3227       ((result & APFloat::opUnderflow) && Val.isZero())) {
3228     unsigned diagnostic;
3229     SmallString<20> buffer;
3230     if (result & APFloat::opOverflow) {
3231       diagnostic = diag::warn_float_overflow;
3232       APFloat::getLargest(Format).toString(buffer);
3233     } else {
3234       diagnostic = diag::warn_float_underflow;
3235       APFloat::getSmallest(Format).toString(buffer);
3236     }
3237
3238     S.Diag(Loc, diagnostic)
3239       << Ty
3240       << StringRef(buffer.data(), buffer.size());
3241   }
3242
3243   bool isExact = (result == APFloat::opOK);
3244   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3245 }
3246
3247 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3248   assert(E && "Invalid expression");
3249
3250   if (E->isValueDependent())
3251     return false;
3252
3253   QualType QT = E->getType();
3254   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3255     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3256     return true;
3257   }
3258
3259   llvm::APSInt ValueAPS;
3260   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3261
3262   if (R.isInvalid())
3263     return true;
3264
3265   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3266   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3267     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3268         << ValueAPS.toString(10) << ValueIsPositive;
3269     return true;
3270   }
3271
3272   return false;
3273 }
3274
3275 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3276   // Fast path for a single digit (which is quite common).  A single digit
3277   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3278   if (Tok.getLength() == 1) {
3279     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3280     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3281   }
3282
3283   SmallString<128> SpellingBuffer;
3284   // NumericLiteralParser wants to overread by one character.  Add padding to
3285   // the buffer in case the token is copied to the buffer.  If getSpelling()
3286   // returns a StringRef to the memory buffer, it should have a null char at
3287   // the EOF, so it is also safe.
3288   SpellingBuffer.resize(Tok.getLength() + 1);
3289
3290   // Get the spelling of the token, which eliminates trigraphs, etc.
3291   bool Invalid = false;
3292   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3293   if (Invalid)
3294     return ExprError();
3295
3296   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3297   if (Literal.hadError)
3298     return ExprError();
3299
3300   if (Literal.hasUDSuffix()) {
3301     // We're building a user-defined literal.
3302     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3303     SourceLocation UDSuffixLoc =
3304       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3305
3306     // Make sure we're allowed user-defined literals here.
3307     if (!UDLScope)
3308       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3309
3310     QualType CookedTy;
3311     if (Literal.isFloatingLiteral()) {
3312       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3313       // long double, the literal is treated as a call of the form
3314       //   operator "" X (f L)
3315       CookedTy = Context.LongDoubleTy;
3316     } else {
3317       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3318       // unsigned long long, the literal is treated as a call of the form
3319       //   operator "" X (n ULL)
3320       CookedTy = Context.UnsignedLongLongTy;
3321     }
3322
3323     DeclarationName OpName =
3324       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3325     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3326     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3327
3328     SourceLocation TokLoc = Tok.getLocation();
3329
3330     // Perform literal operator lookup to determine if we're building a raw
3331     // literal or a cooked one.
3332     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3333     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3334                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3335                                   /*AllowStringTemplate*/false)) {
3336     case LOLR_Error:
3337       return ExprError();
3338
3339     case LOLR_Cooked: {
3340       Expr *Lit;
3341       if (Literal.isFloatingLiteral()) {
3342         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3343       } else {
3344         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3345         if (Literal.GetIntegerValue(ResultVal))
3346           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3347               << /* Unsigned */ 1;
3348         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3349                                      Tok.getLocation());
3350       }
3351       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3352     }
3353
3354     case LOLR_Raw: {
3355       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3356       // literal is treated as a call of the form
3357       //   operator "" X ("n")
3358       unsigned Length = Literal.getUDSuffixOffset();
3359       QualType StrTy = Context.getConstantArrayType(
3360           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3361           ArrayType::Normal, 0);
3362       Expr *Lit = StringLiteral::Create(
3363           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3364           /*Pascal*/false, StrTy, &TokLoc, 1);
3365       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3366     }
3367
3368     case LOLR_Template: {
3369       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3370       // template), L is treated as a call fo the form
3371       //   operator "" X <'c1', 'c2', ... 'ck'>()
3372       // where n is the source character sequence c1 c2 ... ck.
3373       TemplateArgumentListInfo ExplicitArgs;
3374       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3375       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3376       llvm::APSInt Value(CharBits, CharIsUnsigned);
3377       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3378         Value = TokSpelling[I];
3379         TemplateArgument Arg(Context, Value, Context.CharTy);
3380         TemplateArgumentLocInfo ArgInfo;
3381         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3382       }
3383       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3384                                       &ExplicitArgs);
3385     }
3386     case LOLR_StringTemplate:
3387       llvm_unreachable("unexpected literal operator lookup result");
3388     }
3389   }
3390
3391   Expr *Res;
3392
3393   if (Literal.isFloatingLiteral()) {
3394     QualType Ty;
3395     if (Literal.isHalf){
3396       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3397         Ty = Context.HalfTy;
3398       else {
3399         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3400         return ExprError();
3401       }
3402     } else if (Literal.isFloat)
3403       Ty = Context.FloatTy;
3404     else if (Literal.isLong)
3405       Ty = Context.LongDoubleTy;
3406     else if (Literal.isFloat128)
3407       Ty = Context.Float128Ty;
3408     else
3409       Ty = Context.DoubleTy;
3410
3411     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3412
3413     if (Ty == Context.DoubleTy) {
3414       if (getLangOpts().SinglePrecisionConstants) {
3415         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3416         if (BTy->getKind() != BuiltinType::Float) {
3417           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3418         }
3419       } else if (getLangOpts().OpenCL &&
3420                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3421         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3422         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3423         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3424       }
3425     }
3426   } else if (!Literal.isIntegerLiteral()) {
3427     return ExprError();
3428   } else {
3429     QualType Ty;
3430
3431     // 'long long' is a C99 or C++11 feature.
3432     if (!getLangOpts().C99 && Literal.isLongLong) {
3433       if (getLangOpts().CPlusPlus)
3434         Diag(Tok.getLocation(),
3435              getLangOpts().CPlusPlus11 ?
3436              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3437       else
3438         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3439     }
3440
3441     // Get the value in the widest-possible width.
3442     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3443     llvm::APInt ResultVal(MaxWidth, 0);
3444
3445     if (Literal.GetIntegerValue(ResultVal)) {
3446       // If this value didn't fit into uintmax_t, error and force to ull.
3447       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3448           << /* Unsigned */ 1;
3449       Ty = Context.UnsignedLongLongTy;
3450       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3451              "long long is not intmax_t?");
3452     } else {
3453       // If this value fits into a ULL, try to figure out what else it fits into
3454       // according to the rules of C99 6.4.4.1p5.
3455
3456       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3457       // be an unsigned int.
3458       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3459
3460       // Check from smallest to largest, picking the smallest type we can.
3461       unsigned Width = 0;
3462
3463       // Microsoft specific integer suffixes are explicitly sized.
3464       if (Literal.MicrosoftInteger) {
3465         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3466           Width = 8;
3467           Ty = Context.CharTy;
3468         } else {
3469           Width = Literal.MicrosoftInteger;
3470           Ty = Context.getIntTypeForBitwidth(Width,
3471                                              /*Signed=*/!Literal.isUnsigned);
3472         }
3473       }
3474
3475       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3476         // Are int/unsigned possibilities?
3477         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3478
3479         // Does it fit in a unsigned int?
3480         if (ResultVal.isIntN(IntSize)) {
3481           // Does it fit in a signed int?
3482           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3483             Ty = Context.IntTy;
3484           else if (AllowUnsigned)
3485             Ty = Context.UnsignedIntTy;
3486           Width = IntSize;
3487         }
3488       }
3489
3490       // Are long/unsigned long possibilities?
3491       if (Ty.isNull() && !Literal.isLongLong) {
3492         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3493
3494         // Does it fit in a unsigned long?
3495         if (ResultVal.isIntN(LongSize)) {
3496           // Does it fit in a signed long?
3497           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3498             Ty = Context.LongTy;
3499           else if (AllowUnsigned)
3500             Ty = Context.UnsignedLongTy;
3501           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3502           // is compatible.
3503           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3504             const unsigned LongLongSize =
3505                 Context.getTargetInfo().getLongLongWidth();
3506             Diag(Tok.getLocation(),
3507                  getLangOpts().CPlusPlus
3508                      ? Literal.isLong
3509                            ? diag::warn_old_implicitly_unsigned_long_cxx
3510                            : /*C++98 UB*/ diag::
3511                                  ext_old_implicitly_unsigned_long_cxx
3512                      : diag::warn_old_implicitly_unsigned_long)
3513                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3514                                             : /*will be ill-formed*/ 1);
3515             Ty = Context.UnsignedLongTy;
3516           }
3517           Width = LongSize;
3518         }
3519       }
3520
3521       // Check long long if needed.
3522       if (Ty.isNull()) {
3523         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3524
3525         // Does it fit in a unsigned long long?
3526         if (ResultVal.isIntN(LongLongSize)) {
3527           // Does it fit in a signed long long?
3528           // To be compatible with MSVC, hex integer literals ending with the
3529           // LL or i64 suffix are always signed in Microsoft mode.
3530           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3531               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3532             Ty = Context.LongLongTy;
3533           else if (AllowUnsigned)
3534             Ty = Context.UnsignedLongLongTy;
3535           Width = LongLongSize;
3536         }
3537       }
3538
3539       // If we still couldn't decide a type, we probably have something that
3540       // does not fit in a signed long long, but has no U suffix.
3541       if (Ty.isNull()) {
3542         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3543         Ty = Context.UnsignedLongLongTy;
3544         Width = Context.getTargetInfo().getLongLongWidth();
3545       }
3546
3547       if (ResultVal.getBitWidth() != Width)
3548         ResultVal = ResultVal.trunc(Width);
3549     }
3550     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3551   }
3552
3553   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3554   if (Literal.isImaginary)
3555     Res = new (Context) ImaginaryLiteral(Res,
3556                                         Context.getComplexType(Res->getType()));
3557
3558   return Res;
3559 }
3560
3561 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3562   assert(E && "ActOnParenExpr() missing expr");
3563   return new (Context) ParenExpr(L, R, E);
3564 }
3565
3566 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3567                                          SourceLocation Loc,
3568                                          SourceRange ArgRange) {
3569   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3570   // scalar or vector data type argument..."
3571   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3572   // type (C99 6.2.5p18) or void.
3573   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3574     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3575       << T << ArgRange;
3576     return true;
3577   }
3578
3579   assert((T->isVoidType() || !T->isIncompleteType()) &&
3580          "Scalar types should always be complete");
3581   return false;
3582 }
3583
3584 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3585                                            SourceLocation Loc,
3586                                            SourceRange ArgRange,
3587                                            UnaryExprOrTypeTrait TraitKind) {
3588   // Invalid types must be hard errors for SFINAE in C++.
3589   if (S.LangOpts.CPlusPlus)
3590     return true;
3591
3592   // C99 6.5.3.4p1:
3593   if (T->isFunctionType() &&
3594       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3595     // sizeof(function)/alignof(function) is allowed as an extension.
3596     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3597       << TraitKind << ArgRange;
3598     return false;
3599   }
3600
3601   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3602   // this is an error (OpenCL v1.1 s6.3.k)
3603   if (T->isVoidType()) {
3604     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3605                                         : diag::ext_sizeof_alignof_void_type;
3606     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3607     return false;
3608   }
3609
3610   return true;
3611 }
3612
3613 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3614                                              SourceLocation Loc,
3615                                              SourceRange ArgRange,
3616                                              UnaryExprOrTypeTrait TraitKind) {
3617   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3618   // runtime doesn't allow it.
3619   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3620     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3621       << T << (TraitKind == UETT_SizeOf)
3622       << ArgRange;
3623     return true;
3624   }
3625
3626   return false;
3627 }
3628
3629 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3630 /// pointer type is equal to T) and emit a warning if it is.
3631 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3632                                      Expr *E) {
3633   // Don't warn if the operation changed the type.
3634   if (T != E->getType())
3635     return;
3636
3637   // Now look for array decays.
3638   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3639   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3640     return;
3641
3642   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3643                                              << ICE->getType()
3644                                              << ICE->getSubExpr()->getType();
3645 }
3646
3647 /// \brief Check the constraints on expression operands to unary type expression
3648 /// and type traits.
3649 ///
3650 /// Completes any types necessary and validates the constraints on the operand
3651 /// expression. The logic mostly mirrors the type-based overload, but may modify
3652 /// the expression as it completes the type for that expression through template
3653 /// instantiation, etc.
3654 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3655                                             UnaryExprOrTypeTrait ExprKind) {
3656   QualType ExprTy = E->getType();
3657   assert(!ExprTy->isReferenceType());
3658
3659   if (ExprKind == UETT_VecStep)
3660     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661                                         E->getSourceRange());
3662
3663   // Whitelist some types as extensions
3664   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3665                                       E->getSourceRange(), ExprKind))
3666     return false;
3667
3668   // 'alignof' applied to an expression only requires the base element type of
3669   // the expression to be complete. 'sizeof' requires the expression's type to
3670   // be complete (and will attempt to complete it if it's an array of unknown
3671   // bound).
3672   if (ExprKind == UETT_AlignOf) {
3673     if (RequireCompleteType(E->getExprLoc(),
3674                             Context.getBaseElementType(E->getType()),
3675                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3676                             E->getSourceRange()))
3677       return true;
3678   } else {
3679     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3680                                 ExprKind, E->getSourceRange()))
3681       return true;
3682   }
3683
3684   // Completing the expression's type may have changed it.
3685   ExprTy = E->getType();
3686   assert(!ExprTy->isReferenceType());
3687
3688   if (ExprTy->isFunctionType()) {
3689     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3690       << ExprKind << E->getSourceRange();
3691     return true;
3692   }
3693
3694   // The operand for sizeof and alignof is in an unevaluated expression context,
3695   // so side effects could result in unintended consequences.
3696   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3697       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3698     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3699
3700   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3701                                        E->getSourceRange(), ExprKind))
3702     return true;
3703
3704   if (ExprKind == UETT_SizeOf) {
3705     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3706       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3707         QualType OType = PVD->getOriginalType();
3708         QualType Type = PVD->getType();
3709         if (Type->isPointerType() && OType->isArrayType()) {
3710           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3711             << Type << OType;
3712           Diag(PVD->getLocation(), diag::note_declared_at);
3713         }
3714       }
3715     }
3716
3717     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3718     // decays into a pointer and returns an unintended result. This is most
3719     // likely a typo for "sizeof(array) op x".
3720     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3721       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3722                                BO->getLHS());
3723       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3724                                BO->getRHS());
3725     }
3726   }
3727
3728   return false;
3729 }
3730
3731 /// \brief Check the constraints on operands to unary expression and type
3732 /// traits.
3733 ///
3734 /// This will complete any types necessary, and validate the various constraints
3735 /// on those operands.
3736 ///
3737 /// The UsualUnaryConversions() function is *not* called by this routine.
3738 /// C99 6.3.2.1p[2-4] all state:
3739 ///   Except when it is the operand of the sizeof operator ...
3740 ///
3741 /// C++ [expr.sizeof]p4
3742 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3743 ///   standard conversions are not applied to the operand of sizeof.
3744 ///
3745 /// This policy is followed for all of the unary trait expressions.
3746 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3747                                             SourceLocation OpLoc,
3748                                             SourceRange ExprRange,
3749                                             UnaryExprOrTypeTrait ExprKind) {
3750   if (ExprType->isDependentType())
3751     return false;
3752
3753   // C++ [expr.sizeof]p2:
3754   //     When applied to a reference or a reference type, the result
3755   //     is the size of the referenced type.
3756   // C++11 [expr.alignof]p3:
3757   //     When alignof is applied to a reference type, the result
3758   //     shall be the alignment of the referenced type.
3759   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3760     ExprType = Ref->getPointeeType();
3761
3762   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3763   //   When alignof or _Alignof is applied to an array type, the result
3764   //   is the alignment of the element type.
3765   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3766     ExprType = Context.getBaseElementType(ExprType);
3767
3768   if (ExprKind == UETT_VecStep)
3769     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3770
3771   // Whitelist some types as extensions
3772   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3773                                       ExprKind))
3774     return false;
3775
3776   if (RequireCompleteType(OpLoc, ExprType,
3777                           diag::err_sizeof_alignof_incomplete_type,
3778                           ExprKind, ExprRange))
3779     return true;
3780
3781   if (ExprType->isFunctionType()) {
3782     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3783       << ExprKind << ExprRange;
3784     return true;
3785   }
3786
3787   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3788                                        ExprKind))
3789     return true;
3790
3791   return false;
3792 }
3793
3794 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3795   E = E->IgnoreParens();
3796
3797   // Cannot know anything else if the expression is dependent.
3798   if (E->isTypeDependent())
3799     return false;
3800
3801   if (E->getObjectKind() == OK_BitField) {
3802     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3803        << 1 << E->getSourceRange();
3804     return true;
3805   }
3806
3807   ValueDecl *D = nullptr;
3808   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3809     D = DRE->getDecl();
3810   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3811     D = ME->getMemberDecl();
3812   }
3813
3814   // If it's a field, require the containing struct to have a
3815   // complete definition so that we can compute the layout.
3816   //
3817   // This can happen in C++11 onwards, either by naming the member
3818   // in a way that is not transformed into a member access expression
3819   // (in an unevaluated operand, for instance), or by naming the member
3820   // in a trailing-return-type.
3821   //
3822   // For the record, since __alignof__ on expressions is a GCC
3823   // extension, GCC seems to permit this but always gives the
3824   // nonsensical answer 0.
3825   //
3826   // We don't really need the layout here --- we could instead just
3827   // directly check for all the appropriate alignment-lowing
3828   // attributes --- but that would require duplicating a lot of
3829   // logic that just isn't worth duplicating for such a marginal
3830   // use-case.
3831   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3832     // Fast path this check, since we at least know the record has a
3833     // definition if we can find a member of it.
3834     if (!FD->getParent()->isCompleteDefinition()) {
3835       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3836         << E->getSourceRange();
3837       return true;
3838     }
3839
3840     // Otherwise, if it's a field, and the field doesn't have
3841     // reference type, then it must have a complete type (or be a
3842     // flexible array member, which we explicitly want to
3843     // white-list anyway), which makes the following checks trivial.
3844     if (!FD->getType()->isReferenceType())
3845       return false;
3846   }
3847
3848   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3849 }
3850
3851 bool Sema::CheckVecStepExpr(Expr *E) {
3852   E = E->IgnoreParens();
3853
3854   // Cannot know anything else if the expression is dependent.
3855   if (E->isTypeDependent())
3856     return false;
3857
3858   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3859 }
3860
3861 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3862                                         CapturingScopeInfo *CSI) {
3863   assert(T->isVariablyModifiedType());
3864   assert(CSI != nullptr);
3865
3866   // We're going to walk down into the type and look for VLA expressions.
3867   do {
3868     const Type *Ty = T.getTypePtr();
3869     switch (Ty->getTypeClass()) {
3870 #define TYPE(Class, Base)
3871 #define ABSTRACT_TYPE(Class, Base)
3872 #define NON_CANONICAL_TYPE(Class, Base)
3873 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3874 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3875 #include "clang/AST/TypeNodes.def"
3876       T = QualType();
3877       break;
3878     // These types are never variably-modified.
3879     case Type::Builtin:
3880     case Type::Complex:
3881     case Type::Vector:
3882     case Type::ExtVector:
3883     case Type::Record:
3884     case Type::Enum:
3885     case Type::Elaborated:
3886     case Type::TemplateSpecialization:
3887     case Type::ObjCObject:
3888     case Type::ObjCInterface:
3889     case Type::ObjCObjectPointer:
3890     case Type::ObjCTypeParam:
3891     case Type::Pipe:
3892       llvm_unreachable("type class is never variably-modified!");
3893     case Type::Adjusted:
3894       T = cast<AdjustedType>(Ty)->getOriginalType();
3895       break;
3896     case Type::Decayed:
3897       T = cast<DecayedType>(Ty)->getPointeeType();
3898       break;
3899     case Type::Pointer:
3900       T = cast<PointerType>(Ty)->getPointeeType();
3901       break;
3902     case Type::BlockPointer:
3903       T = cast<BlockPointerType>(Ty)->getPointeeType();
3904       break;
3905     case Type::LValueReference:
3906     case Type::RValueReference:
3907       T = cast<ReferenceType>(Ty)->getPointeeType();
3908       break;
3909     case Type::MemberPointer:
3910       T = cast<MemberPointerType>(Ty)->getPointeeType();
3911       break;
3912     case Type::ConstantArray:
3913     case Type::IncompleteArray:
3914       // Losing element qualification here is fine.
3915       T = cast<ArrayType>(Ty)->getElementType();
3916       break;
3917     case Type::VariableArray: {
3918       // Losing element qualification here is fine.
3919       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3920
3921       // Unknown size indication requires no size computation.
3922       // Otherwise, evaluate and record it.
3923       if (auto Size = VAT->getSizeExpr()) {
3924         if (!CSI->isVLATypeCaptured(VAT)) {
3925           RecordDecl *CapRecord = nullptr;
3926           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3927             CapRecord = LSI->Lambda;
3928           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3929             CapRecord = CRSI->TheRecordDecl;
3930           }
3931           if (CapRecord) {
3932             auto ExprLoc = Size->getExprLoc();
3933             auto SizeType = Context.getSizeType();
3934             // Build the non-static data member.
3935             auto Field =
3936                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3937                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3938                                   /*BW*/ nullptr, /*Mutable*/ false,
3939                                   /*InitStyle*/ ICIS_NoInit);
3940             Field->setImplicit(true);
3941             Field->setAccess(AS_private);
3942             Field->setCapturedVLAType(VAT);
3943             CapRecord->addDecl(Field);
3944
3945             CSI->addVLATypeCapture(ExprLoc, SizeType);
3946           }
3947         }
3948       }
3949       T = VAT->getElementType();
3950       break;
3951     }
3952     case Type::FunctionProto:
3953     case Type::FunctionNoProto:
3954       T = cast<FunctionType>(Ty)->getReturnType();
3955       break;
3956     case Type::Paren:
3957     case Type::TypeOf:
3958     case Type::UnaryTransform:
3959     case Type::Attributed:
3960     case Type::SubstTemplateTypeParm:
3961     case Type::PackExpansion:
3962       // Keep walking after single level desugaring.
3963       T = T.getSingleStepDesugaredType(Context);
3964       break;
3965     case Type::Typedef:
3966       T = cast<TypedefType>(Ty)->desugar();
3967       break;
3968     case Type::Decltype:
3969       T = cast<DecltypeType>(Ty)->desugar();
3970       break;
3971     case Type::Auto:
3972       T = cast<AutoType>(Ty)->getDeducedType();
3973       break;
3974     case Type::TypeOfExpr:
3975       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3976       break;
3977     case Type::Atomic:
3978       T = cast<AtomicType>(Ty)->getValueType();
3979       break;
3980     }
3981   } while (!T.isNull() && T->isVariablyModifiedType());
3982 }
3983
3984 /// \brief Build a sizeof or alignof expression given a type operand.
3985 ExprResult
3986 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3987                                      SourceLocation OpLoc,
3988                                      UnaryExprOrTypeTrait ExprKind,
3989                                      SourceRange R) {
3990   if (!TInfo)
3991     return ExprError();
3992
3993   QualType T = TInfo->getType();
3994
3995   if (!T->isDependentType() &&
3996       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3997     return ExprError();
3998
3999   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4000     if (auto *TT = T->getAs<TypedefType>()) {
4001       for (auto I = FunctionScopes.rbegin(),
4002                 E = std::prev(FunctionScopes.rend());
4003            I != E; ++I) {
4004         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4005         if (CSI == nullptr)
4006           break;
4007         DeclContext *DC = nullptr;
4008         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4009           DC = LSI->CallOperator;
4010         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4011           DC = CRSI->TheCapturedDecl;
4012         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4013           DC = BSI->TheDecl;
4014         if (DC) {
4015           if (DC->containsDecl(TT->getDecl()))
4016             break;
4017           captureVariablyModifiedType(Context, T, CSI);
4018         }
4019       }
4020     }
4021   }
4022
4023   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4024   return new (Context) UnaryExprOrTypeTraitExpr(
4025       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4026 }
4027
4028 /// \brief Build a sizeof or alignof expression given an expression
4029 /// operand.
4030 ExprResult
4031 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4032                                      UnaryExprOrTypeTrait ExprKind) {
4033   ExprResult PE = CheckPlaceholderExpr(E);
4034   if (PE.isInvalid()) 
4035     return ExprError();
4036
4037   E = PE.get();
4038   
4039   // Verify that the operand is valid.
4040   bool isInvalid = false;
4041   if (E->isTypeDependent()) {
4042     // Delay type-checking for type-dependent expressions.
4043   } else if (ExprKind == UETT_AlignOf) {
4044     isInvalid = CheckAlignOfExpr(*this, E);
4045   } else if (ExprKind == UETT_VecStep) {
4046     isInvalid = CheckVecStepExpr(E);
4047   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4048       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4049       isInvalid = true;
4050   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4051     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4052     isInvalid = true;
4053   } else {
4054     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4055   }
4056
4057   if (isInvalid)
4058     return ExprError();
4059
4060   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4061     PE = TransformToPotentiallyEvaluated(E);
4062     if (PE.isInvalid()) return ExprError();
4063     E = PE.get();
4064   }
4065
4066   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4067   return new (Context) UnaryExprOrTypeTraitExpr(
4068       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4069 }
4070
4071 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4072 /// expr and the same for @c alignof and @c __alignof
4073 /// Note that the ArgRange is invalid if isType is false.
4074 ExprResult
4075 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4076                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4077                                     void *TyOrEx, SourceRange ArgRange) {
4078   // If error parsing type, ignore.
4079   if (!TyOrEx) return ExprError();
4080
4081   if (IsType) {
4082     TypeSourceInfo *TInfo;
4083     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4084     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4085   }
4086
4087   Expr *ArgEx = (Expr *)TyOrEx;
4088   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4089   return Result;
4090 }
4091
4092 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4093                                      bool IsReal) {
4094   if (V.get()->isTypeDependent())
4095     return S.Context.DependentTy;
4096
4097   // _Real and _Imag are only l-values for normal l-values.
4098   if (V.get()->getObjectKind() != OK_Ordinary) {
4099     V = S.DefaultLvalueConversion(V.get());
4100     if (V.isInvalid())
4101       return QualType();
4102   }
4103
4104   // These operators return the element type of a complex type.
4105   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4106     return CT->getElementType();
4107
4108   // Otherwise they pass through real integer and floating point types here.
4109   if (V.get()->getType()->isArithmeticType())
4110     return V.get()->getType();
4111
4112   // Test for placeholders.
4113   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4114   if (PR.isInvalid()) return QualType();
4115   if (PR.get() != V.get()) {
4116     V = PR;
4117     return CheckRealImagOperand(S, V, Loc, IsReal);
4118   }
4119
4120   // Reject anything else.
4121   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4122     << (IsReal ? "__real" : "__imag");
4123   return QualType();
4124 }
4125
4126
4127
4128 ExprResult
4129 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4130                           tok::TokenKind Kind, Expr *Input) {
4131   UnaryOperatorKind Opc;
4132   switch (Kind) {
4133   default: llvm_unreachable("Unknown unary op!");
4134   case tok::plusplus:   Opc = UO_PostInc; break;
4135   case tok::minusminus: Opc = UO_PostDec; break;
4136   }
4137
4138   // Since this might is a postfix expression, get rid of ParenListExprs.
4139   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4140   if (Result.isInvalid()) return ExprError();
4141   Input = Result.get();
4142
4143   return BuildUnaryOp(S, OpLoc, Opc, Input);
4144 }
4145
4146 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4147 ///
4148 /// \return true on error
4149 static bool checkArithmeticOnObjCPointer(Sema &S,
4150                                          SourceLocation opLoc,
4151                                          Expr *op) {
4152   assert(op->getType()->isObjCObjectPointerType());
4153   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4154       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4155     return false;
4156
4157   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4158     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4159     << op->getSourceRange();
4160   return true;
4161 }
4162
4163 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4164   auto *BaseNoParens = Base->IgnoreParens();
4165   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4166     return MSProp->getPropertyDecl()->getType()->isArrayType();
4167   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4168 }
4169
4170 ExprResult
4171 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4172                               Expr *idx, SourceLocation rbLoc) {
4173   if (base && !base->getType().isNull() &&
4174       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4175     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4176                                     /*Length=*/nullptr, rbLoc);
4177
4178   // Since this might be a postfix expression, get rid of ParenListExprs.
4179   if (isa<ParenListExpr>(base)) {
4180     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4181     if (result.isInvalid()) return ExprError();
4182     base = result.get();
4183   }
4184
4185   // Handle any non-overload placeholder types in the base and index
4186   // expressions.  We can't handle overloads here because the other
4187   // operand might be an overloadable type, in which case the overload
4188   // resolution for the operator overload should get the first crack
4189   // at the overload.
4190   bool IsMSPropertySubscript = false;
4191   if (base->getType()->isNonOverloadPlaceholderType()) {
4192     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4193     if (!IsMSPropertySubscript) {
4194       ExprResult result = CheckPlaceholderExpr(base);
4195       if (result.isInvalid())
4196         return ExprError();
4197       base = result.get();
4198     }
4199   }
4200   if (idx->getType()->isNonOverloadPlaceholderType()) {
4201     ExprResult result = CheckPlaceholderExpr(idx);
4202     if (result.isInvalid()) return ExprError();
4203     idx = result.get();
4204   }
4205
4206   // Build an unanalyzed expression if either operand is type-dependent.
4207   if (getLangOpts().CPlusPlus &&
4208       (base->isTypeDependent() || idx->isTypeDependent())) {
4209     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4210                                             VK_LValue, OK_Ordinary, rbLoc);
4211   }
4212
4213   // MSDN, property (C++)
4214   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4215   // This attribute can also be used in the declaration of an empty array in a
4216   // class or structure definition. For example:
4217   // __declspec(property(get=GetX, put=PutX)) int x[];
4218   // The above statement indicates that x[] can be used with one or more array
4219   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4220   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4221   if (IsMSPropertySubscript) {
4222     // Build MS property subscript expression if base is MS property reference
4223     // or MS property subscript.
4224     return new (Context) MSPropertySubscriptExpr(
4225         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4226   }
4227
4228   // Use C++ overloaded-operator rules if either operand has record
4229   // type.  The spec says to do this if either type is *overloadable*,
4230   // but enum types can't declare subscript operators or conversion
4231   // operators, so there's nothing interesting for overload resolution
4232   // to do if there aren't any record types involved.
4233   //
4234   // ObjC pointers have their own subscripting logic that is not tied
4235   // to overload resolution and so should not take this path.
4236   if (getLangOpts().CPlusPlus &&
4237       (base->getType()->isRecordType() ||
4238        (!base->getType()->isObjCObjectPointerType() &&
4239         idx->getType()->isRecordType()))) {
4240     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4241   }
4242
4243   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4244 }
4245
4246 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4247                                           Expr *LowerBound,
4248                                           SourceLocation ColonLoc, Expr *Length,
4249                                           SourceLocation RBLoc) {
4250   if (Base->getType()->isPlaceholderType() &&
4251       !Base->getType()->isSpecificPlaceholderType(
4252           BuiltinType::OMPArraySection)) {
4253     ExprResult Result = CheckPlaceholderExpr(Base);
4254     if (Result.isInvalid())
4255       return ExprError();
4256     Base = Result.get();
4257   }
4258   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4259     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4260     if (Result.isInvalid())
4261       return ExprError();
4262     Result = DefaultLvalueConversion(Result.get());
4263     if (Result.isInvalid())
4264       return ExprError();
4265     LowerBound = Result.get();
4266   }
4267   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4268     ExprResult Result = CheckPlaceholderExpr(Length);
4269     if (Result.isInvalid())
4270       return ExprError();
4271     Result = DefaultLvalueConversion(Result.get());
4272     if (Result.isInvalid())
4273       return ExprError();
4274     Length = Result.get();
4275   }
4276
4277   // Build an unanalyzed expression if either operand is type-dependent.
4278   if (Base->isTypeDependent() ||
4279       (LowerBound &&
4280        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4281       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4282     return new (Context)
4283         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4284                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4285   }
4286
4287   // Perform default conversions.
4288   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4289   QualType ResultTy;
4290   if (OriginalTy->isAnyPointerType()) {
4291     ResultTy = OriginalTy->getPointeeType();
4292   } else if (OriginalTy->isArrayType()) {
4293     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4294   } else {
4295     return ExprError(
4296         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4297         << Base->getSourceRange());
4298   }
4299   // C99 6.5.2.1p1
4300   if (LowerBound) {
4301     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4302                                                       LowerBound);
4303     if (Res.isInvalid())
4304       return ExprError(Diag(LowerBound->getExprLoc(),
4305                             diag::err_omp_typecheck_section_not_integer)
4306                        << 0 << LowerBound->getSourceRange());
4307     LowerBound = Res.get();
4308
4309     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4310         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4311       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4312           << 0 << LowerBound->getSourceRange();
4313   }
4314   if (Length) {
4315     auto Res =
4316         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4317     if (Res.isInvalid())
4318       return ExprError(Diag(Length->getExprLoc(),
4319                             diag::err_omp_typecheck_section_not_integer)
4320                        << 1 << Length->getSourceRange());
4321     Length = Res.get();
4322
4323     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4324         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4325       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4326           << 1 << Length->getSourceRange();
4327   }
4328
4329   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4330   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4331   // type. Note that functions are not objects, and that (in C99 parlance)
4332   // incomplete types are not object types.
4333   if (ResultTy->isFunctionType()) {
4334     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4335         << ResultTy << Base->getSourceRange();
4336     return ExprError();
4337   }
4338
4339   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4340                           diag::err_omp_section_incomplete_type, Base))
4341     return ExprError();
4342
4343   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4344     llvm::APSInt LowerBoundValue;
4345     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4346       // OpenMP 4.5, [2.4 Array Sections]
4347       // The array section must be a subset of the original array.
4348       if (LowerBoundValue.isNegative()) {
4349         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4350             << LowerBound->getSourceRange();
4351         return ExprError();
4352       }
4353     }
4354   }
4355
4356   if (Length) {
4357     llvm::APSInt LengthValue;
4358     if (Length->EvaluateAsInt(LengthValue, Context)) {
4359       // OpenMP 4.5, [2.4 Array Sections]
4360       // The length must evaluate to non-negative integers.
4361       if (LengthValue.isNegative()) {
4362         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4363             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4364             << Length->getSourceRange();
4365         return ExprError();
4366       }
4367     }
4368   } else if (ColonLoc.isValid() &&
4369              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4370                                       !OriginalTy->isVariableArrayType()))) {
4371     // OpenMP 4.5, [2.4 Array Sections]
4372     // When the size of the array dimension is not known, the length must be
4373     // specified explicitly.
4374     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4375         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4376     return ExprError();
4377   }
4378
4379   if (!Base->getType()->isSpecificPlaceholderType(
4380           BuiltinType::OMPArraySection)) {
4381     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4382     if (Result.isInvalid())
4383       return ExprError();
4384     Base = Result.get();
4385   }
4386   return new (Context)
4387       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4388                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4389 }
4390
4391 ExprResult
4392 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4393                                       Expr *Idx, SourceLocation RLoc) {
4394   Expr *LHSExp = Base;
4395   Expr *RHSExp = Idx;
4396
4397   ExprValueKind VK = VK_LValue;
4398   ExprObjectKind OK = OK_Ordinary;
4399
4400   // Per C++ core issue 1213, the result is an xvalue if either operand is
4401   // a non-lvalue array, and an lvalue otherwise.
4402   if (getLangOpts().CPlusPlus11 &&
4403       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4404        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4405     VK = VK_XValue;
4406
4407   // Perform default conversions.
4408   if (!LHSExp->getType()->getAs<VectorType>()) {
4409     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4410     if (Result.isInvalid())
4411       return ExprError();
4412     LHSExp = Result.get();
4413   }
4414   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4415   if (Result.isInvalid())
4416     return ExprError();
4417   RHSExp = Result.get();
4418
4419   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4420
4421   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4422   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4423   // in the subscript position. As a result, we need to derive the array base
4424   // and index from the expression types.
4425   Expr *BaseExpr, *IndexExpr;
4426   QualType ResultType;
4427   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4428     BaseExpr = LHSExp;
4429     IndexExpr = RHSExp;
4430     ResultType = Context.DependentTy;
4431   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4432     BaseExpr = LHSExp;
4433     IndexExpr = RHSExp;
4434     ResultType = PTy->getPointeeType();
4435   } else if (const ObjCObjectPointerType *PTy =
4436                LHSTy->getAs<ObjCObjectPointerType>()) {
4437     BaseExpr = LHSExp;
4438     IndexExpr = RHSExp;
4439
4440     // Use custom logic if this should be the pseudo-object subscript
4441     // expression.
4442     if (!LangOpts.isSubscriptPointerArithmetic())
4443       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4444                                           nullptr);
4445
4446     ResultType = PTy->getPointeeType();
4447   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4448      // Handle the uncommon case of "123[Ptr]".
4449     BaseExpr = RHSExp;
4450     IndexExpr = LHSExp;
4451     ResultType = PTy->getPointeeType();
4452   } else if (const ObjCObjectPointerType *PTy =
4453                RHSTy->getAs<ObjCObjectPointerType>()) {
4454      // Handle the uncommon case of "123[Ptr]".
4455     BaseExpr = RHSExp;
4456     IndexExpr = LHSExp;
4457     ResultType = PTy->getPointeeType();
4458     if (!LangOpts.isSubscriptPointerArithmetic()) {
4459       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4460         << ResultType << BaseExpr->getSourceRange();
4461       return ExprError();
4462     }
4463   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4464     BaseExpr = LHSExp;    // vectors: V[123]
4465     IndexExpr = RHSExp;
4466     VK = LHSExp->getValueKind();
4467     if (VK != VK_RValue)
4468       OK = OK_VectorComponent;
4469
4470     // FIXME: need to deal with const...
4471     ResultType = VTy->getElementType();
4472   } else if (LHSTy->isArrayType()) {
4473     // If we see an array that wasn't promoted by
4474     // DefaultFunctionArrayLvalueConversion, it must be an array that
4475     // wasn't promoted because of the C90 rule that doesn't
4476     // allow promoting non-lvalue arrays.  Warn, then
4477     // force the promotion here.
4478     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4479         LHSExp->getSourceRange();
4480     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4481                                CK_ArrayToPointerDecay).get();
4482     LHSTy = LHSExp->getType();
4483
4484     BaseExpr = LHSExp;
4485     IndexExpr = RHSExp;
4486     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4487   } else if (RHSTy->isArrayType()) {
4488     // Same as previous, except for 123[f().a] case
4489     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4490         RHSExp->getSourceRange();
4491     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4492                                CK_ArrayToPointerDecay).get();
4493     RHSTy = RHSExp->getType();
4494
4495     BaseExpr = RHSExp;
4496     IndexExpr = LHSExp;
4497     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4498   } else {
4499     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4500        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4501   }
4502   // C99 6.5.2.1p1
4503   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4504     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4505                      << IndexExpr->getSourceRange());
4506
4507   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4508        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4509          && !IndexExpr->isTypeDependent())
4510     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4511
4512   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4513   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4514   // type. Note that Functions are not objects, and that (in C99 parlance)
4515   // incomplete types are not object types.
4516   if (ResultType->isFunctionType()) {
4517     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4518       << ResultType << BaseExpr->getSourceRange();
4519     return ExprError();
4520   }
4521
4522   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4523     // GNU extension: subscripting on pointer to void
4524     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4525       << BaseExpr->getSourceRange();
4526
4527     // C forbids expressions of unqualified void type from being l-values.
4528     // See IsCForbiddenLValueType.
4529     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4530   } else if (!ResultType->isDependentType() &&
4531       RequireCompleteType(LLoc, ResultType,
4532                           diag::err_subscript_incomplete_type, BaseExpr))
4533     return ExprError();
4534
4535   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4536          !ResultType.isCForbiddenLValueType());
4537
4538   return new (Context)
4539       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4540 }
4541
4542 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4543                                   ParmVarDecl *Param) {
4544   if (Param->hasUnparsedDefaultArg()) {
4545     Diag(CallLoc,
4546          diag::err_use_of_default_argument_to_function_declared_later) <<
4547       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4548     Diag(UnparsedDefaultArgLocs[Param],
4549          diag::note_default_argument_declared_here);
4550     return true;
4551   }
4552   
4553   if (Param->hasUninstantiatedDefaultArg()) {
4554     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4555
4556     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4557                                                  Param);
4558
4559     // Instantiate the expression.
4560     MultiLevelTemplateArgumentList MutiLevelArgList
4561       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4562
4563     InstantiatingTemplate Inst(*this, CallLoc, Param,
4564                                MutiLevelArgList.getInnermost());
4565     if (Inst.isInvalid())
4566       return true;
4567     if (Inst.isAlreadyInstantiating()) {
4568       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4569       Param->setInvalidDecl();
4570       return true;
4571     }
4572
4573     ExprResult Result;
4574     {
4575       // C++ [dcl.fct.default]p5:
4576       //   The names in the [default argument] expression are bound, and
4577       //   the semantic constraints are checked, at the point where the
4578       //   default argument expression appears.
4579       ContextRAII SavedContext(*this, FD);
4580       LocalInstantiationScope Local(*this);
4581       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4582                                 /*DirectInit*/false);
4583     }
4584     if (Result.isInvalid())
4585       return true;
4586
4587     // Check the expression as an initializer for the parameter.
4588     InitializedEntity Entity
4589       = InitializedEntity::InitializeParameter(Context, Param);
4590     InitializationKind Kind
4591       = InitializationKind::CreateCopy(Param->getLocation(),
4592              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4593     Expr *ResultE = Result.getAs<Expr>();
4594
4595     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4596     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4597     if (Result.isInvalid())
4598       return true;
4599
4600     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4601                                  Param->getOuterLocStart());
4602     if (Result.isInvalid())
4603       return true;
4604
4605     // Remember the instantiated default argument.
4606     Param->setDefaultArg(Result.getAs<Expr>());
4607     if (ASTMutationListener *L = getASTMutationListener()) {
4608       L->DefaultArgumentInstantiated(Param);
4609     }
4610   }
4611
4612   // If the default argument expression is not set yet, we are building it now.
4613   if (!Param->hasInit()) {
4614     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4615     Param->setInvalidDecl();
4616     return true;
4617   }
4618
4619   // If the default expression creates temporaries, we need to
4620   // push them to the current stack of expression temporaries so they'll
4621   // be properly destroyed.
4622   // FIXME: We should really be rebuilding the default argument with new
4623   // bound temporaries; see the comment in PR5810.
4624   // We don't need to do that with block decls, though, because
4625   // blocks in default argument expression can never capture anything.
4626   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4627     // Set the "needs cleanups" bit regardless of whether there are
4628     // any explicit objects.
4629     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4630
4631     // Append all the objects to the cleanup list.  Right now, this
4632     // should always be a no-op, because blocks in default argument
4633     // expressions should never be able to capture anything.
4634     assert(!Init->getNumObjects() &&
4635            "default argument expression has capturing blocks?");
4636   }
4637
4638   // We already type-checked the argument, so we know it works. 
4639   // Just mark all of the declarations in this potentially-evaluated expression
4640   // as being "referenced".
4641   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4642                                    /*SkipLocalVariables=*/true);
4643   return false;
4644 }
4645
4646 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4647                                         FunctionDecl *FD, ParmVarDecl *Param) {
4648   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4649     return ExprError();
4650   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4651 }
4652
4653 Sema::VariadicCallType
4654 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4655                           Expr *Fn) {
4656   if (Proto && Proto->isVariadic()) {
4657     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4658       return VariadicConstructor;
4659     else if (Fn && Fn->getType()->isBlockPointerType())
4660       return VariadicBlock;
4661     else if (FDecl) {
4662       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4663         if (Method->isInstance())
4664           return VariadicMethod;
4665     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4666       return VariadicMethod;
4667     return VariadicFunction;
4668   }
4669   return VariadicDoesNotApply;
4670 }
4671
4672 namespace {
4673 class FunctionCallCCC : public FunctionCallFilterCCC {
4674 public:
4675   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4676                   unsigned NumArgs, MemberExpr *ME)
4677       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4678         FunctionName(FuncName) {}
4679
4680   bool ValidateCandidate(const TypoCorrection &candidate) override {
4681     if (!candidate.getCorrectionSpecifier() ||
4682         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4683       return false;
4684     }
4685
4686     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4687   }
4688
4689 private:
4690   const IdentifierInfo *const FunctionName;
4691 };
4692 }
4693
4694 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4695                                                FunctionDecl *FDecl,
4696                                                ArrayRef<Expr *> Args) {
4697   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4698   DeclarationName FuncName = FDecl->getDeclName();
4699   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4700
4701   if (TypoCorrection Corrected = S.CorrectTypo(
4702           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4703           S.getScopeForContext(S.CurContext), nullptr,
4704           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4705                                              Args.size(), ME),
4706           Sema::CTK_ErrorRecovery)) {
4707     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4708       if (Corrected.isOverloaded()) {
4709         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4710         OverloadCandidateSet::iterator Best;
4711         for (NamedDecl *CD : Corrected) {
4712           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4713             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4714                                    OCS);
4715         }
4716         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4717         case OR_Success:
4718           ND = Best->FoundDecl;
4719           Corrected.setCorrectionDecl(ND);
4720           break;
4721         default:
4722           break;
4723         }
4724       }
4725       ND = ND->getUnderlyingDecl();
4726       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4727         return Corrected;
4728     }
4729   }
4730   return TypoCorrection();
4731 }
4732
4733 /// ConvertArgumentsForCall - Converts the arguments specified in
4734 /// Args/NumArgs to the parameter types of the function FDecl with
4735 /// function prototype Proto. Call is the call expression itself, and
4736 /// Fn is the function expression. For a C++ member function, this
4737 /// routine does not attempt to convert the object argument. Returns
4738 /// true if the call is ill-formed.
4739 bool
4740 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4741                               FunctionDecl *FDecl,
4742                               const FunctionProtoType *Proto,
4743                               ArrayRef<Expr *> Args,
4744                               SourceLocation RParenLoc,
4745                               bool IsExecConfig) {
4746   // Bail out early if calling a builtin with custom typechecking.
4747   if (FDecl)
4748     if (unsigned ID = FDecl->getBuiltinID())
4749       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4750         return false;
4751
4752   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4753   // assignment, to the types of the corresponding parameter, ...
4754   unsigned NumParams = Proto->getNumParams();
4755   bool Invalid = false;
4756   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4757   unsigned FnKind = Fn->getType()->isBlockPointerType()
4758                        ? 1 /* block */
4759                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4760                                        : 0 /* function */);
4761
4762   // If too few arguments are available (and we don't have default
4763   // arguments for the remaining parameters), don't make the call.
4764   if (Args.size() < NumParams) {
4765     if (Args.size() < MinArgs) {
4766       TypoCorrection TC;
4767       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4768         unsigned diag_id =
4769             MinArgs == NumParams && !Proto->isVariadic()
4770                 ? diag::err_typecheck_call_too_few_args_suggest
4771                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4772         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4773                                         << static_cast<unsigned>(Args.size())
4774                                         << TC.getCorrectionRange());
4775       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4776         Diag(RParenLoc,
4777              MinArgs == NumParams && !Proto->isVariadic()
4778                  ? diag::err_typecheck_call_too_few_args_one
4779                  : diag::err_typecheck_call_too_few_args_at_least_one)
4780             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4781       else
4782         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4783                             ? diag::err_typecheck_call_too_few_args
4784                             : diag::err_typecheck_call_too_few_args_at_least)
4785             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4786             << Fn->getSourceRange();
4787
4788       // Emit the location of the prototype.
4789       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4790         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4791           << FDecl;
4792
4793       return true;
4794     }
4795     Call->setNumArgs(Context, NumParams);
4796   }
4797
4798   // If too many are passed and not variadic, error on the extras and drop
4799   // them.
4800   if (Args.size() > NumParams) {
4801     if (!Proto->isVariadic()) {
4802       TypoCorrection TC;
4803       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4804         unsigned diag_id =
4805             MinArgs == NumParams && !Proto->isVariadic()
4806                 ? diag::err_typecheck_call_too_many_args_suggest
4807                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4808         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4809                                         << static_cast<unsigned>(Args.size())
4810                                         << TC.getCorrectionRange());
4811       } else if (NumParams == 1 && FDecl &&
4812                  FDecl->getParamDecl(0)->getDeclName())
4813         Diag(Args[NumParams]->getLocStart(),
4814              MinArgs == NumParams
4815                  ? diag::err_typecheck_call_too_many_args_one
4816                  : diag::err_typecheck_call_too_many_args_at_most_one)
4817             << FnKind << FDecl->getParamDecl(0)
4818             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4819             << SourceRange(Args[NumParams]->getLocStart(),
4820                            Args.back()->getLocEnd());
4821       else
4822         Diag(Args[NumParams]->getLocStart(),
4823              MinArgs == NumParams
4824                  ? diag::err_typecheck_call_too_many_args
4825                  : diag::err_typecheck_call_too_many_args_at_most)
4826             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4827             << Fn->getSourceRange()
4828             << SourceRange(Args[NumParams]->getLocStart(),
4829                            Args.back()->getLocEnd());
4830
4831       // Emit the location of the prototype.
4832       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4833         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4834           << FDecl;
4835       
4836       // This deletes the extra arguments.
4837       Call->setNumArgs(Context, NumParams);
4838       return true;
4839     }
4840   }
4841   SmallVector<Expr *, 8> AllArgs;
4842   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4843   
4844   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4845                                    Proto, 0, Args, AllArgs, CallType);
4846   if (Invalid)
4847     return true;
4848   unsigned TotalNumArgs = AllArgs.size();
4849   for (unsigned i = 0; i < TotalNumArgs; ++i)
4850     Call->setArg(i, AllArgs[i]);
4851
4852   return false;
4853 }
4854
4855 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4856                                   const FunctionProtoType *Proto,
4857                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4858                                   SmallVectorImpl<Expr *> &AllArgs,
4859                                   VariadicCallType CallType, bool AllowExplicit,
4860                                   bool IsListInitialization) {
4861   unsigned NumParams = Proto->getNumParams();
4862   bool Invalid = false;
4863   size_t ArgIx = 0;
4864   // Continue to check argument types (even if we have too few/many args).
4865   for (unsigned i = FirstParam; i < NumParams; i++) {
4866     QualType ProtoArgType = Proto->getParamType(i);
4867
4868     Expr *Arg;
4869     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4870     if (ArgIx < Args.size()) {
4871       Arg = Args[ArgIx++];
4872
4873       if (RequireCompleteType(Arg->getLocStart(),
4874                               ProtoArgType,
4875                               diag::err_call_incomplete_argument, Arg))
4876         return true;
4877
4878       // Strip the unbridged-cast placeholder expression off, if applicable.
4879       bool CFAudited = false;
4880       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4881           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4882           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4883         Arg = stripARCUnbridgedCast(Arg);
4884       else if (getLangOpts().ObjCAutoRefCount &&
4885                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4886                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4887         CFAudited = true;
4888
4889       InitializedEntity Entity =
4890           Param ? InitializedEntity::InitializeParameter(Context, Param,
4891                                                          ProtoArgType)
4892                 : InitializedEntity::InitializeParameter(
4893                       Context, ProtoArgType, Proto->isParamConsumed(i));
4894
4895       // Remember that parameter belongs to a CF audited API.
4896       if (CFAudited)
4897         Entity.setParameterCFAudited();
4898
4899       ExprResult ArgE = PerformCopyInitialization(
4900           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4901       if (ArgE.isInvalid())
4902         return true;
4903
4904       Arg = ArgE.getAs<Expr>();
4905     } else {
4906       assert(Param && "can't use default arguments without a known callee");
4907
4908       ExprResult ArgExpr =
4909         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4910       if (ArgExpr.isInvalid())
4911         return true;
4912
4913       Arg = ArgExpr.getAs<Expr>();
4914     }
4915
4916     // Check for array bounds violations for each argument to the call. This
4917     // check only triggers warnings when the argument isn't a more complex Expr
4918     // with its own checking, such as a BinaryOperator.
4919     CheckArrayAccess(Arg);
4920
4921     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4922     CheckStaticArrayArgument(CallLoc, Param, Arg);
4923
4924     AllArgs.push_back(Arg);
4925   }
4926
4927   // If this is a variadic call, handle args passed through "...".
4928   if (CallType != VariadicDoesNotApply) {
4929     // Assume that extern "C" functions with variadic arguments that
4930     // return __unknown_anytype aren't *really* variadic.
4931     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4932         FDecl->isExternC()) {
4933       for (Expr *A : Args.slice(ArgIx)) {
4934         QualType paramType; // ignored
4935         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4936         Invalid |= arg.isInvalid();
4937         AllArgs.push_back(arg.get());
4938       }
4939
4940     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4941     } else {
4942       for (Expr *A : Args.slice(ArgIx)) {
4943         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4944         Invalid |= Arg.isInvalid();
4945         AllArgs.push_back(Arg.get());
4946       }
4947     }
4948
4949     // Check for array bounds violations.
4950     for (Expr *A : Args.slice(ArgIx))
4951       CheckArrayAccess(A);
4952   }
4953   return Invalid;
4954 }
4955
4956 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4957   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4958   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4959     TL = DTL.getOriginalLoc();
4960   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4961     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4962       << ATL.getLocalSourceRange();
4963 }
4964
4965 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4966 /// array parameter, check that it is non-null, and that if it is formed by
4967 /// array-to-pointer decay, the underlying array is sufficiently large.
4968 ///
4969 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4970 /// array type derivation, then for each call to the function, the value of the
4971 /// corresponding actual argument shall provide access to the first element of
4972 /// an array with at least as many elements as specified by the size expression.
4973 void
4974 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4975                                ParmVarDecl *Param,
4976                                const Expr *ArgExpr) {
4977   // Static array parameters are not supported in C++.
4978   if (!Param || getLangOpts().CPlusPlus)
4979     return;
4980
4981   QualType OrigTy = Param->getOriginalType();
4982
4983   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4984   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4985     return;
4986
4987   if (ArgExpr->isNullPointerConstant(Context,
4988                                      Expr::NPC_NeverValueDependent)) {
4989     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4990     DiagnoseCalleeStaticArrayParam(*this, Param);
4991     return;
4992   }
4993
4994   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4995   if (!CAT)
4996     return;
4997
4998   const ConstantArrayType *ArgCAT =
4999     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5000   if (!ArgCAT)
5001     return;
5002
5003   if (ArgCAT->getSize().ult(CAT->getSize())) {
5004     Diag(CallLoc, diag::warn_static_array_too_small)
5005       << ArgExpr->getSourceRange()
5006       << (unsigned) ArgCAT->getSize().getZExtValue()
5007       << (unsigned) CAT->getSize().getZExtValue();
5008     DiagnoseCalleeStaticArrayParam(*this, Param);
5009   }
5010 }
5011
5012 /// Given a function expression of unknown-any type, try to rebuild it
5013 /// to have a function type.
5014 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5015
5016 /// Is the given type a placeholder that we need to lower out
5017 /// immediately during argument processing?
5018 static bool isPlaceholderToRemoveAsArg(QualType type) {
5019   // Placeholders are never sugared.
5020   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5021   if (!placeholder) return false;
5022
5023   switch (placeholder->getKind()) {
5024   // Ignore all the non-placeholder types.
5025 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5026   case BuiltinType::Id:
5027 #include "clang/Basic/OpenCLImageTypes.def"
5028 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5029 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5030 #include "clang/AST/BuiltinTypes.def"
5031     return false;
5032
5033   // We cannot lower out overload sets; they might validly be resolved
5034   // by the call machinery.
5035   case BuiltinType::Overload:
5036     return false;
5037
5038   // Unbridged casts in ARC can be handled in some call positions and
5039   // should be left in place.
5040   case BuiltinType::ARCUnbridgedCast:
5041     return false;
5042
5043   // Pseudo-objects should be converted as soon as possible.
5044   case BuiltinType::PseudoObject:
5045     return true;
5046
5047   // The debugger mode could theoretically but currently does not try
5048   // to resolve unknown-typed arguments based on known parameter types.
5049   case BuiltinType::UnknownAny:
5050     return true;
5051
5052   // These are always invalid as call arguments and should be reported.
5053   case BuiltinType::BoundMember:
5054   case BuiltinType::BuiltinFn:
5055   case BuiltinType::OMPArraySection:
5056     return true;
5057
5058   }
5059   llvm_unreachable("bad builtin type kind");
5060 }
5061
5062 /// Check an argument list for placeholders that we won't try to
5063 /// handle later.
5064 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5065   // Apply this processing to all the arguments at once instead of
5066   // dying at the first failure.
5067   bool hasInvalid = false;
5068   for (size_t i = 0, e = args.size(); i != e; i++) {
5069     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5070       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5071       if (result.isInvalid()) hasInvalid = true;
5072       else args[i] = result.get();
5073     } else if (hasInvalid) {
5074       (void)S.CorrectDelayedTyposInExpr(args[i]);
5075     }
5076   }
5077   return hasInvalid;
5078 }
5079
5080 /// If a builtin function has a pointer argument with no explicit address
5081 /// space, then it should be able to accept a pointer to any address
5082 /// space as input.  In order to do this, we need to replace the
5083 /// standard builtin declaration with one that uses the same address space
5084 /// as the call.
5085 ///
5086 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5087 ///                  it does not contain any pointer arguments without
5088 ///                  an address space qualifer.  Otherwise the rewritten
5089 ///                  FunctionDecl is returned.
5090 /// TODO: Handle pointer return types.
5091 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5092                                                 const FunctionDecl *FDecl,
5093                                                 MultiExprArg ArgExprs) {
5094
5095   QualType DeclType = FDecl->getType();
5096   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5097
5098   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5099       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5100     return nullptr;
5101
5102   bool NeedsNewDecl = false;
5103   unsigned i = 0;
5104   SmallVector<QualType, 8> OverloadParams;
5105
5106   for (QualType ParamType : FT->param_types()) {
5107
5108     // Convert array arguments to pointer to simplify type lookup.
5109     ExprResult ArgRes =
5110         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5111     if (ArgRes.isInvalid())
5112       return nullptr;
5113     Expr *Arg = ArgRes.get();
5114     QualType ArgType = Arg->getType();
5115     if (!ParamType->isPointerType() ||
5116         ParamType.getQualifiers().hasAddressSpace() ||
5117         !ArgType->isPointerType() ||
5118         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5119       OverloadParams.push_back(ParamType);
5120       continue;
5121     }
5122
5123     NeedsNewDecl = true;
5124     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5125
5126     QualType PointeeType = ParamType->getPointeeType();
5127     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5128     OverloadParams.push_back(Context.getPointerType(PointeeType));
5129   }
5130
5131   if (!NeedsNewDecl)
5132     return nullptr;
5133
5134   FunctionProtoType::ExtProtoInfo EPI;
5135   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5136                                                 OverloadParams, EPI);
5137   DeclContext *Parent = Context.getTranslationUnitDecl();
5138   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5139                                                     FDecl->getLocation(),
5140                                                     FDecl->getLocation(),
5141                                                     FDecl->getIdentifier(),
5142                                                     OverloadTy,
5143                                                     /*TInfo=*/nullptr,
5144                                                     SC_Extern, false,
5145                                                     /*hasPrototype=*/true);
5146   SmallVector<ParmVarDecl*, 16> Params;
5147   FT = cast<FunctionProtoType>(OverloadTy);
5148   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5149     QualType ParamType = FT->getParamType(i);
5150     ParmVarDecl *Parm =
5151         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5152                                 SourceLocation(), nullptr, ParamType,
5153                                 /*TInfo=*/nullptr, SC_None, nullptr);
5154     Parm->setScopeInfo(0, i);
5155     Params.push_back(Parm);
5156   }
5157   OverloadDecl->setParams(Params);
5158   return OverloadDecl;
5159 }
5160
5161 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5162                                     FunctionDecl *Callee,
5163                                     MultiExprArg ArgExprs) {
5164   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5165   // similar attributes) really don't like it when functions are called with an
5166   // invalid number of args.
5167   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5168                          /*PartialOverloading=*/false) &&
5169       !Callee->isVariadic())
5170     return;
5171   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5172     return;
5173
5174   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5175     S.Diag(Fn->getLocStart(),
5176            isa<CXXMethodDecl>(Callee)
5177                ? diag::err_ovl_no_viable_member_function_in_call
5178                : diag::err_ovl_no_viable_function_in_call)
5179         << Callee << Callee->getSourceRange();
5180     S.Diag(Callee->getLocation(),
5181            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5182         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5183     return;
5184   }
5185 }
5186
5187 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5188 /// This provides the location of the left/right parens and a list of comma
5189 /// locations.
5190 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5191                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5192                                Expr *ExecConfig, bool IsExecConfig) {
5193   // Since this might be a postfix expression, get rid of ParenListExprs.
5194   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5195   if (Result.isInvalid()) return ExprError();
5196   Fn = Result.get();
5197
5198   if (checkArgsForPlaceholders(*this, ArgExprs))
5199     return ExprError();
5200
5201   if (getLangOpts().CPlusPlus) {
5202     // If this is a pseudo-destructor expression, build the call immediately.
5203     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5204       if (!ArgExprs.empty()) {
5205         // Pseudo-destructor calls should not have any arguments.
5206         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5207             << FixItHint::CreateRemoval(
5208                    SourceRange(ArgExprs.front()->getLocStart(),
5209                                ArgExprs.back()->getLocEnd()));
5210       }
5211
5212       return new (Context)
5213           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5214     }
5215     if (Fn->getType() == Context.PseudoObjectTy) {
5216       ExprResult result = CheckPlaceholderExpr(Fn);
5217       if (result.isInvalid()) return ExprError();
5218       Fn = result.get();
5219     }
5220
5221     // Determine whether this is a dependent call inside a C++ template,
5222     // in which case we won't do any semantic analysis now.
5223     bool Dependent = false;
5224     if (Fn->isTypeDependent())
5225       Dependent = true;
5226     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5227       Dependent = true;
5228
5229     if (Dependent) {
5230       if (ExecConfig) {
5231         return new (Context) CUDAKernelCallExpr(
5232             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5233             Context.DependentTy, VK_RValue, RParenLoc);
5234       } else {
5235         return new (Context) CallExpr(
5236             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5237       }
5238     }
5239
5240     // Determine whether this is a call to an object (C++ [over.call.object]).
5241     if (Fn->getType()->isRecordType())
5242       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5243                                           RParenLoc);
5244
5245     if (Fn->getType() == Context.UnknownAnyTy) {
5246       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5247       if (result.isInvalid()) return ExprError();
5248       Fn = result.get();
5249     }
5250
5251     if (Fn->getType() == Context.BoundMemberTy) {
5252       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5253                                        RParenLoc);
5254     }
5255   }
5256
5257   // Check for overloaded calls.  This can happen even in C due to extensions.
5258   if (Fn->getType() == Context.OverloadTy) {
5259     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5260
5261     // We aren't supposed to apply this logic for if there'Scope an '&'
5262     // involved.
5263     if (!find.HasFormOfMemberPointer) {
5264       OverloadExpr *ovl = find.Expression;
5265       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5266         return BuildOverloadedCallExpr(
5267             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5268             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5269       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5270                                        RParenLoc);
5271     }
5272   }
5273
5274   // If we're directly calling a function, get the appropriate declaration.
5275   if (Fn->getType() == Context.UnknownAnyTy) {
5276     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5277     if (result.isInvalid()) return ExprError();
5278     Fn = result.get();
5279   }
5280
5281   Expr *NakedFn = Fn->IgnoreParens();
5282
5283   bool CallingNDeclIndirectly = false;
5284   NamedDecl *NDecl = nullptr;
5285   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5286     if (UnOp->getOpcode() == UO_AddrOf) {
5287       CallingNDeclIndirectly = true;
5288       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5289     }
5290   }
5291
5292   if (isa<DeclRefExpr>(NakedFn)) {
5293     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5294
5295     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5296     if (FDecl && FDecl->getBuiltinID()) {
5297       // Rewrite the function decl for this builtin by replacing parameters
5298       // with no explicit address space with the address space of the arguments
5299       // in ArgExprs.
5300       if ((FDecl =
5301                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5302         NDecl = FDecl;
5303         Fn = DeclRefExpr::Create(
5304             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5305             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5306       }
5307     }
5308   } else if (isa<MemberExpr>(NakedFn))
5309     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5310
5311   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5312     if (CallingNDeclIndirectly &&
5313         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5314                                            Fn->getLocStart()))
5315       return ExprError();
5316
5317     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5318       return ExprError();
5319
5320     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5321   }
5322
5323   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5324                                ExecConfig, IsExecConfig);
5325 }
5326
5327 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5328 ///
5329 /// __builtin_astype( value, dst type )
5330 ///
5331 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5332                                  SourceLocation BuiltinLoc,
5333                                  SourceLocation RParenLoc) {
5334   ExprValueKind VK = VK_RValue;
5335   ExprObjectKind OK = OK_Ordinary;
5336   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5337   QualType SrcTy = E->getType();
5338   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5339     return ExprError(Diag(BuiltinLoc,
5340                           diag::err_invalid_astype_of_different_size)
5341                      << DstTy
5342                      << SrcTy
5343                      << E->getSourceRange());
5344   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5345 }
5346
5347 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5348 /// provided arguments.
5349 ///
5350 /// __builtin_convertvector( value, dst type )
5351 ///
5352 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5353                                         SourceLocation BuiltinLoc,
5354                                         SourceLocation RParenLoc) {
5355   TypeSourceInfo *TInfo;
5356   GetTypeFromParser(ParsedDestTy, &TInfo);
5357   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5358 }
5359
5360 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5361 /// i.e. an expression not of \p OverloadTy.  The expression should
5362 /// unary-convert to an expression of function-pointer or
5363 /// block-pointer type.
5364 ///
5365 /// \param NDecl the declaration being called, if available
5366 ExprResult
5367 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5368                             SourceLocation LParenLoc,
5369                             ArrayRef<Expr *> Args,
5370                             SourceLocation RParenLoc,
5371                             Expr *Config, bool IsExecConfig) {
5372   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5373   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5374
5375   // Functions with 'interrupt' attribute cannot be called directly.
5376   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5377     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5378     return ExprError();
5379   }
5380
5381   // Promote the function operand.
5382   // We special-case function promotion here because we only allow promoting
5383   // builtin functions to function pointers in the callee of a call.
5384   ExprResult Result;
5385   if (BuiltinID &&
5386       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5387     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5388                                CK_BuiltinFnToFnPtr).get();
5389   } else {
5390     Result = CallExprUnaryConversions(Fn);
5391   }
5392   if (Result.isInvalid())
5393     return ExprError();
5394   Fn = Result.get();
5395
5396   // Make the call expr early, before semantic checks.  This guarantees cleanup
5397   // of arguments and function on error.
5398   CallExpr *TheCall;
5399   if (Config)
5400     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5401                                                cast<CallExpr>(Config), Args,
5402                                                Context.BoolTy, VK_RValue,
5403                                                RParenLoc);
5404   else
5405     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5406                                      VK_RValue, RParenLoc);
5407
5408   if (!getLangOpts().CPlusPlus) {
5409     // C cannot always handle TypoExpr nodes in builtin calls and direct
5410     // function calls as their argument checking don't necessarily handle
5411     // dependent types properly, so make sure any TypoExprs have been
5412     // dealt with.
5413     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5414     if (!Result.isUsable()) return ExprError();
5415     TheCall = dyn_cast<CallExpr>(Result.get());
5416     if (!TheCall) return Result;
5417     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5418   }
5419
5420   // Bail out early if calling a builtin with custom typechecking.
5421   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5422     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5423
5424  retry:
5425   const FunctionType *FuncT;
5426   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5427     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5428     // have type pointer to function".
5429     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5430     if (!FuncT)
5431       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5432                          << Fn->getType() << Fn->getSourceRange());
5433   } else if (const BlockPointerType *BPT =
5434                Fn->getType()->getAs<BlockPointerType>()) {
5435     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5436   } else {
5437     // Handle calls to expressions of unknown-any type.
5438     if (Fn->getType() == Context.UnknownAnyTy) {
5439       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5440       if (rewrite.isInvalid()) return ExprError();
5441       Fn = rewrite.get();
5442       TheCall->setCallee(Fn);
5443       goto retry;
5444     }
5445
5446     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5447       << Fn->getType() << Fn->getSourceRange());
5448   }
5449
5450   if (getLangOpts().CUDA) {
5451     if (Config) {
5452       // CUDA: Kernel calls must be to global functions
5453       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5454         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5455             << FDecl->getName() << Fn->getSourceRange());
5456
5457       // CUDA: Kernel function must have 'void' return type
5458       if (!FuncT->getReturnType()->isVoidType())
5459         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5460             << Fn->getType() << Fn->getSourceRange());
5461     } else {
5462       // CUDA: Calls to global functions must be configured
5463       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5464         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5465             << FDecl->getName() << Fn->getSourceRange());
5466     }
5467   }
5468
5469   // Check for a valid return type
5470   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5471                           FDecl))
5472     return ExprError();
5473
5474   // We know the result type of the call, set it.
5475   TheCall->setType(FuncT->getCallResultType(Context));
5476   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5477
5478   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5479   if (Proto) {
5480     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5481                                 IsExecConfig))
5482       return ExprError();
5483   } else {
5484     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5485
5486     if (FDecl) {
5487       // Check if we have too few/too many template arguments, based
5488       // on our knowledge of the function definition.
5489       const FunctionDecl *Def = nullptr;
5490       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5491         Proto = Def->getType()->getAs<FunctionProtoType>();
5492        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5493           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5494           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5495       }
5496       
5497       // If the function we're calling isn't a function prototype, but we have
5498       // a function prototype from a prior declaratiom, use that prototype.
5499       if (!FDecl->hasPrototype())
5500         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5501     }
5502
5503     // Promote the arguments (C99 6.5.2.2p6).
5504     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5505       Expr *Arg = Args[i];
5506
5507       if (Proto && i < Proto->getNumParams()) {
5508         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5509             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5510         ExprResult ArgE =
5511             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5512         if (ArgE.isInvalid())
5513           return true;
5514         
5515         Arg = ArgE.getAs<Expr>();
5516
5517       } else {
5518         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5519
5520         if (ArgE.isInvalid())
5521           return true;
5522
5523         Arg = ArgE.getAs<Expr>();
5524       }
5525       
5526       if (RequireCompleteType(Arg->getLocStart(),
5527                               Arg->getType(),
5528                               diag::err_call_incomplete_argument, Arg))
5529         return ExprError();
5530
5531       TheCall->setArg(i, Arg);
5532     }
5533   }
5534
5535   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5536     if (!Method->isStatic())
5537       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5538         << Fn->getSourceRange());
5539
5540   // Check for sentinels
5541   if (NDecl)
5542     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5543
5544   // Do special checking on direct calls to functions.
5545   if (FDecl) {
5546     if (CheckFunctionCall(FDecl, TheCall, Proto))
5547       return ExprError();
5548
5549     if (BuiltinID)
5550       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5551   } else if (NDecl) {
5552     if (CheckPointerCall(NDecl, TheCall, Proto))
5553       return ExprError();
5554   } else {
5555     if (CheckOtherCall(TheCall, Proto))
5556       return ExprError();
5557   }
5558
5559   return MaybeBindToTemporary(TheCall);
5560 }
5561
5562 ExprResult
5563 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5564                            SourceLocation RParenLoc, Expr *InitExpr) {
5565   assert(Ty && "ActOnCompoundLiteral(): missing type");
5566   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5567
5568   TypeSourceInfo *TInfo;
5569   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5570   if (!TInfo)
5571     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5572
5573   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5574 }
5575
5576 ExprResult
5577 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5578                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5579   QualType literalType = TInfo->getType();
5580
5581   if (literalType->isArrayType()) {
5582     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5583           diag::err_illegal_decl_array_incomplete_type,
5584           SourceRange(LParenLoc,
5585                       LiteralExpr->getSourceRange().getEnd())))
5586       return ExprError();
5587     if (literalType->isVariableArrayType())
5588       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5589         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5590   } else if (!literalType->isDependentType() &&
5591              RequireCompleteType(LParenLoc, literalType,
5592                diag::err_typecheck_decl_incomplete_type,
5593                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5594     return ExprError();
5595
5596   InitializedEntity Entity
5597     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5598   InitializationKind Kind
5599     = InitializationKind::CreateCStyleCast(LParenLoc, 
5600                                            SourceRange(LParenLoc, RParenLoc),
5601                                            /*InitList=*/true);
5602   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5603   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5604                                       &literalType);
5605   if (Result.isInvalid())
5606     return ExprError();
5607   LiteralExpr = Result.get();
5608
5609   bool isFileScope = !CurContext->isFunctionOrMethod();
5610   if (isFileScope &&
5611       !LiteralExpr->isTypeDependent() &&
5612       !LiteralExpr->isValueDependent() &&
5613       !literalType->isDependentType()) { // 6.5.2.5p3
5614     if (CheckForConstantInitializer(LiteralExpr, literalType))
5615       return ExprError();
5616   }
5617
5618   // In C, compound literals are l-values for some reason.
5619   // For GCC compatibility, in C++, file-scope array compound literals with
5620   // constant initializers are also l-values, and compound literals are
5621   // otherwise prvalues.
5622   //
5623   // (GCC also treats C++ list-initialized file-scope array prvalues with
5624   // constant initializers as l-values, but that's non-conforming, so we don't
5625   // follow it there.)
5626   //
5627   // FIXME: It would be better to handle the lvalue cases as materializing and
5628   // lifetime-extending a temporary object, but our materialized temporaries
5629   // representation only supports lifetime extension from a variable, not "out
5630   // of thin air".
5631   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5632   // is bound to the result of applying array-to-pointer decay to the compound
5633   // literal.
5634   // FIXME: GCC supports compound literals of reference type, which should
5635   // obviously have a value kind derived from the kind of reference involved.
5636   ExprValueKind VK =
5637       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5638           ? VK_RValue
5639           : VK_LValue;
5640
5641   return MaybeBindToTemporary(
5642       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5643                                         VK, LiteralExpr, isFileScope));
5644 }
5645
5646 ExprResult
5647 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5648                     SourceLocation RBraceLoc) {
5649   // Immediately handle non-overload placeholders.  Overloads can be
5650   // resolved contextually, but everything else here can't.
5651   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5652     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5653       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5654
5655       // Ignore failures; dropping the entire initializer list because
5656       // of one failure would be terrible for indexing/etc.
5657       if (result.isInvalid()) continue;
5658
5659       InitArgList[I] = result.get();
5660     }
5661   }
5662
5663   // Semantic analysis for initializers is done by ActOnDeclarator() and
5664   // CheckInitializer() - it requires knowledge of the object being intialized.
5665
5666   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5667                                                RBraceLoc);
5668   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5669   return E;
5670 }
5671
5672 /// Do an explicit extend of the given block pointer if we're in ARC.
5673 void Sema::maybeExtendBlockObject(ExprResult &E) {
5674   assert(E.get()->getType()->isBlockPointerType());
5675   assert(E.get()->isRValue());
5676
5677   // Only do this in an r-value context.
5678   if (!getLangOpts().ObjCAutoRefCount) return;
5679
5680   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5681                                CK_ARCExtendBlockObject, E.get(),
5682                                /*base path*/ nullptr, VK_RValue);
5683   Cleanup.setExprNeedsCleanups(true);
5684 }
5685
5686 /// Prepare a conversion of the given expression to an ObjC object
5687 /// pointer type.
5688 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5689   QualType type = E.get()->getType();
5690   if (type->isObjCObjectPointerType()) {
5691     return CK_BitCast;
5692   } else if (type->isBlockPointerType()) {
5693     maybeExtendBlockObject(E);
5694     return CK_BlockPointerToObjCPointerCast;
5695   } else {
5696     assert(type->isPointerType());
5697     return CK_CPointerToObjCPointerCast;
5698   }
5699 }
5700
5701 /// Prepares for a scalar cast, performing all the necessary stages
5702 /// except the final cast and returning the kind required.
5703 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5704   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5705   // Also, callers should have filtered out the invalid cases with
5706   // pointers.  Everything else should be possible.
5707
5708   QualType SrcTy = Src.get()->getType();
5709   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5710     return CK_NoOp;
5711
5712   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5713   case Type::STK_MemberPointer:
5714     llvm_unreachable("member pointer type in C");
5715
5716   case Type::STK_CPointer:
5717   case Type::STK_BlockPointer:
5718   case Type::STK_ObjCObjectPointer:
5719     switch (DestTy->getScalarTypeKind()) {
5720     case Type::STK_CPointer: {
5721       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5722       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5723       if (SrcAS != DestAS)
5724         return CK_AddressSpaceConversion;
5725       return CK_BitCast;
5726     }
5727     case Type::STK_BlockPointer:
5728       return (SrcKind == Type::STK_BlockPointer
5729                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5730     case Type::STK_ObjCObjectPointer:
5731       if (SrcKind == Type::STK_ObjCObjectPointer)
5732         return CK_BitCast;
5733       if (SrcKind == Type::STK_CPointer)
5734         return CK_CPointerToObjCPointerCast;
5735       maybeExtendBlockObject(Src);
5736       return CK_BlockPointerToObjCPointerCast;
5737     case Type::STK_Bool:
5738       return CK_PointerToBoolean;
5739     case Type::STK_Integral:
5740       return CK_PointerToIntegral;
5741     case Type::STK_Floating:
5742     case Type::STK_FloatingComplex:
5743     case Type::STK_IntegralComplex:
5744     case Type::STK_MemberPointer:
5745       llvm_unreachable("illegal cast from pointer");
5746     }
5747     llvm_unreachable("Should have returned before this");
5748
5749   case Type::STK_Bool: // casting from bool is like casting from an integer
5750   case Type::STK_Integral:
5751     switch (DestTy->getScalarTypeKind()) {
5752     case Type::STK_CPointer:
5753     case Type::STK_ObjCObjectPointer:
5754     case Type::STK_BlockPointer:
5755       if (Src.get()->isNullPointerConstant(Context,
5756                                            Expr::NPC_ValueDependentIsNull))
5757         return CK_NullToPointer;
5758       return CK_IntegralToPointer;
5759     case Type::STK_Bool:
5760       return CK_IntegralToBoolean;
5761     case Type::STK_Integral:
5762       return CK_IntegralCast;
5763     case Type::STK_Floating:
5764       return CK_IntegralToFloating;
5765     case Type::STK_IntegralComplex:
5766       Src = ImpCastExprToType(Src.get(),
5767                       DestTy->castAs<ComplexType>()->getElementType(),
5768                       CK_IntegralCast);
5769       return CK_IntegralRealToComplex;
5770     case Type::STK_FloatingComplex:
5771       Src = ImpCastExprToType(Src.get(),
5772                       DestTy->castAs<ComplexType>()->getElementType(),
5773                       CK_IntegralToFloating);
5774       return CK_FloatingRealToComplex;
5775     case Type::STK_MemberPointer:
5776       llvm_unreachable("member pointer type in C");
5777     }
5778     llvm_unreachable("Should have returned before this");
5779
5780   case Type::STK_Floating:
5781     switch (DestTy->getScalarTypeKind()) {
5782     case Type::STK_Floating:
5783       return CK_FloatingCast;
5784     case Type::STK_Bool:
5785       return CK_FloatingToBoolean;
5786     case Type::STK_Integral:
5787       return CK_FloatingToIntegral;
5788     case Type::STK_FloatingComplex:
5789       Src = ImpCastExprToType(Src.get(),
5790                               DestTy->castAs<ComplexType>()->getElementType(),
5791                               CK_FloatingCast);
5792       return CK_FloatingRealToComplex;
5793     case Type::STK_IntegralComplex:
5794       Src = ImpCastExprToType(Src.get(),
5795                               DestTy->castAs<ComplexType>()->getElementType(),
5796                               CK_FloatingToIntegral);
5797       return CK_IntegralRealToComplex;
5798     case Type::STK_CPointer:
5799     case Type::STK_ObjCObjectPointer:
5800     case Type::STK_BlockPointer:
5801       llvm_unreachable("valid float->pointer cast?");
5802     case Type::STK_MemberPointer:
5803       llvm_unreachable("member pointer type in C");
5804     }
5805     llvm_unreachable("Should have returned before this");
5806
5807   case Type::STK_FloatingComplex:
5808     switch (DestTy->getScalarTypeKind()) {
5809     case Type::STK_FloatingComplex:
5810       return CK_FloatingComplexCast;
5811     case Type::STK_IntegralComplex:
5812       return CK_FloatingComplexToIntegralComplex;
5813     case Type::STK_Floating: {
5814       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5815       if (Context.hasSameType(ET, DestTy))
5816         return CK_FloatingComplexToReal;
5817       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5818       return CK_FloatingCast;
5819     }
5820     case Type::STK_Bool:
5821       return CK_FloatingComplexToBoolean;
5822     case Type::STK_Integral:
5823       Src = ImpCastExprToType(Src.get(),
5824                               SrcTy->castAs<ComplexType>()->getElementType(),
5825                               CK_FloatingComplexToReal);
5826       return CK_FloatingToIntegral;
5827     case Type::STK_CPointer:
5828     case Type::STK_ObjCObjectPointer:
5829     case Type::STK_BlockPointer:
5830       llvm_unreachable("valid complex float->pointer cast?");
5831     case Type::STK_MemberPointer:
5832       llvm_unreachable("member pointer type in C");
5833     }
5834     llvm_unreachable("Should have returned before this");
5835
5836   case Type::STK_IntegralComplex:
5837     switch (DestTy->getScalarTypeKind()) {
5838     case Type::STK_FloatingComplex:
5839       return CK_IntegralComplexToFloatingComplex;
5840     case Type::STK_IntegralComplex:
5841       return CK_IntegralComplexCast;
5842     case Type::STK_Integral: {
5843       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5844       if (Context.hasSameType(ET, DestTy))
5845         return CK_IntegralComplexToReal;
5846       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5847       return CK_IntegralCast;
5848     }
5849     case Type::STK_Bool:
5850       return CK_IntegralComplexToBoolean;
5851     case Type::STK_Floating:
5852       Src = ImpCastExprToType(Src.get(),
5853                               SrcTy->castAs<ComplexType>()->getElementType(),
5854                               CK_IntegralComplexToReal);
5855       return CK_IntegralToFloating;
5856     case Type::STK_CPointer:
5857     case Type::STK_ObjCObjectPointer:
5858     case Type::STK_BlockPointer:
5859       llvm_unreachable("valid complex int->pointer cast?");
5860     case Type::STK_MemberPointer:
5861       llvm_unreachable("member pointer type in C");
5862     }
5863     llvm_unreachable("Should have returned before this");
5864   }
5865
5866   llvm_unreachable("Unhandled scalar cast");
5867 }
5868
5869 static bool breakDownVectorType(QualType type, uint64_t &len,
5870                                 QualType &eltType) {
5871   // Vectors are simple.
5872   if (const VectorType *vecType = type->getAs<VectorType>()) {
5873     len = vecType->getNumElements();
5874     eltType = vecType->getElementType();
5875     assert(eltType->isScalarType());
5876     return true;
5877   }
5878   
5879   // We allow lax conversion to and from non-vector types, but only if
5880   // they're real types (i.e. non-complex, non-pointer scalar types).
5881   if (!type->isRealType()) return false;
5882   
5883   len = 1;
5884   eltType = type;
5885   return true;
5886 }
5887
5888 /// Are the two types lax-compatible vector types?  That is, given
5889 /// that one of them is a vector, do they have equal storage sizes,
5890 /// where the storage size is the number of elements times the element
5891 /// size?
5892 ///
5893 /// This will also return false if either of the types is neither a
5894 /// vector nor a real type.
5895 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5896   assert(destTy->isVectorType() || srcTy->isVectorType());
5897   
5898   // Disallow lax conversions between scalars and ExtVectors (these
5899   // conversions are allowed for other vector types because common headers
5900   // depend on them).  Most scalar OP ExtVector cases are handled by the
5901   // splat path anyway, which does what we want (convert, not bitcast).
5902   // What this rules out for ExtVectors is crazy things like char4*float.
5903   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5904   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5905
5906   uint64_t srcLen, destLen;
5907   QualType srcEltTy, destEltTy;
5908   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5909   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5910   
5911   // ASTContext::getTypeSize will return the size rounded up to a
5912   // power of 2, so instead of using that, we need to use the raw
5913   // element size multiplied by the element count.
5914   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5915   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5916   
5917   return (srcLen * srcEltSize == destLen * destEltSize);
5918 }
5919
5920 /// Is this a legal conversion between two types, one of which is
5921 /// known to be a vector type?
5922 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5923   assert(destTy->isVectorType() || srcTy->isVectorType());
5924   
5925   if (!Context.getLangOpts().LaxVectorConversions)
5926     return false;
5927   return areLaxCompatibleVectorTypes(srcTy, destTy);
5928 }
5929
5930 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5931                            CastKind &Kind) {
5932   assert(VectorTy->isVectorType() && "Not a vector type!");
5933
5934   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5935     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5936       return Diag(R.getBegin(),
5937                   Ty->isVectorType() ?
5938                   diag::err_invalid_conversion_between_vectors :
5939                   diag::err_invalid_conversion_between_vector_and_integer)
5940         << VectorTy << Ty << R;
5941   } else
5942     return Diag(R.getBegin(),
5943                 diag::err_invalid_conversion_between_vector_and_scalar)
5944       << VectorTy << Ty << R;
5945
5946   Kind = CK_BitCast;
5947   return false;
5948 }
5949
5950 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5951   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5952
5953   if (DestElemTy == SplattedExpr->getType())
5954     return SplattedExpr;
5955
5956   assert(DestElemTy->isFloatingType() ||
5957          DestElemTy->isIntegralOrEnumerationType());
5958
5959   CastKind CK;
5960   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5961     // OpenCL requires that we convert `true` boolean expressions to -1, but
5962     // only when splatting vectors.
5963     if (DestElemTy->isFloatingType()) {
5964       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5965       // in two steps: boolean to signed integral, then to floating.
5966       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5967                                                  CK_BooleanToSignedIntegral);
5968       SplattedExpr = CastExprRes.get();
5969       CK = CK_IntegralToFloating;
5970     } else {
5971       CK = CK_BooleanToSignedIntegral;
5972     }
5973   } else {
5974     ExprResult CastExprRes = SplattedExpr;
5975     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5976     if (CastExprRes.isInvalid())
5977       return ExprError();
5978     SplattedExpr = CastExprRes.get();
5979   }
5980   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5981 }
5982
5983 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5984                                     Expr *CastExpr, CastKind &Kind) {
5985   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5986
5987   QualType SrcTy = CastExpr->getType();
5988
5989   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5990   // an ExtVectorType.
5991   // In OpenCL, casts between vectors of different types are not allowed.
5992   // (See OpenCL 6.2).
5993   if (SrcTy->isVectorType()) {
5994     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5995         || (getLangOpts().OpenCL &&
5996             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5997       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5998         << DestTy << SrcTy << R;
5999       return ExprError();
6000     }
6001     Kind = CK_BitCast;
6002     return CastExpr;
6003   }
6004
6005   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6006   // conversion will take place first from scalar to elt type, and then
6007   // splat from elt type to vector.
6008   if (SrcTy->isPointerType())
6009     return Diag(R.getBegin(),
6010                 diag::err_invalid_conversion_between_vector_and_scalar)
6011       << DestTy << SrcTy << R;
6012
6013   Kind = CK_VectorSplat;
6014   return prepareVectorSplat(DestTy, CastExpr);
6015 }
6016
6017 ExprResult
6018 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6019                     Declarator &D, ParsedType &Ty,
6020                     SourceLocation RParenLoc, Expr *CastExpr) {
6021   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6022          "ActOnCastExpr(): missing type or expr");
6023
6024   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6025   if (D.isInvalidType())
6026     return ExprError();
6027
6028   if (getLangOpts().CPlusPlus) {
6029     // Check that there are no default arguments (C++ only).
6030     CheckExtraCXXDefaultArguments(D);
6031   } else {
6032     // Make sure any TypoExprs have been dealt with.
6033     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6034     if (!Res.isUsable())
6035       return ExprError();
6036     CastExpr = Res.get();
6037   }
6038
6039   checkUnusedDeclAttributes(D);
6040
6041   QualType castType = castTInfo->getType();
6042   Ty = CreateParsedType(castType, castTInfo);
6043
6044   bool isVectorLiteral = false;
6045
6046   // Check for an altivec or OpenCL literal,
6047   // i.e. all the elements are integer constants.
6048   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6049   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6050   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6051        && castType->isVectorType() && (PE || PLE)) {
6052     if (PLE && PLE->getNumExprs() == 0) {
6053       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6054       return ExprError();
6055     }
6056     if (PE || PLE->getNumExprs() == 1) {
6057       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6058       if (!E->getType()->isVectorType())
6059         isVectorLiteral = true;
6060     }
6061     else
6062       isVectorLiteral = true;
6063   }
6064
6065   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6066   // then handle it as such.
6067   if (isVectorLiteral)
6068     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6069
6070   // If the Expr being casted is a ParenListExpr, handle it specially.
6071   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6072   // sequence of BinOp comma operators.
6073   if (isa<ParenListExpr>(CastExpr)) {
6074     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6075     if (Result.isInvalid()) return ExprError();
6076     CastExpr = Result.get();
6077   }
6078
6079   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6080       !getSourceManager().isInSystemMacro(LParenLoc))
6081     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6082   
6083   CheckTollFreeBridgeCast(castType, CastExpr);
6084   
6085   CheckObjCBridgeRelatedCast(castType, CastExpr);
6086
6087   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6088
6089   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6090 }
6091
6092 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6093                                     SourceLocation RParenLoc, Expr *E,
6094                                     TypeSourceInfo *TInfo) {
6095   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6096          "Expected paren or paren list expression");
6097
6098   Expr **exprs;
6099   unsigned numExprs;
6100   Expr *subExpr;
6101   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6102   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6103     LiteralLParenLoc = PE->getLParenLoc();
6104     LiteralRParenLoc = PE->getRParenLoc();
6105     exprs = PE->getExprs();
6106     numExprs = PE->getNumExprs();
6107   } else { // isa<ParenExpr> by assertion at function entrance
6108     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6109     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6110     subExpr = cast<ParenExpr>(E)->getSubExpr();
6111     exprs = &subExpr;
6112     numExprs = 1;
6113   }
6114
6115   QualType Ty = TInfo->getType();
6116   assert(Ty->isVectorType() && "Expected vector type");
6117
6118   SmallVector<Expr *, 8> initExprs;
6119   const VectorType *VTy = Ty->getAs<VectorType>();
6120   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6121   
6122   // '(...)' form of vector initialization in AltiVec: the number of
6123   // initializers must be one or must match the size of the vector.
6124   // If a single value is specified in the initializer then it will be
6125   // replicated to all the components of the vector
6126   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6127     // The number of initializers must be one or must match the size of the
6128     // vector. If a single value is specified in the initializer then it will
6129     // be replicated to all the components of the vector
6130     if (numExprs == 1) {
6131       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6132       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6133       if (Literal.isInvalid())
6134         return ExprError();
6135       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6136                                   PrepareScalarCast(Literal, ElemTy));
6137       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6138     }
6139     else if (numExprs < numElems) {
6140       Diag(E->getExprLoc(),
6141            diag::err_incorrect_number_of_vector_initializers);
6142       return ExprError();
6143     }
6144     else
6145       initExprs.append(exprs, exprs + numExprs);
6146   }
6147   else {
6148     // For OpenCL, when the number of initializers is a single value,
6149     // it will be replicated to all components of the vector.
6150     if (getLangOpts().OpenCL &&
6151         VTy->getVectorKind() == VectorType::GenericVector &&
6152         numExprs == 1) {
6153         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6154         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6155         if (Literal.isInvalid())
6156           return ExprError();
6157         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6158                                     PrepareScalarCast(Literal, ElemTy));
6159         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6160     }
6161     
6162     initExprs.append(exprs, exprs + numExprs);
6163   }
6164   // FIXME: This means that pretty-printing the final AST will produce curly
6165   // braces instead of the original commas.
6166   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6167                                                    initExprs, LiteralRParenLoc);
6168   initE->setType(Ty);
6169   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6170 }
6171
6172 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6173 /// the ParenListExpr into a sequence of comma binary operators.
6174 ExprResult
6175 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6176   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6177   if (!E)
6178     return OrigExpr;
6179
6180   ExprResult Result(E->getExpr(0));
6181
6182   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6183     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6184                         E->getExpr(i));
6185
6186   if (Result.isInvalid()) return ExprError();
6187
6188   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6189 }
6190
6191 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6192                                     SourceLocation R,
6193                                     MultiExprArg Val) {
6194   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6195   return expr;
6196 }
6197
6198 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6199 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6200 /// emitted.
6201 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6202                                       SourceLocation QuestionLoc) {
6203   Expr *NullExpr = LHSExpr;
6204   Expr *NonPointerExpr = RHSExpr;
6205   Expr::NullPointerConstantKind NullKind =
6206       NullExpr->isNullPointerConstant(Context,
6207                                       Expr::NPC_ValueDependentIsNotNull);
6208
6209   if (NullKind == Expr::NPCK_NotNull) {
6210     NullExpr = RHSExpr;
6211     NonPointerExpr = LHSExpr;
6212     NullKind =
6213         NullExpr->isNullPointerConstant(Context,
6214                                         Expr::NPC_ValueDependentIsNotNull);
6215   }
6216
6217   if (NullKind == Expr::NPCK_NotNull)
6218     return false;
6219
6220   if (NullKind == Expr::NPCK_ZeroExpression)
6221     return false;
6222
6223   if (NullKind == Expr::NPCK_ZeroLiteral) {
6224     // In this case, check to make sure that we got here from a "NULL"
6225     // string in the source code.
6226     NullExpr = NullExpr->IgnoreParenImpCasts();
6227     SourceLocation loc = NullExpr->getExprLoc();
6228     if (!findMacroSpelling(loc, "NULL"))
6229       return false;
6230   }
6231
6232   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6233   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6234       << NonPointerExpr->getType() << DiagType
6235       << NonPointerExpr->getSourceRange();
6236   return true;
6237 }
6238
6239 /// \brief Return false if the condition expression is valid, true otherwise.
6240 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6241   QualType CondTy = Cond->getType();
6242
6243   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6244   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6245     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6246       << CondTy << Cond->getSourceRange();
6247     return true;
6248   }
6249
6250   // C99 6.5.15p2
6251   if (CondTy->isScalarType()) return false;
6252
6253   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6254     << CondTy << Cond->getSourceRange();
6255   return true;
6256 }
6257
6258 /// \brief Handle when one or both operands are void type.
6259 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6260                                          ExprResult &RHS) {
6261     Expr *LHSExpr = LHS.get();
6262     Expr *RHSExpr = RHS.get();
6263
6264     if (!LHSExpr->getType()->isVoidType())
6265       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6266         << RHSExpr->getSourceRange();
6267     if (!RHSExpr->getType()->isVoidType())
6268       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6269         << LHSExpr->getSourceRange();
6270     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6271     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6272     return S.Context.VoidTy;
6273 }
6274
6275 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6276 /// true otherwise.
6277 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6278                                         QualType PointerTy) {
6279   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6280       !NullExpr.get()->isNullPointerConstant(S.Context,
6281                                             Expr::NPC_ValueDependentIsNull))
6282     return true;
6283
6284   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6285   return false;
6286 }
6287
6288 /// \brief Checks compatibility between two pointers and return the resulting
6289 /// type.
6290 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6291                                                      ExprResult &RHS,
6292                                                      SourceLocation Loc) {
6293   QualType LHSTy = LHS.get()->getType();
6294   QualType RHSTy = RHS.get()->getType();
6295
6296   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6297     // Two identical pointers types are always compatible.
6298     return LHSTy;
6299   }
6300
6301   QualType lhptee, rhptee;
6302
6303   // Get the pointee types.
6304   bool IsBlockPointer = false;
6305   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6306     lhptee = LHSBTy->getPointeeType();
6307     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6308     IsBlockPointer = true;
6309   } else {
6310     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6311     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6312   }
6313
6314   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6315   // differently qualified versions of compatible types, the result type is
6316   // a pointer to an appropriately qualified version of the composite
6317   // type.
6318
6319   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6320   // clause doesn't make sense for our extensions. E.g. address space 2 should
6321   // be incompatible with address space 3: they may live on different devices or
6322   // anything.
6323   Qualifiers lhQual = lhptee.getQualifiers();
6324   Qualifiers rhQual = rhptee.getQualifiers();
6325
6326   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6327   lhQual.removeCVRQualifiers();
6328   rhQual.removeCVRQualifiers();
6329
6330   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6331   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6332
6333   // For OpenCL:
6334   // 1. If LHS and RHS types match exactly and:
6335   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6336   //  (b) AS overlap => generate addrspacecast
6337   //  (c) AS don't overlap => give an error
6338   // 2. if LHS and RHS types don't match:
6339   //  (a) AS match => use standard C rules, generate bitcast
6340   //  (b) AS overlap => generate addrspacecast instead of bitcast
6341   //  (c) AS don't overlap => give an error
6342
6343   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6344   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6345
6346   // OpenCL cases 1c, 2a, 2b, and 2c.
6347   if (CompositeTy.isNull()) {
6348     // In this situation, we assume void* type. No especially good
6349     // reason, but this is what gcc does, and we do have to pick
6350     // to get a consistent AST.
6351     QualType incompatTy;
6352     if (S.getLangOpts().OpenCL) {
6353       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6354       // spaces is disallowed.
6355       unsigned ResultAddrSpace;
6356       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6357         // Cases 2a and 2b.
6358         ResultAddrSpace = lhQual.getAddressSpace();
6359       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6360         // Cases 2a and 2b.
6361         ResultAddrSpace = rhQual.getAddressSpace();
6362       } else {
6363         // Cases 1c and 2c.
6364         S.Diag(Loc,
6365                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6366             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6367             << RHS.get()->getSourceRange();
6368         return QualType();
6369       }
6370
6371       // Continue handling cases 2a and 2b.
6372       incompatTy = S.Context.getPointerType(
6373           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6374       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6375                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6376                                     ? CK_AddressSpaceConversion /* 2b */
6377                                     : CK_BitCast /* 2a */);
6378       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6379                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6380                                     ? CK_AddressSpaceConversion /* 2b */
6381                                     : CK_BitCast /* 2a */);
6382     } else {
6383       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6384           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6385           << RHS.get()->getSourceRange();
6386       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6387       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6388       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6389     }
6390     return incompatTy;
6391   }
6392
6393   // The pointer types are compatible.
6394   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6395   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6396   if (IsBlockPointer)
6397     ResultTy = S.Context.getBlockPointerType(ResultTy);
6398   else {
6399     // Cases 1a and 1b for OpenCL.
6400     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6401     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6402                       ? CK_BitCast /* 1a */
6403                       : CK_AddressSpaceConversion /* 1b */;
6404     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6405                       ? CK_BitCast /* 1a */
6406                       : CK_AddressSpaceConversion /* 1b */;
6407     ResultTy = S.Context.getPointerType(ResultTy);
6408   }
6409
6410   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6411   // if the target type does not change.
6412   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6413   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6414   return ResultTy;
6415 }
6416
6417 /// \brief Return the resulting type when the operands are both block pointers.
6418 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6419                                                           ExprResult &LHS,
6420                                                           ExprResult &RHS,
6421                                                           SourceLocation Loc) {
6422   QualType LHSTy = LHS.get()->getType();
6423   QualType RHSTy = RHS.get()->getType();
6424
6425   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6426     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6427       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6428       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6429       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6430       return destType;
6431     }
6432     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6433       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6434       << RHS.get()->getSourceRange();
6435     return QualType();
6436   }
6437
6438   // We have 2 block pointer types.
6439   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6440 }
6441
6442 /// \brief Return the resulting type when the operands are both pointers.
6443 static QualType
6444 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6445                                             ExprResult &RHS,
6446                                             SourceLocation Loc) {
6447   // get the pointer types
6448   QualType LHSTy = LHS.get()->getType();
6449   QualType RHSTy = RHS.get()->getType();
6450
6451   // get the "pointed to" types
6452   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6453   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6454
6455   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6456   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6457     // Figure out necessary qualifiers (C99 6.5.15p6)
6458     QualType destPointee
6459       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6460     QualType destType = S.Context.getPointerType(destPointee);
6461     // Add qualifiers if necessary.
6462     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6463     // Promote to void*.
6464     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6465     return destType;
6466   }
6467   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6468     QualType destPointee
6469       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6470     QualType destType = S.Context.getPointerType(destPointee);
6471     // Add qualifiers if necessary.
6472     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6473     // Promote to void*.
6474     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6475     return destType;
6476   }
6477
6478   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6479 }
6480
6481 /// \brief Return false if the first expression is not an integer and the second
6482 /// expression is not a pointer, true otherwise.
6483 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6484                                         Expr* PointerExpr, SourceLocation Loc,
6485                                         bool IsIntFirstExpr) {
6486   if (!PointerExpr->getType()->isPointerType() ||
6487       !Int.get()->getType()->isIntegerType())
6488     return false;
6489
6490   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6491   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6492
6493   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6494     << Expr1->getType() << Expr2->getType()
6495     << Expr1->getSourceRange() << Expr2->getSourceRange();
6496   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6497                             CK_IntegralToPointer);
6498   return true;
6499 }
6500
6501 /// \brief Simple conversion between integer and floating point types.
6502 ///
6503 /// Used when handling the OpenCL conditional operator where the
6504 /// condition is a vector while the other operands are scalar.
6505 ///
6506 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6507 /// types are either integer or floating type. Between the two
6508 /// operands, the type with the higher rank is defined as the "result
6509 /// type". The other operand needs to be promoted to the same type. No
6510 /// other type promotion is allowed. We cannot use
6511 /// UsualArithmeticConversions() for this purpose, since it always
6512 /// promotes promotable types.
6513 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6514                                             ExprResult &RHS,
6515                                             SourceLocation QuestionLoc) {
6516   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6517   if (LHS.isInvalid())
6518     return QualType();
6519   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6520   if (RHS.isInvalid())
6521     return QualType();
6522
6523   // For conversion purposes, we ignore any qualifiers.
6524   // For example, "const float" and "float" are equivalent.
6525   QualType LHSType =
6526     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6527   QualType RHSType =
6528     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6529
6530   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6531     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6532       << LHSType << LHS.get()->getSourceRange();
6533     return QualType();
6534   }
6535
6536   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6537     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6538       << RHSType << RHS.get()->getSourceRange();
6539     return QualType();
6540   }
6541
6542   // If both types are identical, no conversion is needed.
6543   if (LHSType == RHSType)
6544     return LHSType;
6545
6546   // Now handle "real" floating types (i.e. float, double, long double).
6547   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6548     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6549                                  /*IsCompAssign = */ false);
6550
6551   // Finally, we have two differing integer types.
6552   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6553   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6554 }
6555
6556 /// \brief Convert scalar operands to a vector that matches the
6557 ///        condition in length.
6558 ///
6559 /// Used when handling the OpenCL conditional operator where the
6560 /// condition is a vector while the other operands are scalar.
6561 ///
6562 /// We first compute the "result type" for the scalar operands
6563 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6564 /// into a vector of that type where the length matches the condition
6565 /// vector type. s6.11.6 requires that the element types of the result
6566 /// and the condition must have the same number of bits.
6567 static QualType
6568 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6569                               QualType CondTy, SourceLocation QuestionLoc) {
6570   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6571   if (ResTy.isNull()) return QualType();
6572
6573   const VectorType *CV = CondTy->getAs<VectorType>();
6574   assert(CV);
6575
6576   // Determine the vector result type
6577   unsigned NumElements = CV->getNumElements();
6578   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6579
6580   // Ensure that all types have the same number of bits
6581   if (S.Context.getTypeSize(CV->getElementType())
6582       != S.Context.getTypeSize(ResTy)) {
6583     // Since VectorTy is created internally, it does not pretty print
6584     // with an OpenCL name. Instead, we just print a description.
6585     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6586     SmallString<64> Str;
6587     llvm::raw_svector_ostream OS(Str);
6588     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6589     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6590       << CondTy << OS.str();
6591     return QualType();
6592   }
6593
6594   // Convert operands to the vector result type
6595   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6596   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6597
6598   return VectorTy;
6599 }
6600
6601 /// \brief Return false if this is a valid OpenCL condition vector
6602 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6603                                        SourceLocation QuestionLoc) {
6604   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6605   // integral type.
6606   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6607   assert(CondTy);
6608   QualType EleTy = CondTy->getElementType();
6609   if (EleTy->isIntegerType()) return false;
6610
6611   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6612     << Cond->getType() << Cond->getSourceRange();
6613   return true;
6614 }
6615
6616 /// \brief Return false if the vector condition type and the vector
6617 ///        result type are compatible.
6618 ///
6619 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6620 /// number of elements, and their element types have the same number
6621 /// of bits.
6622 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6623                               SourceLocation QuestionLoc) {
6624   const VectorType *CV = CondTy->getAs<VectorType>();
6625   const VectorType *RV = VecResTy->getAs<VectorType>();
6626   assert(CV && RV);
6627
6628   if (CV->getNumElements() != RV->getNumElements()) {
6629     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6630       << CondTy << VecResTy;
6631     return true;
6632   }
6633
6634   QualType CVE = CV->getElementType();
6635   QualType RVE = RV->getElementType();
6636
6637   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6638     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6639       << CondTy << VecResTy;
6640     return true;
6641   }
6642
6643   return false;
6644 }
6645
6646 /// \brief Return the resulting type for the conditional operator in
6647 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6648 ///        s6.3.i) when the condition is a vector type.
6649 static QualType
6650 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6651                              ExprResult &LHS, ExprResult &RHS,
6652                              SourceLocation QuestionLoc) {
6653   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6654   if (Cond.isInvalid())
6655     return QualType();
6656   QualType CondTy = Cond.get()->getType();
6657
6658   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6659     return QualType();
6660
6661   // If either operand is a vector then find the vector type of the
6662   // result as specified in OpenCL v1.1 s6.3.i.
6663   if (LHS.get()->getType()->isVectorType() ||
6664       RHS.get()->getType()->isVectorType()) {
6665     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6666                                               /*isCompAssign*/false,
6667                                               /*AllowBothBool*/true,
6668                                               /*AllowBoolConversions*/false);
6669     if (VecResTy.isNull()) return QualType();
6670     // The result type must match the condition type as specified in
6671     // OpenCL v1.1 s6.11.6.
6672     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6673       return QualType();
6674     return VecResTy;
6675   }
6676
6677   // Both operands are scalar.
6678   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6679 }
6680
6681 /// \brief Return true if the Expr is block type
6682 static bool checkBlockType(Sema &S, const Expr *E) {
6683   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6684     QualType Ty = CE->getCallee()->getType();
6685     if (Ty->isBlockPointerType()) {
6686       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6687       return true;
6688     }
6689   }
6690   return false;
6691 }
6692
6693 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6694 /// In that case, LHS = cond.
6695 /// C99 6.5.15
6696 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6697                                         ExprResult &RHS, ExprValueKind &VK,
6698                                         ExprObjectKind &OK,
6699                                         SourceLocation QuestionLoc) {
6700
6701   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6702   if (!LHSResult.isUsable()) return QualType();
6703   LHS = LHSResult;
6704
6705   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6706   if (!RHSResult.isUsable()) return QualType();
6707   RHS = RHSResult;
6708
6709   // C++ is sufficiently different to merit its own checker.
6710   if (getLangOpts().CPlusPlus)
6711     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6712
6713   VK = VK_RValue;
6714   OK = OK_Ordinary;
6715
6716   // The OpenCL operator with a vector condition is sufficiently
6717   // different to merit its own checker.
6718   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6719     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6720
6721   // First, check the condition.
6722   Cond = UsualUnaryConversions(Cond.get());
6723   if (Cond.isInvalid())
6724     return QualType();
6725   if (checkCondition(*this, Cond.get(), QuestionLoc))
6726     return QualType();
6727
6728   // Now check the two expressions.
6729   if (LHS.get()->getType()->isVectorType() ||
6730       RHS.get()->getType()->isVectorType())
6731     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6732                                /*AllowBothBool*/true,
6733                                /*AllowBoolConversions*/false);
6734
6735   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6736   if (LHS.isInvalid() || RHS.isInvalid())
6737     return QualType();
6738
6739   QualType LHSTy = LHS.get()->getType();
6740   QualType RHSTy = RHS.get()->getType();
6741
6742   // Diagnose attempts to convert between __float128 and long double where
6743   // such conversions currently can't be handled.
6744   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6745     Diag(QuestionLoc,
6746          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6747       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6748     return QualType();
6749   }
6750
6751   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6752   // selection operator (?:).
6753   if (getLangOpts().OpenCL &&
6754       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6755     return QualType();
6756   }
6757
6758   // If both operands have arithmetic type, do the usual arithmetic conversions
6759   // to find a common type: C99 6.5.15p3,5.
6760   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6761     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6762     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6763
6764     return ResTy;
6765   }
6766
6767   // If both operands are the same structure or union type, the result is that
6768   // type.
6769   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6770     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6771       if (LHSRT->getDecl() == RHSRT->getDecl())
6772         // "If both the operands have structure or union type, the result has
6773         // that type."  This implies that CV qualifiers are dropped.
6774         return LHSTy.getUnqualifiedType();
6775     // FIXME: Type of conditional expression must be complete in C mode.
6776   }
6777
6778   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6779   // The following || allows only one side to be void (a GCC-ism).
6780   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6781     return checkConditionalVoidType(*this, LHS, RHS);
6782   }
6783
6784   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6785   // the type of the other operand."
6786   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6787   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6788
6789   // All objective-c pointer type analysis is done here.
6790   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6791                                                         QuestionLoc);
6792   if (LHS.isInvalid() || RHS.isInvalid())
6793     return QualType();
6794   if (!compositeType.isNull())
6795     return compositeType;
6796
6797
6798   // Handle block pointer types.
6799   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6800     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6801                                                      QuestionLoc);
6802
6803   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6804   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6805     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6806                                                        QuestionLoc);
6807
6808   // GCC compatibility: soften pointer/integer mismatch.  Note that
6809   // null pointers have been filtered out by this point.
6810   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6811       /*isIntFirstExpr=*/true))
6812     return RHSTy;
6813   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6814       /*isIntFirstExpr=*/false))
6815     return LHSTy;
6816
6817   // Emit a better diagnostic if one of the expressions is a null pointer
6818   // constant and the other is not a pointer type. In this case, the user most
6819   // likely forgot to take the address of the other expression.
6820   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6821     return QualType();
6822
6823   // Otherwise, the operands are not compatible.
6824   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6825     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6826     << RHS.get()->getSourceRange();
6827   return QualType();
6828 }
6829
6830 /// FindCompositeObjCPointerType - Helper method to find composite type of
6831 /// two objective-c pointer types of the two input expressions.
6832 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6833                                             SourceLocation QuestionLoc) {
6834   QualType LHSTy = LHS.get()->getType();
6835   QualType RHSTy = RHS.get()->getType();
6836
6837   // Handle things like Class and struct objc_class*.  Here we case the result
6838   // to the pseudo-builtin, because that will be implicitly cast back to the
6839   // redefinition type if an attempt is made to access its fields.
6840   if (LHSTy->isObjCClassType() &&
6841       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6842     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6843     return LHSTy;
6844   }
6845   if (RHSTy->isObjCClassType() &&
6846       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6847     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6848     return RHSTy;
6849   }
6850   // And the same for struct objc_object* / id
6851   if (LHSTy->isObjCIdType() &&
6852       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6853     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6854     return LHSTy;
6855   }
6856   if (RHSTy->isObjCIdType() &&
6857       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6858     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6859     return RHSTy;
6860   }
6861   // And the same for struct objc_selector* / SEL
6862   if (Context.isObjCSelType(LHSTy) &&
6863       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6864     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6865     return LHSTy;
6866   }
6867   if (Context.isObjCSelType(RHSTy) &&
6868       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6869     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6870     return RHSTy;
6871   }
6872   // Check constraints for Objective-C object pointers types.
6873   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6874
6875     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6876       // Two identical object pointer types are always compatible.
6877       return LHSTy;
6878     }
6879     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6880     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6881     QualType compositeType = LHSTy;
6882
6883     // If both operands are interfaces and either operand can be
6884     // assigned to the other, use that type as the composite
6885     // type. This allows
6886     //   xxx ? (A*) a : (B*) b
6887     // where B is a subclass of A.
6888     //
6889     // Additionally, as for assignment, if either type is 'id'
6890     // allow silent coercion. Finally, if the types are
6891     // incompatible then make sure to use 'id' as the composite
6892     // type so the result is acceptable for sending messages to.
6893
6894     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6895     // It could return the composite type.
6896     if (!(compositeType =
6897           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6898       // Nothing more to do.
6899     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6900       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6901     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6902       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6903     } else if ((LHSTy->isObjCQualifiedIdType() ||
6904                 RHSTy->isObjCQualifiedIdType()) &&
6905                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6906       // Need to handle "id<xx>" explicitly.
6907       // GCC allows qualified id and any Objective-C type to devolve to
6908       // id. Currently localizing to here until clear this should be
6909       // part of ObjCQualifiedIdTypesAreCompatible.
6910       compositeType = Context.getObjCIdType();
6911     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6912       compositeType = Context.getObjCIdType();
6913     } else {
6914       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6915       << LHSTy << RHSTy
6916       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6917       QualType incompatTy = Context.getObjCIdType();
6918       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6919       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6920       return incompatTy;
6921     }
6922     // The object pointer types are compatible.
6923     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6924     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6925     return compositeType;
6926   }
6927   // Check Objective-C object pointer types and 'void *'
6928   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6929     if (getLangOpts().ObjCAutoRefCount) {
6930       // ARC forbids the implicit conversion of object pointers to 'void *',
6931       // so these types are not compatible.
6932       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6933           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6934       LHS = RHS = true;
6935       return QualType();
6936     }
6937     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6938     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6939     QualType destPointee
6940     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6941     QualType destType = Context.getPointerType(destPointee);
6942     // Add qualifiers if necessary.
6943     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6944     // Promote to void*.
6945     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6946     return destType;
6947   }
6948   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6949     if (getLangOpts().ObjCAutoRefCount) {
6950       // ARC forbids the implicit conversion of object pointers to 'void *',
6951       // so these types are not compatible.
6952       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6953           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6954       LHS = RHS = true;
6955       return QualType();
6956     }
6957     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6958     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6959     QualType destPointee
6960     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6961     QualType destType = Context.getPointerType(destPointee);
6962     // Add qualifiers if necessary.
6963     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6964     // Promote to void*.
6965     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6966     return destType;
6967   }
6968   return QualType();
6969 }
6970
6971 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6972 /// ParenRange in parentheses.
6973 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6974                                const PartialDiagnostic &Note,
6975                                SourceRange ParenRange) {
6976   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6977   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6978       EndLoc.isValid()) {
6979     Self.Diag(Loc, Note)
6980       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6981       << FixItHint::CreateInsertion(EndLoc, ")");
6982   } else {
6983     // We can't display the parentheses, so just show the bare note.
6984     Self.Diag(Loc, Note) << ParenRange;
6985   }
6986 }
6987
6988 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6989   return BinaryOperator::isAdditiveOp(Opc) ||
6990          BinaryOperator::isMultiplicativeOp(Opc) ||
6991          BinaryOperator::isShiftOp(Opc);
6992 }
6993
6994 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6995 /// expression, either using a built-in or overloaded operator,
6996 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6997 /// expression.
6998 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6999                                    Expr **RHSExprs) {
7000   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7001   E = E->IgnoreImpCasts();
7002   E = E->IgnoreConversionOperator();
7003   E = E->IgnoreImpCasts();
7004
7005   // Built-in binary operator.
7006   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7007     if (IsArithmeticOp(OP->getOpcode())) {
7008       *Opcode = OP->getOpcode();
7009       *RHSExprs = OP->getRHS();
7010       return true;
7011     }
7012   }
7013
7014   // Overloaded operator.
7015   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7016     if (Call->getNumArgs() != 2)
7017       return false;
7018
7019     // Make sure this is really a binary operator that is safe to pass into
7020     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7021     OverloadedOperatorKind OO = Call->getOperator();
7022     if (OO < OO_Plus || OO > OO_Arrow ||
7023         OO == OO_PlusPlus || OO == OO_MinusMinus)
7024       return false;
7025
7026     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7027     if (IsArithmeticOp(OpKind)) {
7028       *Opcode = OpKind;
7029       *RHSExprs = Call->getArg(1);
7030       return true;
7031     }
7032   }
7033
7034   return false;
7035 }
7036
7037 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7038 /// or is a logical expression such as (x==y) which has int type, but is
7039 /// commonly interpreted as boolean.
7040 static bool ExprLooksBoolean(Expr *E) {
7041   E = E->IgnoreParenImpCasts();
7042
7043   if (E->getType()->isBooleanType())
7044     return true;
7045   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7046     return OP->isComparisonOp() || OP->isLogicalOp();
7047   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7048     return OP->getOpcode() == UO_LNot;
7049   if (E->getType()->isPointerType())
7050     return true;
7051
7052   return false;
7053 }
7054
7055 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7056 /// and binary operator are mixed in a way that suggests the programmer assumed
7057 /// the conditional operator has higher precedence, for example:
7058 /// "int x = a + someBinaryCondition ? 1 : 2".
7059 static void DiagnoseConditionalPrecedence(Sema &Self,
7060                                           SourceLocation OpLoc,
7061                                           Expr *Condition,
7062                                           Expr *LHSExpr,
7063                                           Expr *RHSExpr) {
7064   BinaryOperatorKind CondOpcode;
7065   Expr *CondRHS;
7066
7067   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7068     return;
7069   if (!ExprLooksBoolean(CondRHS))
7070     return;
7071
7072   // The condition is an arithmetic binary expression, with a right-
7073   // hand side that looks boolean, so warn.
7074
7075   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7076       << Condition->getSourceRange()
7077       << BinaryOperator::getOpcodeStr(CondOpcode);
7078
7079   SuggestParentheses(Self, OpLoc,
7080     Self.PDiag(diag::note_precedence_silence)
7081       << BinaryOperator::getOpcodeStr(CondOpcode),
7082     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7083
7084   SuggestParentheses(Self, OpLoc,
7085     Self.PDiag(diag::note_precedence_conditional_first),
7086     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7087 }
7088
7089 /// Compute the nullability of a conditional expression.
7090 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7091                                               QualType LHSTy, QualType RHSTy,
7092                                               ASTContext &Ctx) {
7093   if (!ResTy->isAnyPointerType())
7094     return ResTy;
7095
7096   auto GetNullability = [&Ctx](QualType Ty) {
7097     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7098     if (Kind)
7099       return *Kind;
7100     return NullabilityKind::Unspecified;
7101   };
7102
7103   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7104   NullabilityKind MergedKind;
7105
7106   // Compute nullability of a binary conditional expression.
7107   if (IsBin) {
7108     if (LHSKind == NullabilityKind::NonNull)
7109       MergedKind = NullabilityKind::NonNull;
7110     else
7111       MergedKind = RHSKind;
7112   // Compute nullability of a normal conditional expression.
7113   } else {
7114     if (LHSKind == NullabilityKind::Nullable ||
7115         RHSKind == NullabilityKind::Nullable)
7116       MergedKind = NullabilityKind::Nullable;
7117     else if (LHSKind == NullabilityKind::NonNull)
7118       MergedKind = RHSKind;
7119     else if (RHSKind == NullabilityKind::NonNull)
7120       MergedKind = LHSKind;
7121     else
7122       MergedKind = NullabilityKind::Unspecified;
7123   }
7124
7125   // Return if ResTy already has the correct nullability.
7126   if (GetNullability(ResTy) == MergedKind)
7127     return ResTy;
7128
7129   // Strip all nullability from ResTy.
7130   while (ResTy->getNullability(Ctx))
7131     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7132
7133   // Create a new AttributedType with the new nullability kind.
7134   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7135   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7136 }
7137
7138 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7139 /// in the case of a the GNU conditional expr extension.
7140 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7141                                     SourceLocation ColonLoc,
7142                                     Expr *CondExpr, Expr *LHSExpr,
7143                                     Expr *RHSExpr) {
7144   if (!getLangOpts().CPlusPlus) {
7145     // C cannot handle TypoExpr nodes in the condition because it
7146     // doesn't handle dependent types properly, so make sure any TypoExprs have
7147     // been dealt with before checking the operands.
7148     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7149     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7150     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7151
7152     if (!CondResult.isUsable())
7153       return ExprError();
7154
7155     if (LHSExpr) {
7156       if (!LHSResult.isUsable())
7157         return ExprError();
7158     }
7159
7160     if (!RHSResult.isUsable())
7161       return ExprError();
7162
7163     CondExpr = CondResult.get();
7164     LHSExpr = LHSResult.get();
7165     RHSExpr = RHSResult.get();
7166   }
7167
7168   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7169   // was the condition.
7170   OpaqueValueExpr *opaqueValue = nullptr;
7171   Expr *commonExpr = nullptr;
7172   if (!LHSExpr) {
7173     commonExpr = CondExpr;
7174     // Lower out placeholder types first.  This is important so that we don't
7175     // try to capture a placeholder. This happens in few cases in C++; such
7176     // as Objective-C++'s dictionary subscripting syntax.
7177     if (commonExpr->hasPlaceholderType()) {
7178       ExprResult result = CheckPlaceholderExpr(commonExpr);
7179       if (!result.isUsable()) return ExprError();
7180       commonExpr = result.get();
7181     }
7182     // We usually want to apply unary conversions *before* saving, except
7183     // in the special case of a C++ l-value conditional.
7184     if (!(getLangOpts().CPlusPlus
7185           && !commonExpr->isTypeDependent()
7186           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7187           && commonExpr->isGLValue()
7188           && commonExpr->isOrdinaryOrBitFieldObject()
7189           && RHSExpr->isOrdinaryOrBitFieldObject()
7190           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7191       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7192       if (commonRes.isInvalid())
7193         return ExprError();
7194       commonExpr = commonRes.get();
7195     }
7196
7197     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7198                                                 commonExpr->getType(),
7199                                                 commonExpr->getValueKind(),
7200                                                 commonExpr->getObjectKind(),
7201                                                 commonExpr);
7202     LHSExpr = CondExpr = opaqueValue;
7203   }
7204
7205   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7206   ExprValueKind VK = VK_RValue;
7207   ExprObjectKind OK = OK_Ordinary;
7208   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7209   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
7210                                              VK, OK, QuestionLoc);
7211   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7212       RHS.isInvalid())
7213     return ExprError();
7214
7215   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7216                                 RHS.get());
7217
7218   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7219
7220   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7221                                          Context);
7222
7223   if (!commonExpr)
7224     return new (Context)
7225         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7226                             RHS.get(), result, VK, OK);
7227
7228   return new (Context) BinaryConditionalOperator(
7229       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7230       ColonLoc, result, VK, OK);
7231 }
7232
7233 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7234 // being closely modeled after the C99 spec:-). The odd characteristic of this
7235 // routine is it effectively iqnores the qualifiers on the top level pointee.
7236 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7237 // FIXME: add a couple examples in this comment.
7238 static Sema::AssignConvertType
7239 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7240   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7241   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7242
7243   // get the "pointed to" type (ignoring qualifiers at the top level)
7244   const Type *lhptee, *rhptee;
7245   Qualifiers lhq, rhq;
7246   std::tie(lhptee, lhq) =
7247       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7248   std::tie(rhptee, rhq) =
7249       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7250
7251   Sema::AssignConvertType ConvTy = Sema::Compatible;
7252
7253   // C99 6.5.16.1p1: This following citation is common to constraints
7254   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7255   // qualifiers of the type *pointed to* by the right;
7256
7257   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7258   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7259       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7260     // Ignore lifetime for further calculation.
7261     lhq.removeObjCLifetime();
7262     rhq.removeObjCLifetime();
7263   }
7264
7265   if (!lhq.compatiblyIncludes(rhq)) {
7266     // Treat address-space mismatches as fatal.  TODO: address subspaces
7267     if (!lhq.isAddressSpaceSupersetOf(rhq))
7268       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7269
7270     // It's okay to add or remove GC or lifetime qualifiers when converting to
7271     // and from void*.
7272     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7273                         .compatiblyIncludes(
7274                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7275              && (lhptee->isVoidType() || rhptee->isVoidType()))
7276       ; // keep old
7277
7278     // Treat lifetime mismatches as fatal.
7279     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7280       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7281     
7282     // For GCC/MS compatibility, other qualifier mismatches are treated
7283     // as still compatible in C.
7284     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7285   }
7286
7287   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7288   // incomplete type and the other is a pointer to a qualified or unqualified
7289   // version of void...
7290   if (lhptee->isVoidType()) {
7291     if (rhptee->isIncompleteOrObjectType())
7292       return ConvTy;
7293
7294     // As an extension, we allow cast to/from void* to function pointer.
7295     assert(rhptee->isFunctionType());
7296     return Sema::FunctionVoidPointer;
7297   }
7298
7299   if (rhptee->isVoidType()) {
7300     if (lhptee->isIncompleteOrObjectType())
7301       return ConvTy;
7302
7303     // As an extension, we allow cast to/from void* to function pointer.
7304     assert(lhptee->isFunctionType());
7305     return Sema::FunctionVoidPointer;
7306   }
7307
7308   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7309   // unqualified versions of compatible types, ...
7310   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7311   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7312     // Check if the pointee types are compatible ignoring the sign.
7313     // We explicitly check for char so that we catch "char" vs
7314     // "unsigned char" on systems where "char" is unsigned.
7315     if (lhptee->isCharType())
7316       ltrans = S.Context.UnsignedCharTy;
7317     else if (lhptee->hasSignedIntegerRepresentation())
7318       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7319
7320     if (rhptee->isCharType())
7321       rtrans = S.Context.UnsignedCharTy;
7322     else if (rhptee->hasSignedIntegerRepresentation())
7323       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7324
7325     if (ltrans == rtrans) {
7326       // Types are compatible ignoring the sign. Qualifier incompatibility
7327       // takes priority over sign incompatibility because the sign
7328       // warning can be disabled.
7329       if (ConvTy != Sema::Compatible)
7330         return ConvTy;
7331
7332       return Sema::IncompatiblePointerSign;
7333     }
7334
7335     // If we are a multi-level pointer, it's possible that our issue is simply
7336     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7337     // the eventual target type is the same and the pointers have the same
7338     // level of indirection, this must be the issue.
7339     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7340       do {
7341         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7342         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7343       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7344
7345       if (lhptee == rhptee)
7346         return Sema::IncompatibleNestedPointerQualifiers;
7347     }
7348
7349     // General pointer incompatibility takes priority over qualifiers.
7350     return Sema::IncompatiblePointer;
7351   }
7352   if (!S.getLangOpts().CPlusPlus &&
7353       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7354     return Sema::IncompatiblePointer;
7355   return ConvTy;
7356 }
7357
7358 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7359 /// block pointer types are compatible or whether a block and normal pointer
7360 /// are compatible. It is more restrict than comparing two function pointer
7361 // types.
7362 static Sema::AssignConvertType
7363 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7364                                     QualType RHSType) {
7365   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7366   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7367
7368   QualType lhptee, rhptee;
7369
7370   // get the "pointed to" type (ignoring qualifiers at the top level)
7371   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7372   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7373
7374   // In C++, the types have to match exactly.
7375   if (S.getLangOpts().CPlusPlus)
7376     return Sema::IncompatibleBlockPointer;
7377
7378   Sema::AssignConvertType ConvTy = Sema::Compatible;
7379
7380   // For blocks we enforce that qualifiers are identical.
7381   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7382     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7383
7384   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7385     return Sema::IncompatibleBlockPointer;
7386
7387   return ConvTy;
7388 }
7389
7390 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7391 /// for assignment compatibility.
7392 static Sema::AssignConvertType
7393 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7394                                    QualType RHSType) {
7395   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7396   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7397
7398   if (LHSType->isObjCBuiltinType()) {
7399     // Class is not compatible with ObjC object pointers.
7400     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7401         !RHSType->isObjCQualifiedClassType())
7402       return Sema::IncompatiblePointer;
7403     return Sema::Compatible;
7404   }
7405   if (RHSType->isObjCBuiltinType()) {
7406     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7407         !LHSType->isObjCQualifiedClassType())
7408       return Sema::IncompatiblePointer;
7409     return Sema::Compatible;
7410   }
7411   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7412   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7413
7414   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7415       // make an exception for id<P>
7416       !LHSType->isObjCQualifiedIdType())
7417     return Sema::CompatiblePointerDiscardsQualifiers;
7418
7419   if (S.Context.typesAreCompatible(LHSType, RHSType))
7420     return Sema::Compatible;
7421   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7422     return Sema::IncompatibleObjCQualifiedId;
7423   return Sema::IncompatiblePointer;
7424 }
7425
7426 Sema::AssignConvertType
7427 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7428                                  QualType LHSType, QualType RHSType) {
7429   // Fake up an opaque expression.  We don't actually care about what
7430   // cast operations are required, so if CheckAssignmentConstraints
7431   // adds casts to this they'll be wasted, but fortunately that doesn't
7432   // usually happen on valid code.
7433   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7434   ExprResult RHSPtr = &RHSExpr;
7435   CastKind K = CK_Invalid;
7436
7437   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7438 }
7439
7440 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7441 /// has code to accommodate several GCC extensions when type checking
7442 /// pointers. Here are some objectionable examples that GCC considers warnings:
7443 ///
7444 ///  int a, *pint;
7445 ///  short *pshort;
7446 ///  struct foo *pfoo;
7447 ///
7448 ///  pint = pshort; // warning: assignment from incompatible pointer type
7449 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7450 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7451 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7452 ///
7453 /// As a result, the code for dealing with pointers is more complex than the
7454 /// C99 spec dictates.
7455 ///
7456 /// Sets 'Kind' for any result kind except Incompatible.
7457 Sema::AssignConvertType
7458 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7459                                  CastKind &Kind, bool ConvertRHS) {
7460   QualType RHSType = RHS.get()->getType();
7461   QualType OrigLHSType = LHSType;
7462
7463   // Get canonical types.  We're not formatting these types, just comparing
7464   // them.
7465   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7466   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7467
7468   // Common case: no conversion required.
7469   if (LHSType == RHSType) {
7470     Kind = CK_NoOp;
7471     return Compatible;
7472   }
7473
7474   // If we have an atomic type, try a non-atomic assignment, then just add an
7475   // atomic qualification step.
7476   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7477     Sema::AssignConvertType result =
7478       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7479     if (result != Compatible)
7480       return result;
7481     if (Kind != CK_NoOp && ConvertRHS)
7482       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7483     Kind = CK_NonAtomicToAtomic;
7484     return Compatible;
7485   }
7486
7487   // If the left-hand side is a reference type, then we are in a
7488   // (rare!) case where we've allowed the use of references in C,
7489   // e.g., as a parameter type in a built-in function. In this case,
7490   // just make sure that the type referenced is compatible with the
7491   // right-hand side type. The caller is responsible for adjusting
7492   // LHSType so that the resulting expression does not have reference
7493   // type.
7494   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7495     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7496       Kind = CK_LValueBitCast;
7497       return Compatible;
7498     }
7499     return Incompatible;
7500   }
7501
7502   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7503   // to the same ExtVector type.
7504   if (LHSType->isExtVectorType()) {
7505     if (RHSType->isExtVectorType())
7506       return Incompatible;
7507     if (RHSType->isArithmeticType()) {
7508       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7509       if (ConvertRHS)
7510         RHS = prepareVectorSplat(LHSType, RHS.get());
7511       Kind = CK_VectorSplat;
7512       return Compatible;
7513     }
7514   }
7515
7516   // Conversions to or from vector type.
7517   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7518     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7519       // Allow assignments of an AltiVec vector type to an equivalent GCC
7520       // vector type and vice versa
7521       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7522         Kind = CK_BitCast;
7523         return Compatible;
7524       }
7525
7526       // If we are allowing lax vector conversions, and LHS and RHS are both
7527       // vectors, the total size only needs to be the same. This is a bitcast;
7528       // no bits are changed but the result type is different.
7529       if (isLaxVectorConversion(RHSType, LHSType)) {
7530         Kind = CK_BitCast;
7531         return IncompatibleVectors;
7532       }
7533     }
7534
7535     // When the RHS comes from another lax conversion (e.g. binops between
7536     // scalars and vectors) the result is canonicalized as a vector. When the
7537     // LHS is also a vector, the lax is allowed by the condition above. Handle
7538     // the case where LHS is a scalar.
7539     if (LHSType->isScalarType()) {
7540       const VectorType *VecType = RHSType->getAs<VectorType>();
7541       if (VecType && VecType->getNumElements() == 1 &&
7542           isLaxVectorConversion(RHSType, LHSType)) {
7543         ExprResult *VecExpr = &RHS;
7544         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7545         Kind = CK_BitCast;
7546         return Compatible;
7547       }
7548     }
7549
7550     return Incompatible;
7551   }
7552
7553   // Diagnose attempts to convert between __float128 and long double where
7554   // such conversions currently can't be handled.
7555   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7556     return Incompatible;
7557
7558   // Arithmetic conversions.
7559   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7560       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7561     if (ConvertRHS)
7562       Kind = PrepareScalarCast(RHS, LHSType);
7563     return Compatible;
7564   }
7565
7566   // Conversions to normal pointers.
7567   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7568     // U* -> T*
7569     if (isa<PointerType>(RHSType)) {
7570       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7571       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7572       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7573       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7574     }
7575
7576     // int -> T*
7577     if (RHSType->isIntegerType()) {
7578       Kind = CK_IntegralToPointer; // FIXME: null?
7579       return IntToPointer;
7580     }
7581
7582     // C pointers are not compatible with ObjC object pointers,
7583     // with two exceptions:
7584     if (isa<ObjCObjectPointerType>(RHSType)) {
7585       //  - conversions to void*
7586       if (LHSPointer->getPointeeType()->isVoidType()) {
7587         Kind = CK_BitCast;
7588         return Compatible;
7589       }
7590
7591       //  - conversions from 'Class' to the redefinition type
7592       if (RHSType->isObjCClassType() &&
7593           Context.hasSameType(LHSType, 
7594                               Context.getObjCClassRedefinitionType())) {
7595         Kind = CK_BitCast;
7596         return Compatible;
7597       }
7598
7599       Kind = CK_BitCast;
7600       return IncompatiblePointer;
7601     }
7602
7603     // U^ -> void*
7604     if (RHSType->getAs<BlockPointerType>()) {
7605       if (LHSPointer->getPointeeType()->isVoidType()) {
7606         Kind = CK_BitCast;
7607         return Compatible;
7608       }
7609     }
7610
7611     return Incompatible;
7612   }
7613
7614   // Conversions to block pointers.
7615   if (isa<BlockPointerType>(LHSType)) {
7616     // U^ -> T^
7617     if (RHSType->isBlockPointerType()) {
7618       Kind = CK_BitCast;
7619       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7620     }
7621
7622     // int or null -> T^
7623     if (RHSType->isIntegerType()) {
7624       Kind = CK_IntegralToPointer; // FIXME: null
7625       return IntToBlockPointer;
7626     }
7627
7628     // id -> T^
7629     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7630       Kind = CK_AnyPointerToBlockPointerCast;
7631       return Compatible;
7632     }
7633
7634     // void* -> T^
7635     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7636       if (RHSPT->getPointeeType()->isVoidType()) {
7637         Kind = CK_AnyPointerToBlockPointerCast;
7638         return Compatible;
7639       }
7640
7641     return Incompatible;
7642   }
7643
7644   // Conversions to Objective-C pointers.
7645   if (isa<ObjCObjectPointerType>(LHSType)) {
7646     // A* -> B*
7647     if (RHSType->isObjCObjectPointerType()) {
7648       Kind = CK_BitCast;
7649       Sema::AssignConvertType result = 
7650         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7651       if (getLangOpts().ObjCAutoRefCount &&
7652           result == Compatible && 
7653           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7654         result = IncompatibleObjCWeakRef;
7655       return result;
7656     }
7657
7658     // int or null -> A*
7659     if (RHSType->isIntegerType()) {
7660       Kind = CK_IntegralToPointer; // FIXME: null
7661       return IntToPointer;
7662     }
7663
7664     // In general, C pointers are not compatible with ObjC object pointers,
7665     // with two exceptions:
7666     if (isa<PointerType>(RHSType)) {
7667       Kind = CK_CPointerToObjCPointerCast;
7668
7669       //  - conversions from 'void*'
7670       if (RHSType->isVoidPointerType()) {
7671         return Compatible;
7672       }
7673
7674       //  - conversions to 'Class' from its redefinition type
7675       if (LHSType->isObjCClassType() &&
7676           Context.hasSameType(RHSType, 
7677                               Context.getObjCClassRedefinitionType())) {
7678         return Compatible;
7679       }
7680
7681       return IncompatiblePointer;
7682     }
7683
7684     // Only under strict condition T^ is compatible with an Objective-C pointer.
7685     if (RHSType->isBlockPointerType() && 
7686         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7687       if (ConvertRHS)
7688         maybeExtendBlockObject(RHS);
7689       Kind = CK_BlockPointerToObjCPointerCast;
7690       return Compatible;
7691     }
7692
7693     return Incompatible;
7694   }
7695
7696   // Conversions from pointers that are not covered by the above.
7697   if (isa<PointerType>(RHSType)) {
7698     // T* -> _Bool
7699     if (LHSType == Context.BoolTy) {
7700       Kind = CK_PointerToBoolean;
7701       return Compatible;
7702     }
7703
7704     // T* -> int
7705     if (LHSType->isIntegerType()) {
7706       Kind = CK_PointerToIntegral;
7707       return PointerToInt;
7708     }
7709
7710     return Incompatible;
7711   }
7712
7713   // Conversions from Objective-C pointers that are not covered by the above.
7714   if (isa<ObjCObjectPointerType>(RHSType)) {
7715     // T* -> _Bool
7716     if (LHSType == Context.BoolTy) {
7717       Kind = CK_PointerToBoolean;
7718       return Compatible;
7719     }
7720
7721     // T* -> int
7722     if (LHSType->isIntegerType()) {
7723       Kind = CK_PointerToIntegral;
7724       return PointerToInt;
7725     }
7726
7727     return Incompatible;
7728   }
7729
7730   // struct A -> struct B
7731   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7732     if (Context.typesAreCompatible(LHSType, RHSType)) {
7733       Kind = CK_NoOp;
7734       return Compatible;
7735     }
7736   }
7737
7738   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7739     Kind = CK_IntToOCLSampler;
7740     return Compatible;
7741   }
7742
7743   return Incompatible;
7744 }
7745
7746 /// \brief Constructs a transparent union from an expression that is
7747 /// used to initialize the transparent union.
7748 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7749                                       ExprResult &EResult, QualType UnionType,
7750                                       FieldDecl *Field) {
7751   // Build an initializer list that designates the appropriate member
7752   // of the transparent union.
7753   Expr *E = EResult.get();
7754   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7755                                                    E, SourceLocation());
7756   Initializer->setType(UnionType);
7757   Initializer->setInitializedFieldInUnion(Field);
7758
7759   // Build a compound literal constructing a value of the transparent
7760   // union type from this initializer list.
7761   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7762   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7763                                         VK_RValue, Initializer, false);
7764 }
7765
7766 Sema::AssignConvertType
7767 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7768                                                ExprResult &RHS) {
7769   QualType RHSType = RHS.get()->getType();
7770
7771   // If the ArgType is a Union type, we want to handle a potential
7772   // transparent_union GCC extension.
7773   const RecordType *UT = ArgType->getAsUnionType();
7774   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7775     return Incompatible;
7776
7777   // The field to initialize within the transparent union.
7778   RecordDecl *UD = UT->getDecl();
7779   FieldDecl *InitField = nullptr;
7780   // It's compatible if the expression matches any of the fields.
7781   for (auto *it : UD->fields()) {
7782     if (it->getType()->isPointerType()) {
7783       // If the transparent union contains a pointer type, we allow:
7784       // 1) void pointer
7785       // 2) null pointer constant
7786       if (RHSType->isPointerType())
7787         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7788           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7789           InitField = it;
7790           break;
7791         }
7792
7793       if (RHS.get()->isNullPointerConstant(Context,
7794                                            Expr::NPC_ValueDependentIsNull)) {
7795         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7796                                 CK_NullToPointer);
7797         InitField = it;
7798         break;
7799       }
7800     }
7801
7802     CastKind Kind = CK_Invalid;
7803     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7804           == Compatible) {
7805       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7806       InitField = it;
7807       break;
7808     }
7809   }
7810
7811   if (!InitField)
7812     return Incompatible;
7813
7814   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7815   return Compatible;
7816 }
7817
7818 Sema::AssignConvertType
7819 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7820                                        bool Diagnose,
7821                                        bool DiagnoseCFAudited,
7822                                        bool ConvertRHS) {
7823   // We need to be able to tell the caller whether we diagnosed a problem, if
7824   // they ask us to issue diagnostics.
7825   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7826
7827   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7828   // we can't avoid *all* modifications at the moment, so we need some somewhere
7829   // to put the updated value.
7830   ExprResult LocalRHS = CallerRHS;
7831   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7832
7833   if (getLangOpts().CPlusPlus) {
7834     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7835       // C++ 5.17p3: If the left operand is not of class type, the
7836       // expression is implicitly converted (C++ 4) to the
7837       // cv-unqualified type of the left operand.
7838       QualType RHSType = RHS.get()->getType();
7839       if (Diagnose) {
7840         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7841                                         AA_Assigning);
7842       } else {
7843         ImplicitConversionSequence ICS =
7844             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7845                                   /*SuppressUserConversions=*/false,
7846                                   /*AllowExplicit=*/false,
7847                                   /*InOverloadResolution=*/false,
7848                                   /*CStyle=*/false,
7849                                   /*AllowObjCWritebackConversion=*/false);
7850         if (ICS.isFailure())
7851           return Incompatible;
7852         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7853                                         ICS, AA_Assigning);
7854       }
7855       if (RHS.isInvalid())
7856         return Incompatible;
7857       Sema::AssignConvertType result = Compatible;
7858       if (getLangOpts().ObjCAutoRefCount &&
7859           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7860         result = IncompatibleObjCWeakRef;
7861       return result;
7862     }
7863
7864     // FIXME: Currently, we fall through and treat C++ classes like C
7865     // structures.
7866     // FIXME: We also fall through for atomics; not sure what should
7867     // happen there, though.
7868   } else if (RHS.get()->getType() == Context.OverloadTy) {
7869     // As a set of extensions to C, we support overloading on functions. These
7870     // functions need to be resolved here.
7871     DeclAccessPair DAP;
7872     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7873             RHS.get(), LHSType, /*Complain=*/false, DAP))
7874       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7875     else
7876       return Incompatible;
7877   }
7878
7879   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7880   // a null pointer constant.
7881   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7882        LHSType->isBlockPointerType()) &&
7883       RHS.get()->isNullPointerConstant(Context,
7884                                        Expr::NPC_ValueDependentIsNull)) {
7885     if (Diagnose || ConvertRHS) {
7886       CastKind Kind;
7887       CXXCastPath Path;
7888       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7889                              /*IgnoreBaseAccess=*/false, Diagnose);
7890       if (ConvertRHS)
7891         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7892     }
7893     return Compatible;
7894   }
7895
7896   // This check seems unnatural, however it is necessary to ensure the proper
7897   // conversion of functions/arrays. If the conversion were done for all
7898   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7899   // expressions that suppress this implicit conversion (&, sizeof).
7900   //
7901   // Suppress this for references: C++ 8.5.3p5.
7902   if (!LHSType->isReferenceType()) {
7903     // FIXME: We potentially allocate here even if ConvertRHS is false.
7904     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7905     if (RHS.isInvalid())
7906       return Incompatible;
7907   }
7908
7909   Expr *PRE = RHS.get()->IgnoreParenCasts();
7910   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7911     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7912     if (PDecl && !PDecl->hasDefinition()) {
7913       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7914       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7915     }
7916   }
7917   
7918   CastKind Kind = CK_Invalid;
7919   Sema::AssignConvertType result =
7920     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7921
7922   // C99 6.5.16.1p2: The value of the right operand is converted to the
7923   // type of the assignment expression.
7924   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7925   // so that we can use references in built-in functions even in C.
7926   // The getNonReferenceType() call makes sure that the resulting expression
7927   // does not have reference type.
7928   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7929     QualType Ty = LHSType.getNonLValueExprType(Context);
7930     Expr *E = RHS.get();
7931
7932     // Check for various Objective-C errors. If we are not reporting
7933     // diagnostics and just checking for errors, e.g., during overload
7934     // resolution, return Incompatible to indicate the failure.
7935     if (getLangOpts().ObjCAutoRefCount &&
7936         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7937                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7938       if (!Diagnose)
7939         return Incompatible;
7940     }
7941     if (getLangOpts().ObjC1 &&
7942         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7943                                            E->getType(), E, Diagnose) ||
7944          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7945       if (!Diagnose)
7946         return Incompatible;
7947       // Replace the expression with a corrected version and continue so we
7948       // can find further errors.
7949       RHS = E;
7950       return Compatible;
7951     }
7952     
7953     if (ConvertRHS)
7954       RHS = ImpCastExprToType(E, Ty, Kind);
7955   }
7956   return result;
7957 }
7958
7959 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7960                                ExprResult &RHS) {
7961   Diag(Loc, diag::err_typecheck_invalid_operands)
7962     << LHS.get()->getType() << RHS.get()->getType()
7963     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7964   return QualType();
7965 }
7966
7967 /// Try to convert a value of non-vector type to a vector type by converting
7968 /// the type to the element type of the vector and then performing a splat.
7969 /// If the language is OpenCL, we only use conversions that promote scalar
7970 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7971 /// for float->int.
7972 ///
7973 /// \param scalar - if non-null, actually perform the conversions
7974 /// \return true if the operation fails (but without diagnosing the failure)
7975 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7976                                      QualType scalarTy,
7977                                      QualType vectorEltTy,
7978                                      QualType vectorTy) {
7979   // The conversion to apply to the scalar before splatting it,
7980   // if necessary.
7981   CastKind scalarCast = CK_Invalid;
7982   
7983   if (vectorEltTy->isIntegralType(S.Context)) {
7984     if (!scalarTy->isIntegralType(S.Context))
7985       return true;
7986     if (S.getLangOpts().OpenCL &&
7987         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7988       return true;
7989     scalarCast = CK_IntegralCast;
7990   } else if (vectorEltTy->isRealFloatingType()) {
7991     if (scalarTy->isRealFloatingType()) {
7992       if (S.getLangOpts().OpenCL &&
7993           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7994         return true;
7995       scalarCast = CK_FloatingCast;
7996     }
7997     else if (scalarTy->isIntegralType(S.Context))
7998       scalarCast = CK_IntegralToFloating;
7999     else
8000       return true;
8001   } else {
8002     return true;
8003   }
8004
8005   // Adjust scalar if desired.
8006   if (scalar) {
8007     if (scalarCast != CK_Invalid)
8008       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8009     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8010   }
8011   return false;
8012 }
8013
8014 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8015                                    SourceLocation Loc, bool IsCompAssign,
8016                                    bool AllowBothBool,
8017                                    bool AllowBoolConversions) {
8018   if (!IsCompAssign) {
8019     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8020     if (LHS.isInvalid())
8021       return QualType();
8022   }
8023   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8024   if (RHS.isInvalid())
8025     return QualType();
8026
8027   // For conversion purposes, we ignore any qualifiers.
8028   // For example, "const float" and "float" are equivalent.
8029   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8030   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8031
8032   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8033   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8034   assert(LHSVecType || RHSVecType);
8035
8036   // AltiVec-style "vector bool op vector bool" combinations are allowed
8037   // for some operators but not others.
8038   if (!AllowBothBool &&
8039       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8040       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8041     return InvalidOperands(Loc, LHS, RHS);
8042
8043   // If the vector types are identical, return.
8044   if (Context.hasSameType(LHSType, RHSType))
8045     return LHSType;
8046
8047   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8048   if (LHSVecType && RHSVecType &&
8049       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8050     if (isa<ExtVectorType>(LHSVecType)) {
8051       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8052       return LHSType;
8053     }
8054
8055     if (!IsCompAssign)
8056       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8057     return RHSType;
8058   }
8059
8060   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8061   // can be mixed, with the result being the non-bool type.  The non-bool
8062   // operand must have integer element type.
8063   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8064       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8065       (Context.getTypeSize(LHSVecType->getElementType()) ==
8066        Context.getTypeSize(RHSVecType->getElementType()))) {
8067     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8068         LHSVecType->getElementType()->isIntegerType() &&
8069         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8070       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8071       return LHSType;
8072     }
8073     if (!IsCompAssign &&
8074         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8075         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8076         RHSVecType->getElementType()->isIntegerType()) {
8077       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8078       return RHSType;
8079     }
8080   }
8081
8082   // If there's an ext-vector type and a scalar, try to convert the scalar to
8083   // the vector element type and splat.
8084   // FIXME: this should also work for regular vector types as supported in GCC.
8085   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8086     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8087                                   LHSVecType->getElementType(), LHSType))
8088       return LHSType;
8089   }
8090   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8091     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8092                                   LHSType, RHSVecType->getElementType(),
8093                                   RHSType))
8094       return RHSType;
8095   }
8096
8097   // FIXME: The code below also handles convertion between vectors and
8098   // non-scalars, we should break this down into fine grained specific checks
8099   // and emit proper diagnostics.
8100   QualType VecType = LHSVecType ? LHSType : RHSType;
8101   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8102   QualType OtherType = LHSVecType ? RHSType : LHSType;
8103   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8104   if (isLaxVectorConversion(OtherType, VecType)) {
8105     // If we're allowing lax vector conversions, only the total (data) size
8106     // needs to be the same. For non compound assignment, if one of the types is
8107     // scalar, the result is always the vector type.
8108     if (!IsCompAssign) {
8109       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8110       return VecType;
8111     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8112     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8113     // type. Note that this is already done by non-compound assignments in
8114     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8115     // <1 x T> -> T. The result is also a vector type.
8116     } else if (OtherType->isExtVectorType() ||
8117                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8118       ExprResult *RHSExpr = &RHS;
8119       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8120       return VecType;
8121     }
8122   }
8123
8124   // Okay, the expression is invalid.
8125
8126   // If there's a non-vector, non-real operand, diagnose that.
8127   if ((!RHSVecType && !RHSType->isRealType()) ||
8128       (!LHSVecType && !LHSType->isRealType())) {
8129     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8130       << LHSType << RHSType
8131       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8132     return QualType();
8133   }
8134
8135   // OpenCL V1.1 6.2.6.p1:
8136   // If the operands are of more than one vector type, then an error shall
8137   // occur. Implicit conversions between vector types are not permitted, per
8138   // section 6.2.1.
8139   if (getLangOpts().OpenCL &&
8140       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8141       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8142     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8143                                                            << RHSType;
8144     return QualType();
8145   }
8146
8147   // Otherwise, use the generic diagnostic.
8148   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8149     << LHSType << RHSType
8150     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8151   return QualType();
8152 }
8153
8154 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8155 // expression.  These are mainly cases where the null pointer is used as an
8156 // integer instead of a pointer.
8157 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8158                                 SourceLocation Loc, bool IsCompare) {
8159   // The canonical way to check for a GNU null is with isNullPointerConstant,
8160   // but we use a bit of a hack here for speed; this is a relatively
8161   // hot path, and isNullPointerConstant is slow.
8162   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8163   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8164
8165   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8166
8167   // Avoid analyzing cases where the result will either be invalid (and
8168   // diagnosed as such) or entirely valid and not something to warn about.
8169   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8170       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8171     return;
8172
8173   // Comparison operations would not make sense with a null pointer no matter
8174   // what the other expression is.
8175   if (!IsCompare) {
8176     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8177         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8178         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8179     return;
8180   }
8181
8182   // The rest of the operations only make sense with a null pointer
8183   // if the other expression is a pointer.
8184   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8185       NonNullType->canDecayToPointerType())
8186     return;
8187
8188   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8189       << LHSNull /* LHS is NULL */ << NonNullType
8190       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8191 }
8192
8193 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8194                                                ExprResult &RHS,
8195                                                SourceLocation Loc, bool IsDiv) {
8196   // Check for division/remainder by zero.
8197   llvm::APSInt RHSValue;
8198   if (!RHS.get()->isValueDependent() &&
8199       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8200     S.DiagRuntimeBehavior(Loc, RHS.get(),
8201                           S.PDiag(diag::warn_remainder_division_by_zero)
8202                             << IsDiv << RHS.get()->getSourceRange());
8203 }
8204
8205 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8206                                            SourceLocation Loc,
8207                                            bool IsCompAssign, bool IsDiv) {
8208   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8209
8210   if (LHS.get()->getType()->isVectorType() ||
8211       RHS.get()->getType()->isVectorType())
8212     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8213                                /*AllowBothBool*/getLangOpts().AltiVec,
8214                                /*AllowBoolConversions*/false);
8215
8216   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8217   if (LHS.isInvalid() || RHS.isInvalid())
8218     return QualType();
8219
8220
8221   if (compType.isNull() || !compType->isArithmeticType())
8222     return InvalidOperands(Loc, LHS, RHS);
8223   if (IsDiv)
8224     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8225   return compType;
8226 }
8227
8228 QualType Sema::CheckRemainderOperands(
8229   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8230   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8231
8232   if (LHS.get()->getType()->isVectorType() ||
8233       RHS.get()->getType()->isVectorType()) {
8234     if (LHS.get()->getType()->hasIntegerRepresentation() && 
8235         RHS.get()->getType()->hasIntegerRepresentation())
8236       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8237                                  /*AllowBothBool*/getLangOpts().AltiVec,
8238                                  /*AllowBoolConversions*/false);
8239     return InvalidOperands(Loc, LHS, RHS);
8240   }
8241
8242   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8243   if (LHS.isInvalid() || RHS.isInvalid())
8244     return QualType();
8245
8246   if (compType.isNull() || !compType->isIntegerType())
8247     return InvalidOperands(Loc, LHS, RHS);
8248   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8249   return compType;
8250 }
8251
8252 /// \brief Diagnose invalid arithmetic on two void pointers.
8253 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8254                                                 Expr *LHSExpr, Expr *RHSExpr) {
8255   S.Diag(Loc, S.getLangOpts().CPlusPlus
8256                 ? diag::err_typecheck_pointer_arith_void_type
8257                 : diag::ext_gnu_void_ptr)
8258     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8259                             << RHSExpr->getSourceRange();
8260 }
8261
8262 /// \brief Diagnose invalid arithmetic on a void pointer.
8263 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8264                                             Expr *Pointer) {
8265   S.Diag(Loc, S.getLangOpts().CPlusPlus
8266                 ? diag::err_typecheck_pointer_arith_void_type
8267                 : diag::ext_gnu_void_ptr)
8268     << 0 /* one pointer */ << Pointer->getSourceRange();
8269 }
8270
8271 /// \brief Diagnose invalid arithmetic on two function pointers.
8272 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8273                                                     Expr *LHS, Expr *RHS) {
8274   assert(LHS->getType()->isAnyPointerType());
8275   assert(RHS->getType()->isAnyPointerType());
8276   S.Diag(Loc, S.getLangOpts().CPlusPlus
8277                 ? diag::err_typecheck_pointer_arith_function_type
8278                 : diag::ext_gnu_ptr_func_arith)
8279     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8280     // We only show the second type if it differs from the first.
8281     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8282                                                    RHS->getType())
8283     << RHS->getType()->getPointeeType()
8284     << LHS->getSourceRange() << RHS->getSourceRange();
8285 }
8286
8287 /// \brief Diagnose invalid arithmetic on a function pointer.
8288 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8289                                                 Expr *Pointer) {
8290   assert(Pointer->getType()->isAnyPointerType());
8291   S.Diag(Loc, S.getLangOpts().CPlusPlus
8292                 ? diag::err_typecheck_pointer_arith_function_type
8293                 : diag::ext_gnu_ptr_func_arith)
8294     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8295     << 0 /* one pointer, so only one type */
8296     << Pointer->getSourceRange();
8297 }
8298
8299 /// \brief Emit error if Operand is incomplete pointer type
8300 ///
8301 /// \returns True if pointer has incomplete type
8302 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8303                                                  Expr *Operand) {
8304   QualType ResType = Operand->getType();
8305   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8306     ResType = ResAtomicType->getValueType();
8307
8308   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8309   QualType PointeeTy = ResType->getPointeeType();
8310   return S.RequireCompleteType(Loc, PointeeTy,
8311                                diag::err_typecheck_arithmetic_incomplete_type,
8312                                PointeeTy, Operand->getSourceRange());
8313 }
8314
8315 /// \brief Check the validity of an arithmetic pointer operand.
8316 ///
8317 /// If the operand has pointer type, this code will check for pointer types
8318 /// which are invalid in arithmetic operations. These will be diagnosed
8319 /// appropriately, including whether or not the use is supported as an
8320 /// extension.
8321 ///
8322 /// \returns True when the operand is valid to use (even if as an extension).
8323 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8324                                             Expr *Operand) {
8325   QualType ResType = Operand->getType();
8326   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8327     ResType = ResAtomicType->getValueType();
8328
8329   if (!ResType->isAnyPointerType()) return true;
8330
8331   QualType PointeeTy = ResType->getPointeeType();
8332   if (PointeeTy->isVoidType()) {
8333     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8334     return !S.getLangOpts().CPlusPlus;
8335   }
8336   if (PointeeTy->isFunctionType()) {
8337     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8338     return !S.getLangOpts().CPlusPlus;
8339   }
8340
8341   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8342
8343   return true;
8344 }
8345
8346 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8347 /// operands.
8348 ///
8349 /// This routine will diagnose any invalid arithmetic on pointer operands much
8350 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8351 /// for emitting a single diagnostic even for operations where both LHS and RHS
8352 /// are (potentially problematic) pointers.
8353 ///
8354 /// \returns True when the operand is valid to use (even if as an extension).
8355 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8356                                                 Expr *LHSExpr, Expr *RHSExpr) {
8357   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8358   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8359   if (!isLHSPointer && !isRHSPointer) return true;
8360
8361   QualType LHSPointeeTy, RHSPointeeTy;
8362   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8363   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8364
8365   // if both are pointers check if operation is valid wrt address spaces
8366   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8367     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8368     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8369     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8370       S.Diag(Loc,
8371              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8372           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8373           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8374       return false;
8375     }
8376   }
8377
8378   // Check for arithmetic on pointers to incomplete types.
8379   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8380   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8381   if (isLHSVoidPtr || isRHSVoidPtr) {
8382     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8383     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8384     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8385
8386     return !S.getLangOpts().CPlusPlus;
8387   }
8388
8389   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8390   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8391   if (isLHSFuncPtr || isRHSFuncPtr) {
8392     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8393     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8394                                                                 RHSExpr);
8395     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8396
8397     return !S.getLangOpts().CPlusPlus;
8398   }
8399
8400   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8401     return false;
8402   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8403     return false;
8404
8405   return true;
8406 }
8407
8408 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8409 /// literal.
8410 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8411                                   Expr *LHSExpr, Expr *RHSExpr) {
8412   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8413   Expr* IndexExpr = RHSExpr;
8414   if (!StrExpr) {
8415     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8416     IndexExpr = LHSExpr;
8417   }
8418
8419   bool IsStringPlusInt = StrExpr &&
8420       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8421   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8422     return;
8423
8424   llvm::APSInt index;
8425   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8426     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8427     if (index.isNonNegative() &&
8428         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8429                               index.isUnsigned()))
8430       return;
8431   }
8432
8433   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8434   Self.Diag(OpLoc, diag::warn_string_plus_int)
8435       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8436
8437   // Only print a fixit for "str" + int, not for int + "str".
8438   if (IndexExpr == RHSExpr) {
8439     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8440     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8441         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8442         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8443         << FixItHint::CreateInsertion(EndLoc, "]");
8444   } else
8445     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8446 }
8447
8448 /// \brief Emit a warning when adding a char literal to a string.
8449 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8450                                    Expr *LHSExpr, Expr *RHSExpr) {
8451   const Expr *StringRefExpr = LHSExpr;
8452   const CharacterLiteral *CharExpr =
8453       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8454
8455   if (!CharExpr) {
8456     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8457     StringRefExpr = RHSExpr;
8458   }
8459
8460   if (!CharExpr || !StringRefExpr)
8461     return;
8462
8463   const QualType StringType = StringRefExpr->getType();
8464
8465   // Return if not a PointerType.
8466   if (!StringType->isAnyPointerType())
8467     return;
8468
8469   // Return if not a CharacterType.
8470   if (!StringType->getPointeeType()->isAnyCharacterType())
8471     return;
8472
8473   ASTContext &Ctx = Self.getASTContext();
8474   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8475
8476   const QualType CharType = CharExpr->getType();
8477   if (!CharType->isAnyCharacterType() &&
8478       CharType->isIntegerType() &&
8479       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8480     Self.Diag(OpLoc, diag::warn_string_plus_char)
8481         << DiagRange << Ctx.CharTy;
8482   } else {
8483     Self.Diag(OpLoc, diag::warn_string_plus_char)
8484         << DiagRange << CharExpr->getType();
8485   }
8486
8487   // Only print a fixit for str + char, not for char + str.
8488   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8489     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8490     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8491         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8492         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8493         << FixItHint::CreateInsertion(EndLoc, "]");
8494   } else {
8495     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8496   }
8497 }
8498
8499 /// \brief Emit error when two pointers are incompatible.
8500 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8501                                            Expr *LHSExpr, Expr *RHSExpr) {
8502   assert(LHSExpr->getType()->isAnyPointerType());
8503   assert(RHSExpr->getType()->isAnyPointerType());
8504   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8505     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8506     << RHSExpr->getSourceRange();
8507 }
8508
8509 // C99 6.5.6
8510 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8511                                      SourceLocation Loc, BinaryOperatorKind Opc,
8512                                      QualType* CompLHSTy) {
8513   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8514
8515   if (LHS.get()->getType()->isVectorType() ||
8516       RHS.get()->getType()->isVectorType()) {
8517     QualType compType = CheckVectorOperands(
8518         LHS, RHS, Loc, CompLHSTy,
8519         /*AllowBothBool*/getLangOpts().AltiVec,
8520         /*AllowBoolConversions*/getLangOpts().ZVector);
8521     if (CompLHSTy) *CompLHSTy = compType;
8522     return compType;
8523   }
8524
8525   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8526   if (LHS.isInvalid() || RHS.isInvalid())
8527     return QualType();
8528
8529   // Diagnose "string literal" '+' int and string '+' "char literal".
8530   if (Opc == BO_Add) {
8531     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8532     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8533   }
8534
8535   // handle the common case first (both operands are arithmetic).
8536   if (!compType.isNull() && compType->isArithmeticType()) {
8537     if (CompLHSTy) *CompLHSTy = compType;
8538     return compType;
8539   }
8540
8541   // Type-checking.  Ultimately the pointer's going to be in PExp;
8542   // note that we bias towards the LHS being the pointer.
8543   Expr *PExp = LHS.get(), *IExp = RHS.get();
8544
8545   bool isObjCPointer;
8546   if (PExp->getType()->isPointerType()) {
8547     isObjCPointer = false;
8548   } else if (PExp->getType()->isObjCObjectPointerType()) {
8549     isObjCPointer = true;
8550   } else {
8551     std::swap(PExp, IExp);
8552     if (PExp->getType()->isPointerType()) {
8553       isObjCPointer = false;
8554     } else if (PExp->getType()->isObjCObjectPointerType()) {
8555       isObjCPointer = true;
8556     } else {
8557       return InvalidOperands(Loc, LHS, RHS);
8558     }
8559   }
8560   assert(PExp->getType()->isAnyPointerType());
8561
8562   if (!IExp->getType()->isIntegerType())
8563     return InvalidOperands(Loc, LHS, RHS);
8564
8565   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8566     return QualType();
8567
8568   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8569     return QualType();
8570
8571   // Check array bounds for pointer arithemtic
8572   CheckArrayAccess(PExp, IExp);
8573
8574   if (CompLHSTy) {
8575     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8576     if (LHSTy.isNull()) {
8577       LHSTy = LHS.get()->getType();
8578       if (LHSTy->isPromotableIntegerType())
8579         LHSTy = Context.getPromotedIntegerType(LHSTy);
8580     }
8581     *CompLHSTy = LHSTy;
8582   }
8583
8584   return PExp->getType();
8585 }
8586
8587 // C99 6.5.6
8588 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8589                                         SourceLocation Loc,
8590                                         QualType* CompLHSTy) {
8591   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8592
8593   if (LHS.get()->getType()->isVectorType() ||
8594       RHS.get()->getType()->isVectorType()) {
8595     QualType compType = CheckVectorOperands(
8596         LHS, RHS, Loc, CompLHSTy,
8597         /*AllowBothBool*/getLangOpts().AltiVec,
8598         /*AllowBoolConversions*/getLangOpts().ZVector);
8599     if (CompLHSTy) *CompLHSTy = compType;
8600     return compType;
8601   }
8602
8603   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8604   if (LHS.isInvalid() || RHS.isInvalid())
8605     return QualType();
8606
8607   // Enforce type constraints: C99 6.5.6p3.
8608
8609   // Handle the common case first (both operands are arithmetic).
8610   if (!compType.isNull() && compType->isArithmeticType()) {
8611     if (CompLHSTy) *CompLHSTy = compType;
8612     return compType;
8613   }
8614
8615   // Either ptr - int   or   ptr - ptr.
8616   if (LHS.get()->getType()->isAnyPointerType()) {
8617     QualType lpointee = LHS.get()->getType()->getPointeeType();
8618
8619     // Diagnose bad cases where we step over interface counts.
8620     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8621         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8622       return QualType();
8623
8624     // The result type of a pointer-int computation is the pointer type.
8625     if (RHS.get()->getType()->isIntegerType()) {
8626       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8627         return QualType();
8628
8629       // Check array bounds for pointer arithemtic
8630       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8631                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8632
8633       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8634       return LHS.get()->getType();
8635     }
8636
8637     // Handle pointer-pointer subtractions.
8638     if (const PointerType *RHSPTy
8639           = RHS.get()->getType()->getAs<PointerType>()) {
8640       QualType rpointee = RHSPTy->getPointeeType();
8641
8642       if (getLangOpts().CPlusPlus) {
8643         // Pointee types must be the same: C++ [expr.add]
8644         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8645           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8646         }
8647       } else {
8648         // Pointee types must be compatible C99 6.5.6p3
8649         if (!Context.typesAreCompatible(
8650                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8651                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8652           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8653           return QualType();
8654         }
8655       }
8656
8657       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8658                                                LHS.get(), RHS.get()))
8659         return QualType();
8660
8661       // The pointee type may have zero size.  As an extension, a structure or
8662       // union may have zero size or an array may have zero length.  In this
8663       // case subtraction does not make sense.
8664       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8665         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8666         if (ElementSize.isZero()) {
8667           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8668             << rpointee.getUnqualifiedType()
8669             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8670         }
8671       }
8672
8673       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8674       return Context.getPointerDiffType();
8675     }
8676   }
8677
8678   return InvalidOperands(Loc, LHS, RHS);
8679 }
8680
8681 static bool isScopedEnumerationType(QualType T) {
8682   if (const EnumType *ET = T->getAs<EnumType>())
8683     return ET->getDecl()->isScoped();
8684   return false;
8685 }
8686
8687 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8688                                    SourceLocation Loc, BinaryOperatorKind Opc,
8689                                    QualType LHSType) {
8690   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8691   // so skip remaining warnings as we don't want to modify values within Sema.
8692   if (S.getLangOpts().OpenCL)
8693     return;
8694
8695   llvm::APSInt Right;
8696   // Check right/shifter operand
8697   if (RHS.get()->isValueDependent() ||
8698       !RHS.get()->EvaluateAsInt(Right, S.Context))
8699     return;
8700
8701   if (Right.isNegative()) {
8702     S.DiagRuntimeBehavior(Loc, RHS.get(),
8703                           S.PDiag(diag::warn_shift_negative)
8704                             << RHS.get()->getSourceRange());
8705     return;
8706   }
8707   llvm::APInt LeftBits(Right.getBitWidth(),
8708                        S.Context.getTypeSize(LHS.get()->getType()));
8709   if (Right.uge(LeftBits)) {
8710     S.DiagRuntimeBehavior(Loc, RHS.get(),
8711                           S.PDiag(diag::warn_shift_gt_typewidth)
8712                             << RHS.get()->getSourceRange());
8713     return;
8714   }
8715   if (Opc != BO_Shl)
8716     return;
8717
8718   // When left shifting an ICE which is signed, we can check for overflow which
8719   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8720   // integers have defined behavior modulo one more than the maximum value
8721   // representable in the result type, so never warn for those.
8722   llvm::APSInt Left;
8723   if (LHS.get()->isValueDependent() ||
8724       LHSType->hasUnsignedIntegerRepresentation() ||
8725       !LHS.get()->EvaluateAsInt(Left, S.Context))
8726     return;
8727
8728   // If LHS does not have a signed type and non-negative value
8729   // then, the behavior is undefined. Warn about it.
8730   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8731     S.DiagRuntimeBehavior(Loc, LHS.get(),
8732                           S.PDiag(diag::warn_shift_lhs_negative)
8733                             << LHS.get()->getSourceRange());
8734     return;
8735   }
8736
8737   llvm::APInt ResultBits =
8738       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8739   if (LeftBits.uge(ResultBits))
8740     return;
8741   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8742   Result = Result.shl(Right);
8743
8744   // Print the bit representation of the signed integer as an unsigned
8745   // hexadecimal number.
8746   SmallString<40> HexResult;
8747   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8748
8749   // If we are only missing a sign bit, this is less likely to result in actual
8750   // bugs -- if the result is cast back to an unsigned type, it will have the
8751   // expected value. Thus we place this behind a different warning that can be
8752   // turned off separately if needed.
8753   if (LeftBits == ResultBits - 1) {
8754     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8755         << HexResult << LHSType
8756         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8757     return;
8758   }
8759
8760   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8761     << HexResult.str() << Result.getMinSignedBits() << LHSType
8762     << Left.getBitWidth() << LHS.get()->getSourceRange()
8763     << RHS.get()->getSourceRange();
8764 }
8765
8766 /// \brief Return the resulting type when a vector is shifted
8767 ///        by a scalar or vector shift amount.
8768 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8769                                  SourceLocation Loc, bool IsCompAssign) {
8770   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8771   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8772       !LHS.get()->getType()->isVectorType()) {
8773     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8774       << RHS.get()->getType() << LHS.get()->getType()
8775       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8776     return QualType();
8777   }
8778
8779   if (!IsCompAssign) {
8780     LHS = S.UsualUnaryConversions(LHS.get());
8781     if (LHS.isInvalid()) return QualType();
8782   }
8783
8784   RHS = S.UsualUnaryConversions(RHS.get());
8785   if (RHS.isInvalid()) return QualType();
8786
8787   QualType LHSType = LHS.get()->getType();
8788   // Note that LHS might be a scalar because the routine calls not only in
8789   // OpenCL case.
8790   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8791   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8792
8793   // Note that RHS might not be a vector.
8794   QualType RHSType = RHS.get()->getType();
8795   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8796   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8797
8798   // The operands need to be integers.
8799   if (!LHSEleType->isIntegerType()) {
8800     S.Diag(Loc, diag::err_typecheck_expect_int)
8801       << LHS.get()->getType() << LHS.get()->getSourceRange();
8802     return QualType();
8803   }
8804
8805   if (!RHSEleType->isIntegerType()) {
8806     S.Diag(Loc, diag::err_typecheck_expect_int)
8807       << RHS.get()->getType() << RHS.get()->getSourceRange();
8808     return QualType();
8809   }
8810
8811   if (!LHSVecTy) {
8812     assert(RHSVecTy);
8813     if (IsCompAssign)
8814       return RHSType;
8815     if (LHSEleType != RHSEleType) {
8816       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8817       LHSEleType = RHSEleType;
8818     }
8819     QualType VecTy =
8820         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8821     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8822     LHSType = VecTy;
8823   } else if (RHSVecTy) {
8824     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8825     // are applied component-wise. So if RHS is a vector, then ensure
8826     // that the number of elements is the same as LHS...
8827     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8828       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8829         << LHS.get()->getType() << RHS.get()->getType()
8830         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8831       return QualType();
8832     }
8833     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8834       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8835       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8836       if (LHSBT != RHSBT &&
8837           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8838         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8839             << LHS.get()->getType() << RHS.get()->getType()
8840             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8841       }
8842     }
8843   } else {
8844     // ...else expand RHS to match the number of elements in LHS.
8845     QualType VecTy =
8846       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8847     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8848   }
8849
8850   return LHSType;
8851 }
8852
8853 // C99 6.5.7
8854 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8855                                   SourceLocation Loc, BinaryOperatorKind Opc,
8856                                   bool IsCompAssign) {
8857   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8858
8859   // Vector shifts promote their scalar inputs to vector type.
8860   if (LHS.get()->getType()->isVectorType() ||
8861       RHS.get()->getType()->isVectorType()) {
8862     if (LangOpts.ZVector) {
8863       // The shift operators for the z vector extensions work basically
8864       // like general shifts, except that neither the LHS nor the RHS is
8865       // allowed to be a "vector bool".
8866       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8867         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8868           return InvalidOperands(Loc, LHS, RHS);
8869       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8870         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8871           return InvalidOperands(Loc, LHS, RHS);
8872     }
8873     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8874   }
8875
8876   // Shifts don't perform usual arithmetic conversions, they just do integer
8877   // promotions on each operand. C99 6.5.7p3
8878
8879   // For the LHS, do usual unary conversions, but then reset them away
8880   // if this is a compound assignment.
8881   ExprResult OldLHS = LHS;
8882   LHS = UsualUnaryConversions(LHS.get());
8883   if (LHS.isInvalid())
8884     return QualType();
8885   QualType LHSType = LHS.get()->getType();
8886   if (IsCompAssign) LHS = OldLHS;
8887
8888   // The RHS is simpler.
8889   RHS = UsualUnaryConversions(RHS.get());
8890   if (RHS.isInvalid())
8891     return QualType();
8892   QualType RHSType = RHS.get()->getType();
8893
8894   // C99 6.5.7p2: Each of the operands shall have integer type.
8895   if (!LHSType->hasIntegerRepresentation() ||
8896       !RHSType->hasIntegerRepresentation())
8897     return InvalidOperands(Loc, LHS, RHS);
8898
8899   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8900   // hasIntegerRepresentation() above instead of this.
8901   if (isScopedEnumerationType(LHSType) ||
8902       isScopedEnumerationType(RHSType)) {
8903     return InvalidOperands(Loc, LHS, RHS);
8904   }
8905   // Sanity-check shift operands
8906   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8907
8908   // "The type of the result is that of the promoted left operand."
8909   return LHSType;
8910 }
8911
8912 static bool IsWithinTemplateSpecialization(Decl *D) {
8913   if (DeclContext *DC = D->getDeclContext()) {
8914     if (isa<ClassTemplateSpecializationDecl>(DC))
8915       return true;
8916     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8917       return FD->isFunctionTemplateSpecialization();
8918   }
8919   return false;
8920 }
8921
8922 /// If two different enums are compared, raise a warning.
8923 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8924                                 Expr *RHS) {
8925   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8926   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8927
8928   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8929   if (!LHSEnumType)
8930     return;
8931   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8932   if (!RHSEnumType)
8933     return;
8934
8935   // Ignore anonymous enums.
8936   if (!LHSEnumType->getDecl()->getIdentifier())
8937     return;
8938   if (!RHSEnumType->getDecl()->getIdentifier())
8939     return;
8940
8941   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8942     return;
8943
8944   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8945       << LHSStrippedType << RHSStrippedType
8946       << LHS->getSourceRange() << RHS->getSourceRange();
8947 }
8948
8949 /// \brief Diagnose bad pointer comparisons.
8950 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8951                                               ExprResult &LHS, ExprResult &RHS,
8952                                               bool IsError) {
8953   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8954                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8955     << LHS.get()->getType() << RHS.get()->getType()
8956     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8957 }
8958
8959 /// \brief Returns false if the pointers are converted to a composite type,
8960 /// true otherwise.
8961 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8962                                            ExprResult &LHS, ExprResult &RHS) {
8963   // C++ [expr.rel]p2:
8964   //   [...] Pointer conversions (4.10) and qualification
8965   //   conversions (4.4) are performed on pointer operands (or on
8966   //   a pointer operand and a null pointer constant) to bring
8967   //   them to their composite pointer type. [...]
8968   //
8969   // C++ [expr.eq]p1 uses the same notion for (in)equality
8970   // comparisons of pointers.
8971
8972   QualType LHSType = LHS.get()->getType();
8973   QualType RHSType = RHS.get()->getType();
8974   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8975          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
8976
8977   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
8978   if (T.isNull()) {
8979     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8980         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8981       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8982     else
8983       S.InvalidOperands(Loc, LHS, RHS);
8984     return true;
8985   }
8986
8987   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8988   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8989   return false;
8990 }
8991
8992 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8993                                                     ExprResult &LHS,
8994                                                     ExprResult &RHS,
8995                                                     bool IsError) {
8996   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8997                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8998     << LHS.get()->getType() << RHS.get()->getType()
8999     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9000 }
9001
9002 static bool isObjCObjectLiteral(ExprResult &E) {
9003   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9004   case Stmt::ObjCArrayLiteralClass:
9005   case Stmt::ObjCDictionaryLiteralClass:
9006   case Stmt::ObjCStringLiteralClass:
9007   case Stmt::ObjCBoxedExprClass:
9008     return true;
9009   default:
9010     // Note that ObjCBoolLiteral is NOT an object literal!
9011     return false;
9012   }
9013 }
9014
9015 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9016   const ObjCObjectPointerType *Type =
9017     LHS->getType()->getAs<ObjCObjectPointerType>();
9018
9019   // If this is not actually an Objective-C object, bail out.
9020   if (!Type)
9021     return false;
9022
9023   // Get the LHS object's interface type.
9024   QualType InterfaceType = Type->getPointeeType();
9025
9026   // If the RHS isn't an Objective-C object, bail out.
9027   if (!RHS->getType()->isObjCObjectPointerType())
9028     return false;
9029
9030   // Try to find the -isEqual: method.
9031   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9032   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9033                                                       InterfaceType,
9034                                                       /*instance=*/true);
9035   if (!Method) {
9036     if (Type->isObjCIdType()) {
9037       // For 'id', just check the global pool.
9038       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9039                                                   /*receiverId=*/true);
9040     } else {
9041       // Check protocols.
9042       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9043                                              /*instance=*/true);
9044     }
9045   }
9046
9047   if (!Method)
9048     return false;
9049
9050   QualType T = Method->parameters()[0]->getType();
9051   if (!T->isObjCObjectPointerType())
9052     return false;
9053
9054   QualType R = Method->getReturnType();
9055   if (!R->isScalarType())
9056     return false;
9057
9058   return true;
9059 }
9060
9061 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9062   FromE = FromE->IgnoreParenImpCasts();
9063   switch (FromE->getStmtClass()) {
9064     default:
9065       break;
9066     case Stmt::ObjCStringLiteralClass:
9067       // "string literal"
9068       return LK_String;
9069     case Stmt::ObjCArrayLiteralClass:
9070       // "array literal"
9071       return LK_Array;
9072     case Stmt::ObjCDictionaryLiteralClass:
9073       // "dictionary literal"
9074       return LK_Dictionary;
9075     case Stmt::BlockExprClass:
9076       return LK_Block;
9077     case Stmt::ObjCBoxedExprClass: {
9078       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9079       switch (Inner->getStmtClass()) {
9080         case Stmt::IntegerLiteralClass:
9081         case Stmt::FloatingLiteralClass:
9082         case Stmt::CharacterLiteralClass:
9083         case Stmt::ObjCBoolLiteralExprClass:
9084         case Stmt::CXXBoolLiteralExprClass:
9085           // "numeric literal"
9086           return LK_Numeric;
9087         case Stmt::ImplicitCastExprClass: {
9088           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9089           // Boolean literals can be represented by implicit casts.
9090           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9091             return LK_Numeric;
9092           break;
9093         }
9094         default:
9095           break;
9096       }
9097       return LK_Boxed;
9098     }
9099   }
9100   return LK_None;
9101 }
9102
9103 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9104                                           ExprResult &LHS, ExprResult &RHS,
9105                                           BinaryOperator::Opcode Opc){
9106   Expr *Literal;
9107   Expr *Other;
9108   if (isObjCObjectLiteral(LHS)) {
9109     Literal = LHS.get();
9110     Other = RHS.get();
9111   } else {
9112     Literal = RHS.get();
9113     Other = LHS.get();
9114   }
9115
9116   // Don't warn on comparisons against nil.
9117   Other = Other->IgnoreParenCasts();
9118   if (Other->isNullPointerConstant(S.getASTContext(),
9119                                    Expr::NPC_ValueDependentIsNotNull))
9120     return;
9121
9122   // This should be kept in sync with warn_objc_literal_comparison.
9123   // LK_String should always be after the other literals, since it has its own
9124   // warning flag.
9125   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9126   assert(LiteralKind != Sema::LK_Block);
9127   if (LiteralKind == Sema::LK_None) {
9128     llvm_unreachable("Unknown Objective-C object literal kind");
9129   }
9130
9131   if (LiteralKind == Sema::LK_String)
9132     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9133       << Literal->getSourceRange();
9134   else
9135     S.Diag(Loc, diag::warn_objc_literal_comparison)
9136       << LiteralKind << Literal->getSourceRange();
9137
9138   if (BinaryOperator::isEqualityOp(Opc) &&
9139       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9140     SourceLocation Start = LHS.get()->getLocStart();
9141     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9142     CharSourceRange OpRange =
9143       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9144
9145     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9146       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9147       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9148       << FixItHint::CreateInsertion(End, "]");
9149   }
9150 }
9151
9152 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9153 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9154                                            ExprResult &RHS, SourceLocation Loc,
9155                                            BinaryOperatorKind Opc) {
9156   // Check that left hand side is !something.
9157   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9158   if (!UO || UO->getOpcode() != UO_LNot) return;
9159
9160   // Only check if the right hand side is non-bool arithmetic type.
9161   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9162
9163   // Make sure that the something in !something is not bool.
9164   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9165   if (SubExpr->isKnownToHaveBooleanValue()) return;
9166
9167   // Emit warning.
9168   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9169   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9170       << Loc << IsBitwiseOp;
9171
9172   // First note suggest !(x < y)
9173   SourceLocation FirstOpen = SubExpr->getLocStart();
9174   SourceLocation FirstClose = RHS.get()->getLocEnd();
9175   FirstClose = S.getLocForEndOfToken(FirstClose);
9176   if (FirstClose.isInvalid())
9177     FirstOpen = SourceLocation();
9178   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9179       << IsBitwiseOp
9180       << FixItHint::CreateInsertion(FirstOpen, "(")
9181       << FixItHint::CreateInsertion(FirstClose, ")");
9182
9183   // Second note suggests (!x) < y
9184   SourceLocation SecondOpen = LHS.get()->getLocStart();
9185   SourceLocation SecondClose = LHS.get()->getLocEnd();
9186   SecondClose = S.getLocForEndOfToken(SecondClose);
9187   if (SecondClose.isInvalid())
9188     SecondOpen = SourceLocation();
9189   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9190       << FixItHint::CreateInsertion(SecondOpen, "(")
9191       << FixItHint::CreateInsertion(SecondClose, ")");
9192 }
9193
9194 // Get the decl for a simple expression: a reference to a variable,
9195 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9196 static ValueDecl *getCompareDecl(Expr *E) {
9197   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9198     return DR->getDecl();
9199   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9200     if (Ivar->isFreeIvar())
9201       return Ivar->getDecl();
9202   }
9203   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9204     if (Mem->isImplicitAccess())
9205       return Mem->getMemberDecl();
9206   }
9207   return nullptr;
9208 }
9209
9210 // C99 6.5.8, C++ [expr.rel]
9211 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9212                                     SourceLocation Loc, BinaryOperatorKind Opc,
9213                                     bool IsRelational) {
9214   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9215
9216   // Handle vector comparisons separately.
9217   if (LHS.get()->getType()->isVectorType() ||
9218       RHS.get()->getType()->isVectorType())
9219     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9220
9221   QualType LHSType = LHS.get()->getType();
9222   QualType RHSType = RHS.get()->getType();
9223
9224   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9225   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9226
9227   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9228   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9229
9230   if (!LHSType->hasFloatingRepresentation() &&
9231       !(LHSType->isBlockPointerType() && IsRelational) &&
9232       !LHS.get()->getLocStart().isMacroID() &&
9233       !RHS.get()->getLocStart().isMacroID() &&
9234       ActiveTemplateInstantiations.empty()) {
9235     // For non-floating point types, check for self-comparisons of the form
9236     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9237     // often indicate logic errors in the program.
9238     //
9239     // NOTE: Don't warn about comparison expressions resulting from macro
9240     // expansion. Also don't warn about comparisons which are only self
9241     // comparisons within a template specialization. The warnings should catch
9242     // obvious cases in the definition of the template anyways. The idea is to
9243     // warn when the typed comparison operator will always evaluate to the same
9244     // result.
9245     ValueDecl *DL = getCompareDecl(LHSStripped);
9246     ValueDecl *DR = getCompareDecl(RHSStripped);
9247     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9248       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9249                           << 0 // self-
9250                           << (Opc == BO_EQ
9251                               || Opc == BO_LE
9252                               || Opc == BO_GE));
9253     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9254                !DL->getType()->isReferenceType() &&
9255                !DR->getType()->isReferenceType()) {
9256         // what is it always going to eval to?
9257         char always_evals_to;
9258         switch(Opc) {
9259         case BO_EQ: // e.g. array1 == array2
9260           always_evals_to = 0; // false
9261           break;
9262         case BO_NE: // e.g. array1 != array2
9263           always_evals_to = 1; // true
9264           break;
9265         default:
9266           // best we can say is 'a constant'
9267           always_evals_to = 2; // e.g. array1 <= array2
9268           break;
9269         }
9270         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9271                             << 1 // array
9272                             << always_evals_to);
9273     }
9274
9275     if (isa<CastExpr>(LHSStripped))
9276       LHSStripped = LHSStripped->IgnoreParenCasts();
9277     if (isa<CastExpr>(RHSStripped))
9278       RHSStripped = RHSStripped->IgnoreParenCasts();
9279
9280     // Warn about comparisons against a string constant (unless the other
9281     // operand is null), the user probably wants strcmp.
9282     Expr *literalString = nullptr;
9283     Expr *literalStringStripped = nullptr;
9284     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9285         !RHSStripped->isNullPointerConstant(Context,
9286                                             Expr::NPC_ValueDependentIsNull)) {
9287       literalString = LHS.get();
9288       literalStringStripped = LHSStripped;
9289     } else if ((isa<StringLiteral>(RHSStripped) ||
9290                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9291                !LHSStripped->isNullPointerConstant(Context,
9292                                             Expr::NPC_ValueDependentIsNull)) {
9293       literalString = RHS.get();
9294       literalStringStripped = RHSStripped;
9295     }
9296
9297     if (literalString) {
9298       DiagRuntimeBehavior(Loc, nullptr,
9299         PDiag(diag::warn_stringcompare)
9300           << isa<ObjCEncodeExpr>(literalStringStripped)
9301           << literalString->getSourceRange());
9302     }
9303   }
9304
9305   // C99 6.5.8p3 / C99 6.5.9p4
9306   UsualArithmeticConversions(LHS, RHS);
9307   if (LHS.isInvalid() || RHS.isInvalid())
9308     return QualType();
9309
9310   LHSType = LHS.get()->getType();
9311   RHSType = RHS.get()->getType();
9312
9313   // The result of comparisons is 'bool' in C++, 'int' in C.
9314   QualType ResultTy = Context.getLogicalOperationType();
9315
9316   if (IsRelational) {
9317     if (LHSType->isRealType() && RHSType->isRealType())
9318       return ResultTy;
9319   } else {
9320     // Check for comparisons of floating point operands using != and ==.
9321     if (LHSType->hasFloatingRepresentation())
9322       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9323
9324     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9325       return ResultTy;
9326   }
9327
9328   const Expr::NullPointerConstantKind LHSNullKind =
9329       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9330   const Expr::NullPointerConstantKind RHSNullKind =
9331       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9332   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9333   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9334
9335   if (!IsRelational && LHSIsNull != RHSIsNull) {
9336     bool IsEquality = Opc == BO_EQ;
9337     if (RHSIsNull)
9338       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9339                                    RHS.get()->getSourceRange());
9340     else
9341       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9342                                    LHS.get()->getSourceRange());
9343   }
9344
9345   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9346       (RHSType->isIntegerType() && !RHSIsNull)) {
9347     // Skip normal pointer conversion checks in this case; we have better
9348     // diagnostics for this below.
9349   } else if (getLangOpts().CPlusPlus) {
9350     // Equality comparison of a function pointer to a void pointer is invalid,
9351     // but we allow it as an extension.
9352     // FIXME: If we really want to allow this, should it be part of composite
9353     // pointer type computation so it works in conditionals too?
9354     if (!IsRelational &&
9355         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9356          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9357       // This is a gcc extension compatibility comparison.
9358       // In a SFINAE context, we treat this as a hard error to maintain
9359       // conformance with the C++ standard.
9360       diagnoseFunctionPointerToVoidComparison(
9361           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9362       
9363       if (isSFINAEContext())
9364         return QualType();
9365       
9366       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9367       return ResultTy;
9368     }
9369
9370     // C++ [expr.eq]p2:
9371     //   If at least one operand is a pointer [...] bring them to their
9372     //   composite pointer type.
9373     // C++ [expr.rel]p2:
9374     //   If both operands are pointers, [...] bring them to their composite
9375     //   pointer type.
9376     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9377         (IsRelational ? 2 : 1)) {
9378       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9379         return QualType();
9380       else
9381         return ResultTy;
9382     }
9383   } else if (LHSType->isPointerType() &&
9384              RHSType->isPointerType()) { // C99 6.5.8p2
9385     // All of the following pointer-related warnings are GCC extensions, except
9386     // when handling null pointer constants.
9387     QualType LCanPointeeTy =
9388       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9389     QualType RCanPointeeTy =
9390       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9391
9392     // C99 6.5.9p2 and C99 6.5.8p2
9393     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9394                                    RCanPointeeTy.getUnqualifiedType())) {
9395       // Valid unless a relational comparison of function pointers
9396       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9397         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9398           << LHSType << RHSType << LHS.get()->getSourceRange()
9399           << RHS.get()->getSourceRange();
9400       }
9401     } else if (!IsRelational &&
9402                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9403       // Valid unless comparison between non-null pointer and function pointer
9404       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9405           && !LHSIsNull && !RHSIsNull)
9406         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9407                                                 /*isError*/false);
9408     } else {
9409       // Invalid
9410       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9411     }
9412     if (LCanPointeeTy != RCanPointeeTy) {
9413       // Treat NULL constant as a special case in OpenCL.
9414       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9415         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9416         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9417           Diag(Loc,
9418                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9419               << LHSType << RHSType << 0 /* comparison */
9420               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9421         }
9422       }
9423       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9424       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9425       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9426                                                : CK_BitCast;
9427       if (LHSIsNull && !RHSIsNull)
9428         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9429       else
9430         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9431     }
9432     return ResultTy;
9433   }
9434
9435   if (getLangOpts().CPlusPlus) {
9436     // C++ [expr.eq]p4:
9437     //   Two operands of type std::nullptr_t or one operand of type
9438     //   std::nullptr_t and the other a null pointer constant compare equal.
9439     if (!IsRelational && LHSIsNull && RHSIsNull) {
9440       if (LHSType->isNullPtrType()) {
9441         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9442         return ResultTy;
9443       }
9444       if (RHSType->isNullPtrType()) {
9445         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9446         return ResultTy;
9447       }
9448     }
9449
9450     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9451     // These aren't covered by the composite pointer type rules.
9452     if (!IsRelational && RHSType->isNullPtrType() &&
9453         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9454       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9455       return ResultTy;
9456     }
9457     if (!IsRelational && LHSType->isNullPtrType() &&
9458         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9459       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9460       return ResultTy;
9461     }
9462
9463     if (IsRelational &&
9464         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9465          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9466       // HACK: Relational comparison of nullptr_t against a pointer type is
9467       // invalid per DR583, but we allow it within std::less<> and friends,
9468       // since otherwise common uses of it break.
9469       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9470       // friends to have std::nullptr_t overload candidates.
9471       DeclContext *DC = CurContext;
9472       if (isa<FunctionDecl>(DC))
9473         DC = DC->getParent();
9474       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9475         if (CTSD->isInStdNamespace() &&
9476             llvm::StringSwitch<bool>(CTSD->getName())
9477                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9478                 .Default(false)) {
9479           if (RHSType->isNullPtrType())
9480             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9481           else
9482             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9483           return ResultTy;
9484         }
9485       }
9486     }
9487
9488     // C++ [expr.eq]p2:
9489     //   If at least one operand is a pointer to member, [...] bring them to
9490     //   their composite pointer type.
9491     if (!IsRelational &&
9492         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9493       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9494         return QualType();
9495       else
9496         return ResultTy;
9497     }
9498
9499     // Handle scoped enumeration types specifically, since they don't promote
9500     // to integers.
9501     if (LHS.get()->getType()->isEnumeralType() &&
9502         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9503                                        RHS.get()->getType()))
9504       return ResultTy;
9505   }
9506
9507   // Handle block pointer types.
9508   if (!IsRelational && LHSType->isBlockPointerType() &&
9509       RHSType->isBlockPointerType()) {
9510     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9511     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9512
9513     if (!LHSIsNull && !RHSIsNull &&
9514         !Context.typesAreCompatible(lpointee, rpointee)) {
9515       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9516         << LHSType << RHSType << LHS.get()->getSourceRange()
9517         << RHS.get()->getSourceRange();
9518     }
9519     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9520     return ResultTy;
9521   }
9522
9523   // Allow block pointers to be compared with null pointer constants.
9524   if (!IsRelational
9525       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9526           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9527     if (!LHSIsNull && !RHSIsNull) {
9528       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9529              ->getPointeeType()->isVoidType())
9530             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9531                 ->getPointeeType()->isVoidType())))
9532         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9533           << LHSType << RHSType << LHS.get()->getSourceRange()
9534           << RHS.get()->getSourceRange();
9535     }
9536     if (LHSIsNull && !RHSIsNull)
9537       LHS = ImpCastExprToType(LHS.get(), RHSType,
9538                               RHSType->isPointerType() ? CK_BitCast
9539                                 : CK_AnyPointerToBlockPointerCast);
9540     else
9541       RHS = ImpCastExprToType(RHS.get(), LHSType,
9542                               LHSType->isPointerType() ? CK_BitCast
9543                                 : CK_AnyPointerToBlockPointerCast);
9544     return ResultTy;
9545   }
9546
9547   if (LHSType->isObjCObjectPointerType() ||
9548       RHSType->isObjCObjectPointerType()) {
9549     const PointerType *LPT = LHSType->getAs<PointerType>();
9550     const PointerType *RPT = RHSType->getAs<PointerType>();
9551     if (LPT || RPT) {
9552       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9553       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9554
9555       if (!LPtrToVoid && !RPtrToVoid &&
9556           !Context.typesAreCompatible(LHSType, RHSType)) {
9557         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9558                                           /*isError*/false);
9559       }
9560       if (LHSIsNull && !RHSIsNull) {
9561         Expr *E = LHS.get();
9562         if (getLangOpts().ObjCAutoRefCount)
9563           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9564         LHS = ImpCastExprToType(E, RHSType,
9565                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9566       }
9567       else {
9568         Expr *E = RHS.get();
9569         if (getLangOpts().ObjCAutoRefCount)
9570           CheckObjCARCConversion(SourceRange(), LHSType, E,
9571                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9572                                  /*DiagnoseCFAudited=*/false, Opc);
9573         RHS = ImpCastExprToType(E, LHSType,
9574                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9575       }
9576       return ResultTy;
9577     }
9578     if (LHSType->isObjCObjectPointerType() &&
9579         RHSType->isObjCObjectPointerType()) {
9580       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9581         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9582                                           /*isError*/false);
9583       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9584         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9585
9586       if (LHSIsNull && !RHSIsNull)
9587         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9588       else
9589         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9590       return ResultTy;
9591     }
9592   }
9593   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9594       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9595     unsigned DiagID = 0;
9596     bool isError = false;
9597     if (LangOpts.DebuggerSupport) {
9598       // Under a debugger, allow the comparison of pointers to integers,
9599       // since users tend to want to compare addresses.
9600     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9601                (RHSIsNull && RHSType->isIntegerType())) {
9602       if (IsRelational) {
9603         isError = getLangOpts().CPlusPlus;
9604         DiagID =
9605           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9606                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9607       }
9608     } else if (getLangOpts().CPlusPlus) {
9609       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9610       isError = true;
9611     } else if (IsRelational)
9612       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9613     else
9614       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9615
9616     if (DiagID) {
9617       Diag(Loc, DiagID)
9618         << LHSType << RHSType << LHS.get()->getSourceRange()
9619         << RHS.get()->getSourceRange();
9620       if (isError)
9621         return QualType();
9622     }
9623     
9624     if (LHSType->isIntegerType())
9625       LHS = ImpCastExprToType(LHS.get(), RHSType,
9626                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9627     else
9628       RHS = ImpCastExprToType(RHS.get(), LHSType,
9629                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9630     return ResultTy;
9631   }
9632   
9633   // Handle block pointers.
9634   if (!IsRelational && RHSIsNull
9635       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9636     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9637     return ResultTy;
9638   }
9639   if (!IsRelational && LHSIsNull
9640       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9641     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9642     return ResultTy;
9643   }
9644
9645   if (getLangOpts().OpenCLVersion >= 200) {
9646     if (LHSIsNull && RHSType->isQueueT()) {
9647       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9648       return ResultTy;
9649     }
9650
9651     if (LHSType->isQueueT() && RHSIsNull) {
9652       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9653       return ResultTy;
9654     }
9655   }
9656
9657   return InvalidOperands(Loc, LHS, RHS);
9658 }
9659
9660
9661 // Return a signed type that is of identical size and number of elements.
9662 // For floating point vectors, return an integer type of identical size 
9663 // and number of elements.
9664 QualType Sema::GetSignedVectorType(QualType V) {
9665   const VectorType *VTy = V->getAs<VectorType>();
9666   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9667   if (TypeSize == Context.getTypeSize(Context.CharTy))
9668     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9669   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9670     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9671   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9672     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9673   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9674     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9675   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9676          "Unhandled vector element size in vector compare");
9677   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9678 }
9679
9680 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9681 /// operates on extended vector types.  Instead of producing an IntTy result,
9682 /// like a scalar comparison, a vector comparison produces a vector of integer
9683 /// types.
9684 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9685                                           SourceLocation Loc,
9686                                           bool IsRelational) {
9687   // Check to make sure we're operating on vectors of the same type and width,
9688   // Allowing one side to be a scalar of element type.
9689   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9690                               /*AllowBothBool*/true,
9691                               /*AllowBoolConversions*/getLangOpts().ZVector);
9692   if (vType.isNull())
9693     return vType;
9694
9695   QualType LHSType = LHS.get()->getType();
9696
9697   // If AltiVec, the comparison results in a numeric type, i.e.
9698   // bool for C++, int for C
9699   if (getLangOpts().AltiVec &&
9700       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9701     return Context.getLogicalOperationType();
9702
9703   // For non-floating point types, check for self-comparisons of the form
9704   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9705   // often indicate logic errors in the program.
9706   if (!LHSType->hasFloatingRepresentation() &&
9707       ActiveTemplateInstantiations.empty()) {
9708     if (DeclRefExpr* DRL
9709           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9710       if (DeclRefExpr* DRR
9711             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9712         if (DRL->getDecl() == DRR->getDecl())
9713           DiagRuntimeBehavior(Loc, nullptr,
9714                               PDiag(diag::warn_comparison_always)
9715                                 << 0 // self-
9716                                 << 2 // "a constant"
9717                               );
9718   }
9719
9720   // Check for comparisons of floating point operands using != and ==.
9721   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9722     assert (RHS.get()->getType()->hasFloatingRepresentation());
9723     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9724   }
9725   
9726   // Return a signed type for the vector.
9727   return GetSignedVectorType(vType);
9728 }
9729
9730 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9731                                           SourceLocation Loc) {
9732   // Ensure that either both operands are of the same vector type, or
9733   // one operand is of a vector type and the other is of its element type.
9734   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9735                                        /*AllowBothBool*/true,
9736                                        /*AllowBoolConversions*/false);
9737   if (vType.isNull())
9738     return InvalidOperands(Loc, LHS, RHS);
9739   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9740       vType->hasFloatingRepresentation())
9741     return InvalidOperands(Loc, LHS, RHS);
9742   
9743   return GetSignedVectorType(LHS.get()->getType());
9744 }
9745
9746 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9747                                            SourceLocation Loc,
9748                                            BinaryOperatorKind Opc) {
9749   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9750
9751   bool IsCompAssign =
9752       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9753
9754   if (LHS.get()->getType()->isVectorType() ||
9755       RHS.get()->getType()->isVectorType()) {
9756     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9757         RHS.get()->getType()->hasIntegerRepresentation())
9758       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9759                         /*AllowBothBool*/true,
9760                         /*AllowBoolConversions*/getLangOpts().ZVector);
9761     return InvalidOperands(Loc, LHS, RHS);
9762   }
9763
9764   if (Opc == BO_And)
9765     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9766
9767   ExprResult LHSResult = LHS, RHSResult = RHS;
9768   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9769                                                  IsCompAssign);
9770   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9771     return QualType();
9772   LHS = LHSResult.get();
9773   RHS = RHSResult.get();
9774
9775   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9776     return compType;
9777   return InvalidOperands(Loc, LHS, RHS);
9778 }
9779
9780 // C99 6.5.[13,14]
9781 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9782                                            SourceLocation Loc,
9783                                            BinaryOperatorKind Opc) {
9784   // Check vector operands differently.
9785   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9786     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9787   
9788   // Diagnose cases where the user write a logical and/or but probably meant a
9789   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9790   // is a constant.
9791   if (LHS.get()->getType()->isIntegerType() &&
9792       !LHS.get()->getType()->isBooleanType() &&
9793       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9794       // Don't warn in macros or template instantiations.
9795       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9796     // If the RHS can be constant folded, and if it constant folds to something
9797     // that isn't 0 or 1 (which indicate a potential logical operation that
9798     // happened to fold to true/false) then warn.
9799     // Parens on the RHS are ignored.
9800     llvm::APSInt Result;
9801     if (RHS.get()->EvaluateAsInt(Result, Context))
9802       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9803            !RHS.get()->getExprLoc().isMacroID()) ||
9804           (Result != 0 && Result != 1)) {
9805         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9806           << RHS.get()->getSourceRange()
9807           << (Opc == BO_LAnd ? "&&" : "||");
9808         // Suggest replacing the logical operator with the bitwise version
9809         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9810             << (Opc == BO_LAnd ? "&" : "|")
9811             << FixItHint::CreateReplacement(SourceRange(
9812                                                  Loc, getLocForEndOfToken(Loc)),
9813                                             Opc == BO_LAnd ? "&" : "|");
9814         if (Opc == BO_LAnd)
9815           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9816           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9817               << FixItHint::CreateRemoval(
9818                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9819                               RHS.get()->getLocEnd()));
9820       }
9821   }
9822
9823   if (!Context.getLangOpts().CPlusPlus) {
9824     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9825     // not operate on the built-in scalar and vector float types.
9826     if (Context.getLangOpts().OpenCL &&
9827         Context.getLangOpts().OpenCLVersion < 120) {
9828       if (LHS.get()->getType()->isFloatingType() ||
9829           RHS.get()->getType()->isFloatingType())
9830         return InvalidOperands(Loc, LHS, RHS);
9831     }
9832
9833     LHS = UsualUnaryConversions(LHS.get());
9834     if (LHS.isInvalid())
9835       return QualType();
9836
9837     RHS = UsualUnaryConversions(RHS.get());
9838     if (RHS.isInvalid())
9839       return QualType();
9840
9841     if (!LHS.get()->getType()->isScalarType() ||
9842         !RHS.get()->getType()->isScalarType())
9843       return InvalidOperands(Loc, LHS, RHS);
9844
9845     return Context.IntTy;
9846   }
9847
9848   // The following is safe because we only use this method for
9849   // non-overloadable operands.
9850
9851   // C++ [expr.log.and]p1
9852   // C++ [expr.log.or]p1
9853   // The operands are both contextually converted to type bool.
9854   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9855   if (LHSRes.isInvalid())
9856     return InvalidOperands(Loc, LHS, RHS);
9857   LHS = LHSRes;
9858
9859   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9860   if (RHSRes.isInvalid())
9861     return InvalidOperands(Loc, LHS, RHS);
9862   RHS = RHSRes;
9863
9864   // C++ [expr.log.and]p2
9865   // C++ [expr.log.or]p2
9866   // The result is a bool.
9867   return Context.BoolTy;
9868 }
9869
9870 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9871   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9872   if (!ME) return false;
9873   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9874   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9875       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9876   if (!Base) return false;
9877   return Base->getMethodDecl() != nullptr;
9878 }
9879
9880 /// Is the given expression (which must be 'const') a reference to a
9881 /// variable which was originally non-const, but which has become
9882 /// 'const' due to being captured within a block?
9883 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9884 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9885   assert(E->isLValue() && E->getType().isConstQualified());
9886   E = E->IgnoreParens();
9887
9888   // Must be a reference to a declaration from an enclosing scope.
9889   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9890   if (!DRE) return NCCK_None;
9891   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9892
9893   // The declaration must be a variable which is not declared 'const'.
9894   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9895   if (!var) return NCCK_None;
9896   if (var->getType().isConstQualified()) return NCCK_None;
9897   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9898
9899   // Decide whether the first capture was for a block or a lambda.
9900   DeclContext *DC = S.CurContext, *Prev = nullptr;
9901   // Decide whether the first capture was for a block or a lambda.
9902   while (DC) {
9903     // For init-capture, it is possible that the variable belongs to the
9904     // template pattern of the current context.
9905     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9906       if (var->isInitCapture() &&
9907           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9908         break;
9909     if (DC == var->getDeclContext())
9910       break;
9911     Prev = DC;
9912     DC = DC->getParent();
9913   }
9914   // Unless we have an init-capture, we've gone one step too far.
9915   if (!var->isInitCapture())
9916     DC = Prev;
9917   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9918 }
9919
9920 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9921   Ty = Ty.getNonReferenceType();
9922   if (IsDereference && Ty->isPointerType())
9923     Ty = Ty->getPointeeType();
9924   return !Ty.isConstQualified();
9925 }
9926
9927 /// Emit the "read-only variable not assignable" error and print notes to give
9928 /// more information about why the variable is not assignable, such as pointing
9929 /// to the declaration of a const variable, showing that a method is const, or
9930 /// that the function is returning a const reference.
9931 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9932                                     SourceLocation Loc) {
9933   // Update err_typecheck_assign_const and note_typecheck_assign_const
9934   // when this enum is changed.
9935   enum {
9936     ConstFunction,
9937     ConstVariable,
9938     ConstMember,
9939     ConstMethod,
9940     ConstUnknown,  // Keep as last element
9941   };
9942
9943   SourceRange ExprRange = E->getSourceRange();
9944
9945   // Only emit one error on the first const found.  All other consts will emit
9946   // a note to the error.
9947   bool DiagnosticEmitted = false;
9948
9949   // Track if the current expression is the result of a dereference, and if the
9950   // next checked expression is the result of a dereference.
9951   bool IsDereference = false;
9952   bool NextIsDereference = false;
9953
9954   // Loop to process MemberExpr chains.
9955   while (true) {
9956     IsDereference = NextIsDereference;
9957
9958     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9959     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9960       NextIsDereference = ME->isArrow();
9961       const ValueDecl *VD = ME->getMemberDecl();
9962       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9963         // Mutable fields can be modified even if the class is const.
9964         if (Field->isMutable()) {
9965           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9966           break;
9967         }
9968
9969         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9970           if (!DiagnosticEmitted) {
9971             S.Diag(Loc, diag::err_typecheck_assign_const)
9972                 << ExprRange << ConstMember << false /*static*/ << Field
9973                 << Field->getType();
9974             DiagnosticEmitted = true;
9975           }
9976           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9977               << ConstMember << false /*static*/ << Field << Field->getType()
9978               << Field->getSourceRange();
9979         }
9980         E = ME->getBase();
9981         continue;
9982       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9983         if (VDecl->getType().isConstQualified()) {
9984           if (!DiagnosticEmitted) {
9985             S.Diag(Loc, diag::err_typecheck_assign_const)
9986                 << ExprRange << ConstMember << true /*static*/ << VDecl
9987                 << VDecl->getType();
9988             DiagnosticEmitted = true;
9989           }
9990           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9991               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9992               << VDecl->getSourceRange();
9993         }
9994         // Static fields do not inherit constness from parents.
9995         break;
9996       }
9997       break;
9998     } // End MemberExpr
9999     break;
10000   }
10001
10002   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10003     // Function calls
10004     const FunctionDecl *FD = CE->getDirectCallee();
10005     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10006       if (!DiagnosticEmitted) {
10007         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10008                                                       << ConstFunction << FD;
10009         DiagnosticEmitted = true;
10010       }
10011       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10012              diag::note_typecheck_assign_const)
10013           << ConstFunction << FD << FD->getReturnType()
10014           << FD->getReturnTypeSourceRange();
10015     }
10016   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10017     // Point to variable declaration.
10018     if (const ValueDecl *VD = DRE->getDecl()) {
10019       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10020         if (!DiagnosticEmitted) {
10021           S.Diag(Loc, diag::err_typecheck_assign_const)
10022               << ExprRange << ConstVariable << VD << VD->getType();
10023           DiagnosticEmitted = true;
10024         }
10025         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10026             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10027       }
10028     }
10029   } else if (isa<CXXThisExpr>(E)) {
10030     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10031       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10032         if (MD->isConst()) {
10033           if (!DiagnosticEmitted) {
10034             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10035                                                           << ConstMethod << MD;
10036             DiagnosticEmitted = true;
10037           }
10038           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10039               << ConstMethod << MD << MD->getSourceRange();
10040         }
10041       }
10042     }
10043   }
10044
10045   if (DiagnosticEmitted)
10046     return;
10047
10048   // Can't determine a more specific message, so display the generic error.
10049   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10050 }
10051
10052 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10053 /// emit an error and return true.  If so, return false.
10054 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10055   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10056
10057   S.CheckShadowingDeclModification(E, Loc);
10058
10059   SourceLocation OrigLoc = Loc;
10060   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10061                                                               &Loc);
10062   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10063     IsLV = Expr::MLV_InvalidMessageExpression;
10064   if (IsLV == Expr::MLV_Valid)
10065     return false;
10066
10067   unsigned DiagID = 0;
10068   bool NeedType = false;
10069   switch (IsLV) { // C99 6.5.16p2
10070   case Expr::MLV_ConstQualified:
10071     // Use a specialized diagnostic when we're assigning to an object
10072     // from an enclosing function or block.
10073     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10074       if (NCCK == NCCK_Block)
10075         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10076       else
10077         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10078       break;
10079     }
10080
10081     // In ARC, use some specialized diagnostics for occasions where we
10082     // infer 'const'.  These are always pseudo-strong variables.
10083     if (S.getLangOpts().ObjCAutoRefCount) {
10084       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10085       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10086         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10087
10088         // Use the normal diagnostic if it's pseudo-__strong but the
10089         // user actually wrote 'const'.
10090         if (var->isARCPseudoStrong() &&
10091             (!var->getTypeSourceInfo() ||
10092              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10093           // There are two pseudo-strong cases:
10094           //  - self
10095           ObjCMethodDecl *method = S.getCurMethodDecl();
10096           if (method && var == method->getSelfDecl())
10097             DiagID = method->isClassMethod()
10098               ? diag::err_typecheck_arc_assign_self_class_method
10099               : diag::err_typecheck_arc_assign_self;
10100
10101           //  - fast enumeration variables
10102           else
10103             DiagID = diag::err_typecheck_arr_assign_enumeration;
10104
10105           SourceRange Assign;
10106           if (Loc != OrigLoc)
10107             Assign = SourceRange(OrigLoc, OrigLoc);
10108           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10109           // We need to preserve the AST regardless, so migration tool
10110           // can do its job.
10111           return false;
10112         }
10113       }
10114     }
10115
10116     // If none of the special cases above are triggered, then this is a
10117     // simple const assignment.
10118     if (DiagID == 0) {
10119       DiagnoseConstAssignment(S, E, Loc);
10120       return true;
10121     }
10122
10123     break;
10124   case Expr::MLV_ConstAddrSpace:
10125     DiagnoseConstAssignment(S, E, Loc);
10126     return true;
10127   case Expr::MLV_ArrayType:
10128   case Expr::MLV_ArrayTemporary:
10129     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10130     NeedType = true;
10131     break;
10132   case Expr::MLV_NotObjectType:
10133     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10134     NeedType = true;
10135     break;
10136   case Expr::MLV_LValueCast:
10137     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10138     break;
10139   case Expr::MLV_Valid:
10140     llvm_unreachable("did not take early return for MLV_Valid");
10141   case Expr::MLV_InvalidExpression:
10142   case Expr::MLV_MemberFunction:
10143   case Expr::MLV_ClassTemporary:
10144     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10145     break;
10146   case Expr::MLV_IncompleteType:
10147   case Expr::MLV_IncompleteVoidType:
10148     return S.RequireCompleteType(Loc, E->getType(),
10149              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10150   case Expr::MLV_DuplicateVectorComponents:
10151     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10152     break;
10153   case Expr::MLV_NoSetterProperty:
10154     llvm_unreachable("readonly properties should be processed differently");
10155   case Expr::MLV_InvalidMessageExpression:
10156     DiagID = diag::err_readonly_message_assignment;
10157     break;
10158   case Expr::MLV_SubObjCPropertySetting:
10159     DiagID = diag::err_no_subobject_property_setting;
10160     break;
10161   }
10162
10163   SourceRange Assign;
10164   if (Loc != OrigLoc)
10165     Assign = SourceRange(OrigLoc, OrigLoc);
10166   if (NeedType)
10167     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10168   else
10169     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10170   return true;
10171 }
10172
10173 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10174                                          SourceLocation Loc,
10175                                          Sema &Sema) {
10176   // C / C++ fields
10177   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10178   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10179   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10180     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10181       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10182   }
10183
10184   // Objective-C instance variables
10185   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10186   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10187   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10188     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10189     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10190     if (RL && RR && RL->getDecl() == RR->getDecl())
10191       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10192   }
10193 }
10194
10195 // C99 6.5.16.1
10196 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10197                                        SourceLocation Loc,
10198                                        QualType CompoundType) {
10199   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10200
10201   // Verify that LHS is a modifiable lvalue, and emit error if not.
10202   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10203     return QualType();
10204
10205   QualType LHSType = LHSExpr->getType();
10206   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10207                                              CompoundType;
10208   // OpenCL v1.2 s6.1.1.1 p2:
10209   // The half data type can only be used to declare a pointer to a buffer that
10210   // contains half values
10211   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10212     LHSType->isHalfType()) {
10213     Diag(Loc, diag::err_opencl_half_load_store) << 1
10214         << LHSType.getUnqualifiedType();
10215     return QualType();
10216   }
10217     
10218   AssignConvertType ConvTy;
10219   if (CompoundType.isNull()) {
10220     Expr *RHSCheck = RHS.get();
10221
10222     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10223
10224     QualType LHSTy(LHSType);
10225     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10226     if (RHS.isInvalid())
10227       return QualType();
10228     // Special case of NSObject attributes on c-style pointer types.
10229     if (ConvTy == IncompatiblePointer &&
10230         ((Context.isObjCNSObjectType(LHSType) &&
10231           RHSType->isObjCObjectPointerType()) ||
10232          (Context.isObjCNSObjectType(RHSType) &&
10233           LHSType->isObjCObjectPointerType())))
10234       ConvTy = Compatible;
10235
10236     if (ConvTy == Compatible &&
10237         LHSType->isObjCObjectType())
10238         Diag(Loc, diag::err_objc_object_assignment)
10239           << LHSType;
10240
10241     // If the RHS is a unary plus or minus, check to see if they = and + are
10242     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10243     // instead of "x += 4".
10244     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10245       RHSCheck = ICE->getSubExpr();
10246     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10247       if ((UO->getOpcode() == UO_Plus ||
10248            UO->getOpcode() == UO_Minus) &&
10249           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10250           // Only if the two operators are exactly adjacent.
10251           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10252           // And there is a space or other character before the subexpr of the
10253           // unary +/-.  We don't want to warn on "x=-1".
10254           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10255           UO->getSubExpr()->getLocStart().isFileID()) {
10256         Diag(Loc, diag::warn_not_compound_assign)
10257           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10258           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10259       }
10260     }
10261
10262     if (ConvTy == Compatible) {
10263       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10264         // Warn about retain cycles where a block captures the LHS, but
10265         // not if the LHS is a simple variable into which the block is
10266         // being stored...unless that variable can be captured by reference!
10267         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10268         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10269         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10270           checkRetainCycles(LHSExpr, RHS.get());
10271
10272         // It is safe to assign a weak reference into a strong variable.
10273         // Although this code can still have problems:
10274         //   id x = self.weakProp;
10275         //   id y = self.weakProp;
10276         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10277         // paths through the function. This should be revisited if
10278         // -Wrepeated-use-of-weak is made flow-sensitive.
10279         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10280                              RHS.get()->getLocStart()))
10281           getCurFunction()->markSafeWeakUse(RHS.get());
10282
10283       } else if (getLangOpts().ObjCAutoRefCount) {
10284         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10285       }
10286     }
10287   } else {
10288     // Compound assignment "x += y"
10289     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10290   }
10291
10292   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10293                                RHS.get(), AA_Assigning))
10294     return QualType();
10295
10296   CheckForNullPointerDereference(*this, LHSExpr);
10297
10298   // C99 6.5.16p3: The type of an assignment expression is the type of the
10299   // left operand unless the left operand has qualified type, in which case
10300   // it is the unqualified version of the type of the left operand.
10301   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10302   // is converted to the type of the assignment expression (above).
10303   // C++ 5.17p1: the type of the assignment expression is that of its left
10304   // operand.
10305   return (getLangOpts().CPlusPlus
10306           ? LHSType : LHSType.getUnqualifiedType());
10307 }
10308
10309 // Only ignore explicit casts to void.
10310 static bool IgnoreCommaOperand(const Expr *E) {
10311   E = E->IgnoreParens();
10312
10313   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10314     if (CE->getCastKind() == CK_ToVoid) {
10315       return true;
10316     }
10317   }
10318
10319   return false;
10320 }
10321
10322 // Look for instances where it is likely the comma operator is confused with
10323 // another operator.  There is a whitelist of acceptable expressions for the
10324 // left hand side of the comma operator, otherwise emit a warning.
10325 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10326   // No warnings in macros
10327   if (Loc.isMacroID())
10328     return;
10329
10330   // Don't warn in template instantiations.
10331   if (!ActiveTemplateInstantiations.empty())
10332     return;
10333
10334   // Scope isn't fine-grained enough to whitelist the specific cases, so
10335   // instead, skip more than needed, then call back into here with the
10336   // CommaVisitor in SemaStmt.cpp.
10337   // The whitelisted locations are the initialization and increment portions
10338   // of a for loop.  The additional checks are on the condition of
10339   // if statements, do/while loops, and for loops.
10340   const unsigned ForIncrementFlags =
10341       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10342   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10343   const unsigned ScopeFlags = getCurScope()->getFlags();
10344   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10345       (ScopeFlags & ForInitFlags) == ForInitFlags)
10346     return;
10347
10348   // If there are multiple comma operators used together, get the RHS of the
10349   // of the comma operator as the LHS.
10350   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10351     if (BO->getOpcode() != BO_Comma)
10352       break;
10353     LHS = BO->getRHS();
10354   }
10355
10356   // Only allow some expressions on LHS to not warn.
10357   if (IgnoreCommaOperand(LHS))
10358     return;
10359
10360   Diag(Loc, diag::warn_comma_operator);
10361   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10362       << LHS->getSourceRange()
10363       << FixItHint::CreateInsertion(LHS->getLocStart(),
10364                                     LangOpts.CPlusPlus ? "static_cast<void>("
10365                                                        : "(void)(")
10366       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10367                                     ")");
10368 }
10369
10370 // C99 6.5.17
10371 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10372                                    SourceLocation Loc) {
10373   LHS = S.CheckPlaceholderExpr(LHS.get());
10374   RHS = S.CheckPlaceholderExpr(RHS.get());
10375   if (LHS.isInvalid() || RHS.isInvalid())
10376     return QualType();
10377
10378   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10379   // operands, but not unary promotions.
10380   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10381
10382   // So we treat the LHS as a ignored value, and in C++ we allow the
10383   // containing site to determine what should be done with the RHS.
10384   LHS = S.IgnoredValueConversions(LHS.get());
10385   if (LHS.isInvalid())
10386     return QualType();
10387
10388   S.DiagnoseUnusedExprResult(LHS.get());
10389
10390   if (!S.getLangOpts().CPlusPlus) {
10391     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10392     if (RHS.isInvalid())
10393       return QualType();
10394     if (!RHS.get()->getType()->isVoidType())
10395       S.RequireCompleteType(Loc, RHS.get()->getType(),
10396                             diag::err_incomplete_type);
10397   }
10398
10399   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10400     S.DiagnoseCommaOperator(LHS.get(), Loc);
10401
10402   return RHS.get()->getType();
10403 }
10404
10405 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10406 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10407 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10408                                                ExprValueKind &VK,
10409                                                ExprObjectKind &OK,
10410                                                SourceLocation OpLoc,
10411                                                bool IsInc, bool IsPrefix) {
10412   if (Op->isTypeDependent())
10413     return S.Context.DependentTy;
10414
10415   QualType ResType = Op->getType();
10416   // Atomic types can be used for increment / decrement where the non-atomic
10417   // versions can, so ignore the _Atomic() specifier for the purpose of
10418   // checking.
10419   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10420     ResType = ResAtomicType->getValueType();
10421
10422   assert(!ResType.isNull() && "no type for increment/decrement expression");
10423
10424   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10425     // Decrement of bool is not allowed.
10426     if (!IsInc) {
10427       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10428       return QualType();
10429     }
10430     // Increment of bool sets it to true, but is deprecated.
10431     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10432                                               : diag::warn_increment_bool)
10433       << Op->getSourceRange();
10434   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10435     // Error on enum increments and decrements in C++ mode
10436     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10437     return QualType();
10438   } else if (ResType->isRealType()) {
10439     // OK!
10440   } else if (ResType->isPointerType()) {
10441     // C99 6.5.2.4p2, 6.5.6p2
10442     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10443       return QualType();
10444   } else if (ResType->isObjCObjectPointerType()) {
10445     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10446     // Otherwise, we just need a complete type.
10447     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10448         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10449       return QualType();    
10450   } else if (ResType->isAnyComplexType()) {
10451     // C99 does not support ++/-- on complex types, we allow as an extension.
10452     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10453       << ResType << Op->getSourceRange();
10454   } else if (ResType->isPlaceholderType()) {
10455     ExprResult PR = S.CheckPlaceholderExpr(Op);
10456     if (PR.isInvalid()) return QualType();
10457     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10458                                           IsInc, IsPrefix);
10459   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10460     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10461   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10462              (ResType->getAs<VectorType>()->getVectorKind() !=
10463               VectorType::AltiVecBool)) {
10464     // The z vector extensions allow ++ and -- for non-bool vectors.
10465   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10466             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10467     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10468   } else {
10469     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10470       << ResType << int(IsInc) << Op->getSourceRange();
10471     return QualType();
10472   }
10473   // At this point, we know we have a real, complex or pointer type.
10474   // Now make sure the operand is a modifiable lvalue.
10475   if (CheckForModifiableLvalue(Op, OpLoc, S))
10476     return QualType();
10477   // In C++, a prefix increment is the same type as the operand. Otherwise
10478   // (in C or with postfix), the increment is the unqualified type of the
10479   // operand.
10480   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10481     VK = VK_LValue;
10482     OK = Op->getObjectKind();
10483     return ResType;
10484   } else {
10485     VK = VK_RValue;
10486     return ResType.getUnqualifiedType();
10487   }
10488 }
10489   
10490
10491 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10492 /// This routine allows us to typecheck complex/recursive expressions
10493 /// where the declaration is needed for type checking. We only need to
10494 /// handle cases when the expression references a function designator
10495 /// or is an lvalue. Here are some examples:
10496 ///  - &(x) => x
10497 ///  - &*****f => f for f a function designator.
10498 ///  - &s.xx => s
10499 ///  - &s.zz[1].yy -> s, if zz is an array
10500 ///  - *(x + 1) -> x, if x is an array
10501 ///  - &"123"[2] -> 0
10502 ///  - & __real__ x -> x
10503 static ValueDecl *getPrimaryDecl(Expr *E) {
10504   switch (E->getStmtClass()) {
10505   case Stmt::DeclRefExprClass:
10506     return cast<DeclRefExpr>(E)->getDecl();
10507   case Stmt::MemberExprClass:
10508     // If this is an arrow operator, the address is an offset from
10509     // the base's value, so the object the base refers to is
10510     // irrelevant.
10511     if (cast<MemberExpr>(E)->isArrow())
10512       return nullptr;
10513     // Otherwise, the expression refers to a part of the base
10514     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10515   case Stmt::ArraySubscriptExprClass: {
10516     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10517     // promotion of register arrays earlier.
10518     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10519     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10520       if (ICE->getSubExpr()->getType()->isArrayType())
10521         return getPrimaryDecl(ICE->getSubExpr());
10522     }
10523     return nullptr;
10524   }
10525   case Stmt::UnaryOperatorClass: {
10526     UnaryOperator *UO = cast<UnaryOperator>(E);
10527
10528     switch(UO->getOpcode()) {
10529     case UO_Real:
10530     case UO_Imag:
10531     case UO_Extension:
10532       return getPrimaryDecl(UO->getSubExpr());
10533     default:
10534       return nullptr;
10535     }
10536   }
10537   case Stmt::ParenExprClass:
10538     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10539   case Stmt::ImplicitCastExprClass:
10540     // If the result of an implicit cast is an l-value, we care about
10541     // the sub-expression; otherwise, the result here doesn't matter.
10542     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10543   default:
10544     return nullptr;
10545   }
10546 }
10547
10548 namespace {
10549   enum {
10550     AO_Bit_Field = 0,
10551     AO_Vector_Element = 1,
10552     AO_Property_Expansion = 2,
10553     AO_Register_Variable = 3,
10554     AO_No_Error = 4
10555   };
10556 }
10557 /// \brief Diagnose invalid operand for address of operations.
10558 ///
10559 /// \param Type The type of operand which cannot have its address taken.
10560 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10561                                          Expr *E, unsigned Type) {
10562   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10563 }
10564
10565 /// CheckAddressOfOperand - The operand of & must be either a function
10566 /// designator or an lvalue designating an object. If it is an lvalue, the
10567 /// object cannot be declared with storage class register or be a bit field.
10568 /// Note: The usual conversions are *not* applied to the operand of the &
10569 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10570 /// In C++, the operand might be an overloaded function name, in which case
10571 /// we allow the '&' but retain the overloaded-function type.
10572 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10573   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10574     if (PTy->getKind() == BuiltinType::Overload) {
10575       Expr *E = OrigOp.get()->IgnoreParens();
10576       if (!isa<OverloadExpr>(E)) {
10577         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10578         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10579           << OrigOp.get()->getSourceRange();
10580         return QualType();
10581       }
10582
10583       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10584       if (isa<UnresolvedMemberExpr>(Ovl))
10585         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10586           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10587             << OrigOp.get()->getSourceRange();
10588           return QualType();
10589         }
10590
10591       return Context.OverloadTy;
10592     }
10593
10594     if (PTy->getKind() == BuiltinType::UnknownAny)
10595       return Context.UnknownAnyTy;
10596
10597     if (PTy->getKind() == BuiltinType::BoundMember) {
10598       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10599         << OrigOp.get()->getSourceRange();
10600       return QualType();
10601     }
10602
10603     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10604     if (OrigOp.isInvalid()) return QualType();
10605   }
10606
10607   if (OrigOp.get()->isTypeDependent())
10608     return Context.DependentTy;
10609
10610   assert(!OrigOp.get()->getType()->isPlaceholderType());
10611
10612   // Make sure to ignore parentheses in subsequent checks
10613   Expr *op = OrigOp.get()->IgnoreParens();
10614
10615   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10616   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10617     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10618     return QualType();
10619   }
10620
10621   if (getLangOpts().C99) {
10622     // Implement C99-only parts of addressof rules.
10623     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10624       if (uOp->getOpcode() == UO_Deref)
10625         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10626         // (assuming the deref expression is valid).
10627         return uOp->getSubExpr()->getType();
10628     }
10629     // Technically, there should be a check for array subscript
10630     // expressions here, but the result of one is always an lvalue anyway.
10631   }
10632   ValueDecl *dcl = getPrimaryDecl(op);
10633
10634   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10635     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10636                                            op->getLocStart()))
10637       return QualType();
10638
10639   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10640   unsigned AddressOfError = AO_No_Error;
10641
10642   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10643     bool sfinae = (bool)isSFINAEContext();
10644     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10645                                   : diag::ext_typecheck_addrof_temporary)
10646       << op->getType() << op->getSourceRange();
10647     if (sfinae)
10648       return QualType();
10649     // Materialize the temporary as an lvalue so that we can take its address.
10650     OrigOp = op =
10651         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10652   } else if (isa<ObjCSelectorExpr>(op)) {
10653     return Context.getPointerType(op->getType());
10654   } else if (lval == Expr::LV_MemberFunction) {
10655     // If it's an instance method, make a member pointer.
10656     // The expression must have exactly the form &A::foo.
10657
10658     // If the underlying expression isn't a decl ref, give up.
10659     if (!isa<DeclRefExpr>(op)) {
10660       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10661         << OrigOp.get()->getSourceRange();
10662       return QualType();
10663     }
10664     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10665     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10666
10667     // The id-expression was parenthesized.
10668     if (OrigOp.get() != DRE) {
10669       Diag(OpLoc, diag::err_parens_pointer_member_function)
10670         << OrigOp.get()->getSourceRange();
10671
10672     // The method was named without a qualifier.
10673     } else if (!DRE->getQualifier()) {
10674       if (MD->getParent()->getName().empty())
10675         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10676           << op->getSourceRange();
10677       else {
10678         SmallString<32> Str;
10679         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10680         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10681           << op->getSourceRange()
10682           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10683       }
10684     }
10685
10686     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10687     if (isa<CXXDestructorDecl>(MD))
10688       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10689
10690     QualType MPTy = Context.getMemberPointerType(
10691         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10692     // Under the MS ABI, lock down the inheritance model now.
10693     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10694       (void)isCompleteType(OpLoc, MPTy);
10695     return MPTy;
10696   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10697     // C99 6.5.3.2p1
10698     // The operand must be either an l-value or a function designator
10699     if (!op->getType()->isFunctionType()) {
10700       // Use a special diagnostic for loads from property references.
10701       if (isa<PseudoObjectExpr>(op)) {
10702         AddressOfError = AO_Property_Expansion;
10703       } else {
10704         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10705           << op->getType() << op->getSourceRange();
10706         return QualType();
10707       }
10708     }
10709   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10710     // The operand cannot be a bit-field
10711     AddressOfError = AO_Bit_Field;
10712   } else if (op->getObjectKind() == OK_VectorComponent) {
10713     // The operand cannot be an element of a vector
10714     AddressOfError = AO_Vector_Element;
10715   } else if (dcl) { // C99 6.5.3.2p1
10716     // We have an lvalue with a decl. Make sure the decl is not declared
10717     // with the register storage-class specifier.
10718     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10719       // in C++ it is not error to take address of a register
10720       // variable (c++03 7.1.1P3)
10721       if (vd->getStorageClass() == SC_Register &&
10722           !getLangOpts().CPlusPlus) {
10723         AddressOfError = AO_Register_Variable;
10724       }
10725     } else if (isa<MSPropertyDecl>(dcl)) {
10726       AddressOfError = AO_Property_Expansion;
10727     } else if (isa<FunctionTemplateDecl>(dcl)) {
10728       return Context.OverloadTy;
10729     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10730       // Okay: we can take the address of a field.
10731       // Could be a pointer to member, though, if there is an explicit
10732       // scope qualifier for the class.
10733       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10734         DeclContext *Ctx = dcl->getDeclContext();
10735         if (Ctx && Ctx->isRecord()) {
10736           if (dcl->getType()->isReferenceType()) {
10737             Diag(OpLoc,
10738                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10739               << dcl->getDeclName() << dcl->getType();
10740             return QualType();
10741           }
10742
10743           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10744             Ctx = Ctx->getParent();
10745
10746           QualType MPTy = Context.getMemberPointerType(
10747               op->getType(),
10748               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10749           // Under the MS ABI, lock down the inheritance model now.
10750           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10751             (void)isCompleteType(OpLoc, MPTy);
10752           return MPTy;
10753         }
10754       }
10755     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10756                !isa<BindingDecl>(dcl))
10757       llvm_unreachable("Unknown/unexpected decl type");
10758   }
10759
10760   if (AddressOfError != AO_No_Error) {
10761     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10762     return QualType();
10763   }
10764
10765   if (lval == Expr::LV_IncompleteVoidType) {
10766     // Taking the address of a void variable is technically illegal, but we
10767     // allow it in cases which are otherwise valid.
10768     // Example: "extern void x; void* y = &x;".
10769     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10770   }
10771
10772   // If the operand has type "type", the result has type "pointer to type".
10773   if (op->getType()->isObjCObjectType())
10774     return Context.getObjCObjectPointerType(op->getType());
10775
10776   CheckAddressOfPackedMember(op);
10777
10778   return Context.getPointerType(op->getType());
10779 }
10780
10781 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10782   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10783   if (!DRE)
10784     return;
10785   const Decl *D = DRE->getDecl();
10786   if (!D)
10787     return;
10788   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10789   if (!Param)
10790     return;
10791   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10792     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10793       return;
10794   if (FunctionScopeInfo *FD = S.getCurFunction())
10795     if (!FD->ModifiedNonNullParams.count(Param))
10796       FD->ModifiedNonNullParams.insert(Param);
10797 }
10798
10799 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10800 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10801                                         SourceLocation OpLoc) {
10802   if (Op->isTypeDependent())
10803     return S.Context.DependentTy;
10804
10805   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10806   if (ConvResult.isInvalid())
10807     return QualType();
10808   Op = ConvResult.get();
10809   QualType OpTy = Op->getType();
10810   QualType Result;
10811
10812   if (isa<CXXReinterpretCastExpr>(Op)) {
10813     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10814     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10815                                      Op->getSourceRange());
10816   }
10817
10818   if (const PointerType *PT = OpTy->getAs<PointerType>())
10819   {
10820     Result = PT->getPointeeType();
10821   }
10822   else if (const ObjCObjectPointerType *OPT =
10823              OpTy->getAs<ObjCObjectPointerType>())
10824     Result = OPT->getPointeeType();
10825   else {
10826     ExprResult PR = S.CheckPlaceholderExpr(Op);
10827     if (PR.isInvalid()) return QualType();
10828     if (PR.get() != Op)
10829       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10830   }
10831
10832   if (Result.isNull()) {
10833     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10834       << OpTy << Op->getSourceRange();
10835     return QualType();
10836   }
10837
10838   // Note that per both C89 and C99, indirection is always legal, even if Result
10839   // is an incomplete type or void.  It would be possible to warn about
10840   // dereferencing a void pointer, but it's completely well-defined, and such a
10841   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10842   // for pointers to 'void' but is fine for any other pointer type:
10843   //
10844   // C++ [expr.unary.op]p1:
10845   //   [...] the expression to which [the unary * operator] is applied shall
10846   //   be a pointer to an object type, or a pointer to a function type
10847   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10848     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10849       << OpTy << Op->getSourceRange();
10850
10851   // Dereferences are usually l-values...
10852   VK = VK_LValue;
10853
10854   // ...except that certain expressions are never l-values in C.
10855   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10856     VK = VK_RValue;
10857   
10858   return Result;
10859 }
10860
10861 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10862   BinaryOperatorKind Opc;
10863   switch (Kind) {
10864   default: llvm_unreachable("Unknown binop!");
10865   case tok::periodstar:           Opc = BO_PtrMemD; break;
10866   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10867   case tok::star:                 Opc = BO_Mul; break;
10868   case tok::slash:                Opc = BO_Div; break;
10869   case tok::percent:              Opc = BO_Rem; break;
10870   case tok::plus:                 Opc = BO_Add; break;
10871   case tok::minus:                Opc = BO_Sub; break;
10872   case tok::lessless:             Opc = BO_Shl; break;
10873   case tok::greatergreater:       Opc = BO_Shr; break;
10874   case tok::lessequal:            Opc = BO_LE; break;
10875   case tok::less:                 Opc = BO_LT; break;
10876   case tok::greaterequal:         Opc = BO_GE; break;
10877   case tok::greater:              Opc = BO_GT; break;
10878   case tok::exclaimequal:         Opc = BO_NE; break;
10879   case tok::equalequal:           Opc = BO_EQ; break;
10880   case tok::amp:                  Opc = BO_And; break;
10881   case tok::caret:                Opc = BO_Xor; break;
10882   case tok::pipe:                 Opc = BO_Or; break;
10883   case tok::ampamp:               Opc = BO_LAnd; break;
10884   case tok::pipepipe:             Opc = BO_LOr; break;
10885   case tok::equal:                Opc = BO_Assign; break;
10886   case tok::starequal:            Opc = BO_MulAssign; break;
10887   case tok::slashequal:           Opc = BO_DivAssign; break;
10888   case tok::percentequal:         Opc = BO_RemAssign; break;
10889   case tok::plusequal:            Opc = BO_AddAssign; break;
10890   case tok::minusequal:           Opc = BO_SubAssign; break;
10891   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10892   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10893   case tok::ampequal:             Opc = BO_AndAssign; break;
10894   case tok::caretequal:           Opc = BO_XorAssign; break;
10895   case tok::pipeequal:            Opc = BO_OrAssign; break;
10896   case tok::comma:                Opc = BO_Comma; break;
10897   }
10898   return Opc;
10899 }
10900
10901 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10902   tok::TokenKind Kind) {
10903   UnaryOperatorKind Opc;
10904   switch (Kind) {
10905   default: llvm_unreachable("Unknown unary op!");
10906   case tok::plusplus:     Opc = UO_PreInc; break;
10907   case tok::minusminus:   Opc = UO_PreDec; break;
10908   case tok::amp:          Opc = UO_AddrOf; break;
10909   case tok::star:         Opc = UO_Deref; break;
10910   case tok::plus:         Opc = UO_Plus; break;
10911   case tok::minus:        Opc = UO_Minus; break;
10912   case tok::tilde:        Opc = UO_Not; break;
10913   case tok::exclaim:      Opc = UO_LNot; break;
10914   case tok::kw___real:    Opc = UO_Real; break;
10915   case tok::kw___imag:    Opc = UO_Imag; break;
10916   case tok::kw___extension__: Opc = UO_Extension; break;
10917   }
10918   return Opc;
10919 }
10920
10921 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10922 /// This warning is only emitted for builtin assignment operations. It is also
10923 /// suppressed in the event of macro expansions.
10924 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10925                                    SourceLocation OpLoc) {
10926   if (!S.ActiveTemplateInstantiations.empty())
10927     return;
10928   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10929     return;
10930   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10931   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10932   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10933   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10934   if (!LHSDeclRef || !RHSDeclRef ||
10935       LHSDeclRef->getLocation().isMacroID() ||
10936       RHSDeclRef->getLocation().isMacroID())
10937     return;
10938   const ValueDecl *LHSDecl =
10939     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10940   const ValueDecl *RHSDecl =
10941     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10942   if (LHSDecl != RHSDecl)
10943     return;
10944   if (LHSDecl->getType().isVolatileQualified())
10945     return;
10946   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10947     if (RefTy->getPointeeType().isVolatileQualified())
10948       return;
10949
10950   S.Diag(OpLoc, diag::warn_self_assignment)
10951       << LHSDeclRef->getType()
10952       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10953 }
10954
10955 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10956 /// is usually indicative of introspection within the Objective-C pointer.
10957 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10958                                           SourceLocation OpLoc) {
10959   if (!S.getLangOpts().ObjC1)
10960     return;
10961
10962   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10963   const Expr *LHS = L.get();
10964   const Expr *RHS = R.get();
10965
10966   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10967     ObjCPointerExpr = LHS;
10968     OtherExpr = RHS;
10969   }
10970   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10971     ObjCPointerExpr = RHS;
10972     OtherExpr = LHS;
10973   }
10974
10975   // This warning is deliberately made very specific to reduce false
10976   // positives with logic that uses '&' for hashing.  This logic mainly
10977   // looks for code trying to introspect into tagged pointers, which
10978   // code should generally never do.
10979   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10980     unsigned Diag = diag::warn_objc_pointer_masking;
10981     // Determine if we are introspecting the result of performSelectorXXX.
10982     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10983     // Special case messages to -performSelector and friends, which
10984     // can return non-pointer values boxed in a pointer value.
10985     // Some clients may wish to silence warnings in this subcase.
10986     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10987       Selector S = ME->getSelector();
10988       StringRef SelArg0 = S.getNameForSlot(0);
10989       if (SelArg0.startswith("performSelector"))
10990         Diag = diag::warn_objc_pointer_masking_performSelector;
10991     }
10992     
10993     S.Diag(OpLoc, Diag)
10994       << ObjCPointerExpr->getSourceRange();
10995   }
10996 }
10997
10998 static NamedDecl *getDeclFromExpr(Expr *E) {
10999   if (!E)
11000     return nullptr;
11001   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11002     return DRE->getDecl();
11003   if (auto *ME = dyn_cast<MemberExpr>(E))
11004     return ME->getMemberDecl();
11005   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11006     return IRE->getDecl();
11007   return nullptr;
11008 }
11009
11010 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11011 /// operator @p Opc at location @c TokLoc. This routine only supports
11012 /// built-in operations; ActOnBinOp handles overloaded operators.
11013 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11014                                     BinaryOperatorKind Opc,
11015                                     Expr *LHSExpr, Expr *RHSExpr) {
11016   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11017     // The syntax only allows initializer lists on the RHS of assignment,
11018     // so we don't need to worry about accepting invalid code for
11019     // non-assignment operators.
11020     // C++11 5.17p9:
11021     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11022     //   of x = {} is x = T().
11023     InitializationKind Kind =
11024         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11025     InitializedEntity Entity =
11026         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11027     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11028     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11029     if (Init.isInvalid())
11030       return Init;
11031     RHSExpr = Init.get();
11032   }
11033
11034   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11035   QualType ResultTy;     // Result type of the binary operator.
11036   // The following two variables are used for compound assignment operators
11037   QualType CompLHSTy;    // Type of LHS after promotions for computation
11038   QualType CompResultTy; // Type of computation result
11039   ExprValueKind VK = VK_RValue;
11040   ExprObjectKind OK = OK_Ordinary;
11041
11042   if (!getLangOpts().CPlusPlus) {
11043     // C cannot handle TypoExpr nodes on either side of a binop because it
11044     // doesn't handle dependent types properly, so make sure any TypoExprs have
11045     // been dealt with before checking the operands.
11046     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11047     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11048       if (Opc != BO_Assign)
11049         return ExprResult(E);
11050       // Avoid correcting the RHS to the same Expr as the LHS.
11051       Decl *D = getDeclFromExpr(E);
11052       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11053     });
11054     if (!LHS.isUsable() || !RHS.isUsable())
11055       return ExprError();
11056   }
11057
11058   if (getLangOpts().OpenCL) {
11059     QualType LHSTy = LHSExpr->getType();
11060     QualType RHSTy = RHSExpr->getType();
11061     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11062     // the ATOMIC_VAR_INIT macro.
11063     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11064       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11065       if (BO_Assign == Opc)
11066         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11067       else
11068         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11069       return ExprError();
11070     }
11071
11072     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11073     // only with a builtin functions and therefore should be disallowed here.
11074     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11075         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11076         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11077         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11078       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11079       return ExprError();
11080     }
11081   }
11082
11083   switch (Opc) {
11084   case BO_Assign:
11085     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11086     if (getLangOpts().CPlusPlus &&
11087         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11088       VK = LHS.get()->getValueKind();
11089       OK = LHS.get()->getObjectKind();
11090     }
11091     if (!ResultTy.isNull()) {
11092       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11093       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11094     }
11095     RecordModifiableNonNullParam(*this, LHS.get());
11096     break;
11097   case BO_PtrMemD:
11098   case BO_PtrMemI:
11099     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11100                                             Opc == BO_PtrMemI);
11101     break;
11102   case BO_Mul:
11103   case BO_Div:
11104     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11105                                            Opc == BO_Div);
11106     break;
11107   case BO_Rem:
11108     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11109     break;
11110   case BO_Add:
11111     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11112     break;
11113   case BO_Sub:
11114     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11115     break;
11116   case BO_Shl:
11117   case BO_Shr:
11118     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11119     break;
11120   case BO_LE:
11121   case BO_LT:
11122   case BO_GE:
11123   case BO_GT:
11124     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11125     break;
11126   case BO_EQ:
11127   case BO_NE:
11128     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11129     break;
11130   case BO_And:
11131     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11132   case BO_Xor:
11133   case BO_Or:
11134     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11135     break;
11136   case BO_LAnd:
11137   case BO_LOr:
11138     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11139     break;
11140   case BO_MulAssign:
11141   case BO_DivAssign:
11142     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11143                                                Opc == BO_DivAssign);
11144     CompLHSTy = CompResultTy;
11145     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11146       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11147     break;
11148   case BO_RemAssign:
11149     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11150     CompLHSTy = CompResultTy;
11151     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11152       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11153     break;
11154   case BO_AddAssign:
11155     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11156     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11157       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11158     break;
11159   case BO_SubAssign:
11160     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11161     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11162       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11163     break;
11164   case BO_ShlAssign:
11165   case BO_ShrAssign:
11166     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11167     CompLHSTy = CompResultTy;
11168     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11169       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11170     break;
11171   case BO_AndAssign:
11172   case BO_OrAssign: // fallthrough
11173     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11174   case BO_XorAssign:
11175     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11176     CompLHSTy = CompResultTy;
11177     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11178       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11179     break;
11180   case BO_Comma:
11181     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11182     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11183       VK = RHS.get()->getValueKind();
11184       OK = RHS.get()->getObjectKind();
11185     }
11186     break;
11187   }
11188   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11189     return ExprError();
11190
11191   // Check for array bounds violations for both sides of the BinaryOperator
11192   CheckArrayAccess(LHS.get());
11193   CheckArrayAccess(RHS.get());
11194
11195   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11196     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11197                                                  &Context.Idents.get("object_setClass"),
11198                                                  SourceLocation(), LookupOrdinaryName);
11199     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11200       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11201       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11202       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11203       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11204       FixItHint::CreateInsertion(RHSLocEnd, ")");
11205     }
11206     else
11207       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11208   }
11209   else if (const ObjCIvarRefExpr *OIRE =
11210            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11211     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11212   
11213   if (CompResultTy.isNull())
11214     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11215                                         OK, OpLoc, FPFeatures.fp_contract);
11216   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11217       OK_ObjCProperty) {
11218     VK = VK_LValue;
11219     OK = LHS.get()->getObjectKind();
11220   }
11221   return new (Context) CompoundAssignOperator(
11222       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11223       OpLoc, FPFeatures.fp_contract);
11224 }
11225
11226 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11227 /// operators are mixed in a way that suggests that the programmer forgot that
11228 /// comparison operators have higher precedence. The most typical example of
11229 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11230 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11231                                       SourceLocation OpLoc, Expr *LHSExpr,
11232                                       Expr *RHSExpr) {
11233   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11234   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11235
11236   // Check that one of the sides is a comparison operator and the other isn't.
11237   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11238   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11239   if (isLeftComp == isRightComp)
11240     return;
11241
11242   // Bitwise operations are sometimes used as eager logical ops.
11243   // Don't diagnose this.
11244   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11245   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11246   if (isLeftBitwise || isRightBitwise)
11247     return;
11248
11249   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11250                                                    OpLoc)
11251                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11252   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11253   SourceRange ParensRange = isLeftComp ?
11254       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11255     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11256
11257   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11258     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11259   SuggestParentheses(Self, OpLoc,
11260     Self.PDiag(diag::note_precedence_silence) << OpStr,
11261     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11262   SuggestParentheses(Self, OpLoc,
11263     Self.PDiag(diag::note_precedence_bitwise_first)
11264       << BinaryOperator::getOpcodeStr(Opc),
11265     ParensRange);
11266 }
11267
11268 /// \brief It accepts a '&&' expr that is inside a '||' one.
11269 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11270 /// in parentheses.
11271 static void
11272 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11273                                        BinaryOperator *Bop) {
11274   assert(Bop->getOpcode() == BO_LAnd);
11275   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11276       << Bop->getSourceRange() << OpLoc;
11277   SuggestParentheses(Self, Bop->getOperatorLoc(),
11278     Self.PDiag(diag::note_precedence_silence)
11279       << Bop->getOpcodeStr(),
11280     Bop->getSourceRange());
11281 }
11282
11283 /// \brief Returns true if the given expression can be evaluated as a constant
11284 /// 'true'.
11285 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11286   bool Res;
11287   return !E->isValueDependent() &&
11288          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11289 }
11290
11291 /// \brief Returns true if the given expression can be evaluated as a constant
11292 /// 'false'.
11293 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11294   bool Res;
11295   return !E->isValueDependent() &&
11296          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11297 }
11298
11299 /// \brief Look for '&&' in the left hand of a '||' expr.
11300 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11301                                              Expr *LHSExpr, Expr *RHSExpr) {
11302   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11303     if (Bop->getOpcode() == BO_LAnd) {
11304       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11305       if (EvaluatesAsFalse(S, RHSExpr))
11306         return;
11307       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11308       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11309         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11310     } else if (Bop->getOpcode() == BO_LOr) {
11311       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11312         // If it's "a || b && 1 || c" we didn't warn earlier for
11313         // "a || b && 1", but warn now.
11314         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11315           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11316       }
11317     }
11318   }
11319 }
11320
11321 /// \brief Look for '&&' in the right hand of a '||' expr.
11322 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11323                                              Expr *LHSExpr, Expr *RHSExpr) {
11324   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11325     if (Bop->getOpcode() == BO_LAnd) {
11326       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11327       if (EvaluatesAsFalse(S, LHSExpr))
11328         return;
11329       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11330       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11331         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11332     }
11333   }
11334 }
11335
11336 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11337 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11338 /// the '&' expression in parentheses.
11339 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11340                                          SourceLocation OpLoc, Expr *SubExpr) {
11341   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11342     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11343       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11344         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11345         << Bop->getSourceRange() << OpLoc;
11346       SuggestParentheses(S, Bop->getOperatorLoc(),
11347         S.PDiag(diag::note_precedence_silence)
11348           << Bop->getOpcodeStr(),
11349         Bop->getSourceRange());
11350     }
11351   }
11352 }
11353
11354 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11355                                     Expr *SubExpr, StringRef Shift) {
11356   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11357     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11358       StringRef Op = Bop->getOpcodeStr();
11359       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11360           << Bop->getSourceRange() << OpLoc << Shift << Op;
11361       SuggestParentheses(S, Bop->getOperatorLoc(),
11362           S.PDiag(diag::note_precedence_silence) << Op,
11363           Bop->getSourceRange());
11364     }
11365   }
11366 }
11367
11368 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11369                                  Expr *LHSExpr, Expr *RHSExpr) {
11370   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11371   if (!OCE)
11372     return;
11373
11374   FunctionDecl *FD = OCE->getDirectCallee();
11375   if (!FD || !FD->isOverloadedOperator())
11376     return;
11377
11378   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11379   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11380     return;
11381
11382   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11383       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11384       << (Kind == OO_LessLess);
11385   SuggestParentheses(S, OCE->getOperatorLoc(),
11386                      S.PDiag(diag::note_precedence_silence)
11387                          << (Kind == OO_LessLess ? "<<" : ">>"),
11388                      OCE->getSourceRange());
11389   SuggestParentheses(S, OpLoc,
11390                      S.PDiag(diag::note_evaluate_comparison_first),
11391                      SourceRange(OCE->getArg(1)->getLocStart(),
11392                                  RHSExpr->getLocEnd()));
11393 }
11394
11395 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11396 /// precedence.
11397 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11398                                     SourceLocation OpLoc, Expr *LHSExpr,
11399                                     Expr *RHSExpr){
11400   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11401   if (BinaryOperator::isBitwiseOp(Opc))
11402     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11403
11404   // Diagnose "arg1 & arg2 | arg3"
11405   if ((Opc == BO_Or || Opc == BO_Xor) &&
11406       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11407     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11408     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11409   }
11410
11411   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11412   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11413   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11414     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11415     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11416   }
11417
11418   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11419       || Opc == BO_Shr) {
11420     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11421     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11422     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11423   }
11424
11425   // Warn on overloaded shift operators and comparisons, such as:
11426   // cout << 5 == 4;
11427   if (BinaryOperator::isComparisonOp(Opc))
11428     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11429 }
11430
11431 // Binary Operators.  'Tok' is the token for the operator.
11432 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11433                             tok::TokenKind Kind,
11434                             Expr *LHSExpr, Expr *RHSExpr) {
11435   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11436   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11437   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11438
11439   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11440   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11441
11442   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11443 }
11444
11445 /// Build an overloaded binary operator expression in the given scope.
11446 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11447                                        BinaryOperatorKind Opc,
11448                                        Expr *LHS, Expr *RHS) {
11449   // Find all of the overloaded operators visible from this
11450   // point. We perform both an operator-name lookup from the local
11451   // scope and an argument-dependent lookup based on the types of
11452   // the arguments.
11453   UnresolvedSet<16> Functions;
11454   OverloadedOperatorKind OverOp
11455     = BinaryOperator::getOverloadedOperator(Opc);
11456   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11457     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11458                                    RHS->getType(), Functions);
11459
11460   // Build the (potentially-overloaded, potentially-dependent)
11461   // binary operation.
11462   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11463 }
11464
11465 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11466                             BinaryOperatorKind Opc,
11467                             Expr *LHSExpr, Expr *RHSExpr) {
11468   // We want to end up calling one of checkPseudoObjectAssignment
11469   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11470   // both expressions are overloadable or either is type-dependent),
11471   // or CreateBuiltinBinOp (in any other case).  We also want to get
11472   // any placeholder types out of the way.
11473
11474   // Handle pseudo-objects in the LHS.
11475   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11476     // Assignments with a pseudo-object l-value need special analysis.
11477     if (pty->getKind() == BuiltinType::PseudoObject &&
11478         BinaryOperator::isAssignmentOp(Opc))
11479       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11480
11481     // Don't resolve overloads if the other type is overloadable.
11482     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11483       // We can't actually test that if we still have a placeholder,
11484       // though.  Fortunately, none of the exceptions we see in that
11485       // code below are valid when the LHS is an overload set.  Note
11486       // that an overload set can be dependently-typed, but it never
11487       // instantiates to having an overloadable type.
11488       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11489       if (resolvedRHS.isInvalid()) return ExprError();
11490       RHSExpr = resolvedRHS.get();
11491
11492       if (RHSExpr->isTypeDependent() ||
11493           RHSExpr->getType()->isOverloadableType())
11494         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11495     }
11496         
11497     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11498     if (LHS.isInvalid()) return ExprError();
11499     LHSExpr = LHS.get();
11500   }
11501
11502   // Handle pseudo-objects in the RHS.
11503   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11504     // An overload in the RHS can potentially be resolved by the type
11505     // being assigned to.
11506     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11507       if (getLangOpts().CPlusPlus &&
11508           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11509            LHSExpr->getType()->isOverloadableType()))
11510         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11511
11512       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11513     }
11514
11515     // Don't resolve overloads if the other type is overloadable.
11516     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11517         LHSExpr->getType()->isOverloadableType())
11518       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11519
11520     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11521     if (!resolvedRHS.isUsable()) return ExprError();
11522     RHSExpr = resolvedRHS.get();
11523   }
11524
11525   if (getLangOpts().CPlusPlus) {
11526     // If either expression is type-dependent, always build an
11527     // overloaded op.
11528     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11529       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11530
11531     // Otherwise, build an overloaded op if either expression has an
11532     // overloadable type.
11533     if (LHSExpr->getType()->isOverloadableType() ||
11534         RHSExpr->getType()->isOverloadableType())
11535       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11536   }
11537
11538   // Build a built-in binary operation.
11539   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11540 }
11541
11542 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11543                                       UnaryOperatorKind Opc,
11544                                       Expr *InputExpr) {
11545   ExprResult Input = InputExpr;
11546   ExprValueKind VK = VK_RValue;
11547   ExprObjectKind OK = OK_Ordinary;
11548   QualType resultType;
11549   if (getLangOpts().OpenCL) {
11550     QualType Ty = InputExpr->getType();
11551     // The only legal unary operation for atomics is '&'.
11552     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11553     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11554     // only with a builtin functions and therefore should be disallowed here.
11555         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11556         || Ty->isBlockPointerType())) {
11557       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11558                        << InputExpr->getType()
11559                        << Input.get()->getSourceRange());
11560     }
11561   }
11562   switch (Opc) {
11563   case UO_PreInc:
11564   case UO_PreDec:
11565   case UO_PostInc:
11566   case UO_PostDec:
11567     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11568                                                 OpLoc,
11569                                                 Opc == UO_PreInc ||
11570                                                 Opc == UO_PostInc,
11571                                                 Opc == UO_PreInc ||
11572                                                 Opc == UO_PreDec);
11573     break;
11574   case UO_AddrOf:
11575     resultType = CheckAddressOfOperand(Input, OpLoc);
11576     RecordModifiableNonNullParam(*this, InputExpr);
11577     break;
11578   case UO_Deref: {
11579     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11580     if (Input.isInvalid()) return ExprError();
11581     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11582     break;
11583   }
11584   case UO_Plus:
11585   case UO_Minus:
11586     Input = UsualUnaryConversions(Input.get());
11587     if (Input.isInvalid()) return ExprError();
11588     resultType = Input.get()->getType();
11589     if (resultType->isDependentType())
11590       break;
11591     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11592       break;
11593     else if (resultType->isVectorType() &&
11594              // The z vector extensions don't allow + or - with bool vectors.
11595              (!Context.getLangOpts().ZVector ||
11596               resultType->getAs<VectorType>()->getVectorKind() !=
11597               VectorType::AltiVecBool))
11598       break;
11599     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11600              Opc == UO_Plus &&
11601              resultType->isPointerType())
11602       break;
11603
11604     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11605       << resultType << Input.get()->getSourceRange());
11606
11607   case UO_Not: // bitwise complement
11608     Input = UsualUnaryConversions(Input.get());
11609     if (Input.isInvalid())
11610       return ExprError();
11611     resultType = Input.get()->getType();
11612     if (resultType->isDependentType())
11613       break;
11614     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11615     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11616       // C99 does not support '~' for complex conjugation.
11617       Diag(OpLoc, diag::ext_integer_complement_complex)
11618           << resultType << Input.get()->getSourceRange();
11619     else if (resultType->hasIntegerRepresentation())
11620       break;
11621     else if (resultType->isExtVectorType()) {
11622       if (Context.getLangOpts().OpenCL) {
11623         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11624         // on vector float types.
11625         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11626         if (!T->isIntegerType())
11627           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11628                            << resultType << Input.get()->getSourceRange());
11629       }
11630       break;
11631     } else {
11632       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11633                        << resultType << Input.get()->getSourceRange());
11634     }
11635     break;
11636
11637   case UO_LNot: // logical negation
11638     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11639     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11640     if (Input.isInvalid()) return ExprError();
11641     resultType = Input.get()->getType();
11642
11643     // Though we still have to promote half FP to float...
11644     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11645       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11646       resultType = Context.FloatTy;
11647     }
11648
11649     if (resultType->isDependentType())
11650       break;
11651     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11652       // C99 6.5.3.3p1: ok, fallthrough;
11653       if (Context.getLangOpts().CPlusPlus) {
11654         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11655         // operand contextually converted to bool.
11656         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11657                                   ScalarTypeToBooleanCastKind(resultType));
11658       } else if (Context.getLangOpts().OpenCL &&
11659                  Context.getLangOpts().OpenCLVersion < 120) {
11660         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11661         // operate on scalar float types.
11662         if (!resultType->isIntegerType())
11663           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11664                            << resultType << Input.get()->getSourceRange());
11665       }
11666     } else if (resultType->isExtVectorType()) {
11667       if (Context.getLangOpts().OpenCL &&
11668           Context.getLangOpts().OpenCLVersion < 120) {
11669         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11670         // operate on vector float types.
11671         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11672         if (!T->isIntegerType())
11673           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11674                            << resultType << Input.get()->getSourceRange());
11675       }
11676       // Vector logical not returns the signed variant of the operand type.
11677       resultType = GetSignedVectorType(resultType);
11678       break;
11679     } else {
11680       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11681         << resultType << Input.get()->getSourceRange());
11682     }
11683     
11684     // LNot always has type int. C99 6.5.3.3p5.
11685     // In C++, it's bool. C++ 5.3.1p8
11686     resultType = Context.getLogicalOperationType();
11687     break;
11688   case UO_Real:
11689   case UO_Imag:
11690     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11691     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11692     // complex l-values to ordinary l-values and all other values to r-values.
11693     if (Input.isInvalid()) return ExprError();
11694     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11695       if (Input.get()->getValueKind() != VK_RValue &&
11696           Input.get()->getObjectKind() == OK_Ordinary)
11697         VK = Input.get()->getValueKind();
11698     } else if (!getLangOpts().CPlusPlus) {
11699       // In C, a volatile scalar is read by __imag. In C++, it is not.
11700       Input = DefaultLvalueConversion(Input.get());
11701     }
11702     break;
11703   case UO_Extension:
11704   case UO_Coawait:
11705     resultType = Input.get()->getType();
11706     VK = Input.get()->getValueKind();
11707     OK = Input.get()->getObjectKind();
11708     break;
11709   }
11710   if (resultType.isNull() || Input.isInvalid())
11711     return ExprError();
11712
11713   // Check for array bounds violations in the operand of the UnaryOperator,
11714   // except for the '*' and '&' operators that have to be handled specially
11715   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11716   // that are explicitly defined as valid by the standard).
11717   if (Opc != UO_AddrOf && Opc != UO_Deref)
11718     CheckArrayAccess(Input.get());
11719
11720   return new (Context)
11721       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11722 }
11723
11724 /// \brief Determine whether the given expression is a qualified member
11725 /// access expression, of a form that could be turned into a pointer to member
11726 /// with the address-of operator.
11727 static bool isQualifiedMemberAccess(Expr *E) {
11728   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11729     if (!DRE->getQualifier())
11730       return false;
11731     
11732     ValueDecl *VD = DRE->getDecl();
11733     if (!VD->isCXXClassMember())
11734       return false;
11735     
11736     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11737       return true;
11738     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11739       return Method->isInstance();
11740       
11741     return false;
11742   }
11743   
11744   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11745     if (!ULE->getQualifier())
11746       return false;
11747     
11748     for (NamedDecl *D : ULE->decls()) {
11749       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11750         if (Method->isInstance())
11751           return true;
11752       } else {
11753         // Overload set does not contain methods.
11754         break;
11755       }
11756     }
11757     
11758     return false;
11759   }
11760   
11761   return false;
11762 }
11763
11764 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11765                               UnaryOperatorKind Opc, Expr *Input) {
11766   // First things first: handle placeholders so that the
11767   // overloaded-operator check considers the right type.
11768   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11769     // Increment and decrement of pseudo-object references.
11770     if (pty->getKind() == BuiltinType::PseudoObject &&
11771         UnaryOperator::isIncrementDecrementOp(Opc))
11772       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11773
11774     // extension is always a builtin operator.
11775     if (Opc == UO_Extension)
11776       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11777
11778     // & gets special logic for several kinds of placeholder.
11779     // The builtin code knows what to do.
11780     if (Opc == UO_AddrOf &&
11781         (pty->getKind() == BuiltinType::Overload ||
11782          pty->getKind() == BuiltinType::UnknownAny ||
11783          pty->getKind() == BuiltinType::BoundMember))
11784       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11785
11786     // Anything else needs to be handled now.
11787     ExprResult Result = CheckPlaceholderExpr(Input);
11788     if (Result.isInvalid()) return ExprError();
11789     Input = Result.get();
11790   }
11791
11792   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11793       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11794       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11795     // Find all of the overloaded operators visible from this
11796     // point. We perform both an operator-name lookup from the local
11797     // scope and an argument-dependent lookup based on the types of
11798     // the arguments.
11799     UnresolvedSet<16> Functions;
11800     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11801     if (S && OverOp != OO_None)
11802       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11803                                    Functions);
11804
11805     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11806   }
11807
11808   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11809 }
11810
11811 // Unary Operators.  'Tok' is the token for the operator.
11812 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11813                               tok::TokenKind Op, Expr *Input) {
11814   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11815 }
11816
11817 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11818 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11819                                 LabelDecl *TheDecl) {
11820   TheDecl->markUsed(Context);
11821   // Create the AST node.  The address of a label always has type 'void*'.
11822   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11823                                      Context.getPointerType(Context.VoidTy));
11824 }
11825
11826 /// Given the last statement in a statement-expression, check whether
11827 /// the result is a producing expression (like a call to an
11828 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11829 /// release out of the full-expression.  Otherwise, return null.
11830 /// Cannot fail.
11831 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11832   // Should always be wrapped with one of these.
11833   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11834   if (!cleanups) return nullptr;
11835
11836   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11837   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11838     return nullptr;
11839
11840   // Splice out the cast.  This shouldn't modify any interesting
11841   // features of the statement.
11842   Expr *producer = cast->getSubExpr();
11843   assert(producer->getType() == cast->getType());
11844   assert(producer->getValueKind() == cast->getValueKind());
11845   cleanups->setSubExpr(producer);
11846   return cleanups;
11847 }
11848
11849 void Sema::ActOnStartStmtExpr() {
11850   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11851 }
11852
11853 void Sema::ActOnStmtExprError() {
11854   // Note that function is also called by TreeTransform when leaving a
11855   // StmtExpr scope without rebuilding anything.
11856
11857   DiscardCleanupsInEvaluationContext();
11858   PopExpressionEvaluationContext();
11859 }
11860
11861 ExprResult
11862 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11863                     SourceLocation RPLoc) { // "({..})"
11864   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11865   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11866
11867   if (hasAnyUnrecoverableErrorsInThisFunction())
11868     DiscardCleanupsInEvaluationContext();
11869   assert(!Cleanup.exprNeedsCleanups() &&
11870          "cleanups within StmtExpr not correctly bound!");
11871   PopExpressionEvaluationContext();
11872
11873   // FIXME: there are a variety of strange constraints to enforce here, for
11874   // example, it is not possible to goto into a stmt expression apparently.
11875   // More semantic analysis is needed.
11876
11877   // If there are sub-stmts in the compound stmt, take the type of the last one
11878   // as the type of the stmtexpr.
11879   QualType Ty = Context.VoidTy;
11880   bool StmtExprMayBindToTemp = false;
11881   if (!Compound->body_empty()) {
11882     Stmt *LastStmt = Compound->body_back();
11883     LabelStmt *LastLabelStmt = nullptr;
11884     // If LastStmt is a label, skip down through into the body.
11885     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11886       LastLabelStmt = Label;
11887       LastStmt = Label->getSubStmt();
11888     }
11889
11890     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11891       // Do function/array conversion on the last expression, but not
11892       // lvalue-to-rvalue.  However, initialize an unqualified type.
11893       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11894       if (LastExpr.isInvalid())
11895         return ExprError();
11896       Ty = LastExpr.get()->getType().getUnqualifiedType();
11897
11898       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11899         // In ARC, if the final expression ends in a consume, splice
11900         // the consume out and bind it later.  In the alternate case
11901         // (when dealing with a retainable type), the result
11902         // initialization will create a produce.  In both cases the
11903         // result will be +1, and we'll need to balance that out with
11904         // a bind.
11905         if (Expr *rebuiltLastStmt
11906               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11907           LastExpr = rebuiltLastStmt;
11908         } else {
11909           LastExpr = PerformCopyInitialization(
11910                             InitializedEntity::InitializeResult(LPLoc, 
11911                                                                 Ty,
11912                                                                 false),
11913                                                    SourceLocation(),
11914                                                LastExpr);
11915         }
11916
11917         if (LastExpr.isInvalid())
11918           return ExprError();
11919         if (LastExpr.get() != nullptr) {
11920           if (!LastLabelStmt)
11921             Compound->setLastStmt(LastExpr.get());
11922           else
11923             LastLabelStmt->setSubStmt(LastExpr.get());
11924           StmtExprMayBindToTemp = true;
11925         }
11926       }
11927     }
11928   }
11929
11930   // FIXME: Check that expression type is complete/non-abstract; statement
11931   // expressions are not lvalues.
11932   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11933   if (StmtExprMayBindToTemp)
11934     return MaybeBindToTemporary(ResStmtExpr);
11935   return ResStmtExpr;
11936 }
11937
11938 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11939                                       TypeSourceInfo *TInfo,
11940                                       ArrayRef<OffsetOfComponent> Components,
11941                                       SourceLocation RParenLoc) {
11942   QualType ArgTy = TInfo->getType();
11943   bool Dependent = ArgTy->isDependentType();
11944   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11945   
11946   // We must have at least one component that refers to the type, and the first
11947   // one is known to be a field designator.  Verify that the ArgTy represents
11948   // a struct/union/class.
11949   if (!Dependent && !ArgTy->isRecordType())
11950     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
11951                        << ArgTy << TypeRange);
11952   
11953   // Type must be complete per C99 7.17p3 because a declaring a variable
11954   // with an incomplete type would be ill-formed.
11955   if (!Dependent 
11956       && RequireCompleteType(BuiltinLoc, ArgTy,
11957                              diag::err_offsetof_incomplete_type, TypeRange))
11958     return ExprError();
11959   
11960   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11961   // GCC extension, diagnose them.
11962   // FIXME: This diagnostic isn't actually visible because the location is in
11963   // a system header!
11964   if (Components.size() != 1)
11965     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11966       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11967   
11968   bool DidWarnAboutNonPOD = false;
11969   QualType CurrentType = ArgTy;
11970   SmallVector<OffsetOfNode, 4> Comps;
11971   SmallVector<Expr*, 4> Exprs;
11972   for (const OffsetOfComponent &OC : Components) {
11973     if (OC.isBrackets) {
11974       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11975       if (!CurrentType->isDependentType()) {
11976         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11977         if(!AT)
11978           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11979                            << CurrentType);
11980         CurrentType = AT->getElementType();
11981       } else
11982         CurrentType = Context.DependentTy;
11983       
11984       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11985       if (IdxRval.isInvalid())
11986         return ExprError();
11987       Expr *Idx = IdxRval.get();
11988
11989       // The expression must be an integral expression.
11990       // FIXME: An integral constant expression?
11991       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11992           !Idx->getType()->isIntegerType())
11993         return ExprError(Diag(Idx->getLocStart(),
11994                               diag::err_typecheck_subscript_not_integer)
11995                          << Idx->getSourceRange());
11996
11997       // Record this array index.
11998       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11999       Exprs.push_back(Idx);
12000       continue;
12001     }
12002     
12003     // Offset of a field.
12004     if (CurrentType->isDependentType()) {
12005       // We have the offset of a field, but we can't look into the dependent
12006       // type. Just record the identifier of the field.
12007       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12008       CurrentType = Context.DependentTy;
12009       continue;
12010     }
12011     
12012     // We need to have a complete type to look into.
12013     if (RequireCompleteType(OC.LocStart, CurrentType,
12014                             diag::err_offsetof_incomplete_type))
12015       return ExprError();
12016     
12017     // Look for the designated field.
12018     const RecordType *RC = CurrentType->getAs<RecordType>();
12019     if (!RC) 
12020       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12021                        << CurrentType);
12022     RecordDecl *RD = RC->getDecl();
12023     
12024     // C++ [lib.support.types]p5:
12025     //   The macro offsetof accepts a restricted set of type arguments in this
12026     //   International Standard. type shall be a POD structure or a POD union
12027     //   (clause 9).
12028     // C++11 [support.types]p4:
12029     //   If type is not a standard-layout class (Clause 9), the results are
12030     //   undefined.
12031     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12032       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12033       unsigned DiagID =
12034         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12035                             : diag::ext_offsetof_non_pod_type;
12036
12037       if (!IsSafe && !DidWarnAboutNonPOD &&
12038           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12039                               PDiag(DiagID)
12040                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12041                               << CurrentType))
12042         DidWarnAboutNonPOD = true;
12043     }
12044     
12045     // Look for the field.
12046     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12047     LookupQualifiedName(R, RD);
12048     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12049     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12050     if (!MemberDecl) {
12051       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12052         MemberDecl = IndirectMemberDecl->getAnonField();
12053     }
12054
12055     if (!MemberDecl)
12056       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12057                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
12058                                                               OC.LocEnd));
12059     
12060     // C99 7.17p3:
12061     //   (If the specified member is a bit-field, the behavior is undefined.)
12062     //
12063     // We diagnose this as an error.
12064     if (MemberDecl->isBitField()) {
12065       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12066         << MemberDecl->getDeclName()
12067         << SourceRange(BuiltinLoc, RParenLoc);
12068       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12069       return ExprError();
12070     }
12071
12072     RecordDecl *Parent = MemberDecl->getParent();
12073     if (IndirectMemberDecl)
12074       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12075
12076     // If the member was found in a base class, introduce OffsetOfNodes for
12077     // the base class indirections.
12078     CXXBasePaths Paths;
12079     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12080                       Paths)) {
12081       if (Paths.getDetectedVirtual()) {
12082         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12083           << MemberDecl->getDeclName()
12084           << SourceRange(BuiltinLoc, RParenLoc);
12085         return ExprError();
12086       }
12087
12088       CXXBasePath &Path = Paths.front();
12089       for (const CXXBasePathElement &B : Path)
12090         Comps.push_back(OffsetOfNode(B.Base));
12091     }
12092
12093     if (IndirectMemberDecl) {
12094       for (auto *FI : IndirectMemberDecl->chain()) {
12095         assert(isa<FieldDecl>(FI));
12096         Comps.push_back(OffsetOfNode(OC.LocStart,
12097                                      cast<FieldDecl>(FI), OC.LocEnd));
12098       }
12099     } else
12100       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12101
12102     CurrentType = MemberDecl->getType().getNonReferenceType(); 
12103   }
12104   
12105   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12106                               Comps, Exprs, RParenLoc);
12107 }
12108
12109 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12110                                       SourceLocation BuiltinLoc,
12111                                       SourceLocation TypeLoc,
12112                                       ParsedType ParsedArgTy,
12113                                       ArrayRef<OffsetOfComponent> Components,
12114                                       SourceLocation RParenLoc) {
12115   
12116   TypeSourceInfo *ArgTInfo;
12117   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12118   if (ArgTy.isNull())
12119     return ExprError();
12120
12121   if (!ArgTInfo)
12122     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12123
12124   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12125 }
12126
12127
12128 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12129                                  Expr *CondExpr,
12130                                  Expr *LHSExpr, Expr *RHSExpr,
12131                                  SourceLocation RPLoc) {
12132   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12133
12134   ExprValueKind VK = VK_RValue;
12135   ExprObjectKind OK = OK_Ordinary;
12136   QualType resType;
12137   bool ValueDependent = false;
12138   bool CondIsTrue = false;
12139   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12140     resType = Context.DependentTy;
12141     ValueDependent = true;
12142   } else {
12143     // The conditional expression is required to be a constant expression.
12144     llvm::APSInt condEval(32);
12145     ExprResult CondICE
12146       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12147           diag::err_typecheck_choose_expr_requires_constant, false);
12148     if (CondICE.isInvalid())
12149       return ExprError();
12150     CondExpr = CondICE.get();
12151     CondIsTrue = condEval.getZExtValue();
12152
12153     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12154     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12155
12156     resType = ActiveExpr->getType();
12157     ValueDependent = ActiveExpr->isValueDependent();
12158     VK = ActiveExpr->getValueKind();
12159     OK = ActiveExpr->getObjectKind();
12160   }
12161
12162   return new (Context)
12163       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12164                  CondIsTrue, resType->isDependentType(), ValueDependent);
12165 }
12166
12167 //===----------------------------------------------------------------------===//
12168 // Clang Extensions.
12169 //===----------------------------------------------------------------------===//
12170
12171 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12172 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12173   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12174
12175   if (LangOpts.CPlusPlus) {
12176     Decl *ManglingContextDecl;
12177     if (MangleNumberingContext *MCtx =
12178             getCurrentMangleNumberContext(Block->getDeclContext(),
12179                                           ManglingContextDecl)) {
12180       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12181       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12182     }
12183   }
12184
12185   PushBlockScope(CurScope, Block);
12186   CurContext->addDecl(Block);
12187   if (CurScope)
12188     PushDeclContext(CurScope, Block);
12189   else
12190     CurContext = Block;
12191
12192   getCurBlock()->HasImplicitReturnType = true;
12193
12194   // Enter a new evaluation context to insulate the block from any
12195   // cleanups from the enclosing full-expression.
12196   PushExpressionEvaluationContext(PotentiallyEvaluated);  
12197 }
12198
12199 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12200                                Scope *CurScope) {
12201   assert(ParamInfo.getIdentifier() == nullptr &&
12202          "block-id should have no identifier!");
12203   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12204   BlockScopeInfo *CurBlock = getCurBlock();
12205
12206   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12207   QualType T = Sig->getType();
12208
12209   // FIXME: We should allow unexpanded parameter packs here, but that would,
12210   // in turn, make the block expression contain unexpanded parameter packs.
12211   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12212     // Drop the parameters.
12213     FunctionProtoType::ExtProtoInfo EPI;
12214     EPI.HasTrailingReturn = false;
12215     EPI.TypeQuals |= DeclSpec::TQ_const;
12216     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12217     Sig = Context.getTrivialTypeSourceInfo(T);
12218   }
12219   
12220   // GetTypeForDeclarator always produces a function type for a block
12221   // literal signature.  Furthermore, it is always a FunctionProtoType
12222   // unless the function was written with a typedef.
12223   assert(T->isFunctionType() &&
12224          "GetTypeForDeclarator made a non-function block signature");
12225
12226   // Look for an explicit signature in that function type.
12227   FunctionProtoTypeLoc ExplicitSignature;
12228
12229   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12230   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12231
12232     // Check whether that explicit signature was synthesized by
12233     // GetTypeForDeclarator.  If so, don't save that as part of the
12234     // written signature.
12235     if (ExplicitSignature.getLocalRangeBegin() ==
12236         ExplicitSignature.getLocalRangeEnd()) {
12237       // This would be much cheaper if we stored TypeLocs instead of
12238       // TypeSourceInfos.
12239       TypeLoc Result = ExplicitSignature.getReturnLoc();
12240       unsigned Size = Result.getFullDataSize();
12241       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12242       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12243
12244       ExplicitSignature = FunctionProtoTypeLoc();
12245     }
12246   }
12247
12248   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12249   CurBlock->FunctionType = T;
12250
12251   const FunctionType *Fn = T->getAs<FunctionType>();
12252   QualType RetTy = Fn->getReturnType();
12253   bool isVariadic =
12254     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12255
12256   CurBlock->TheDecl->setIsVariadic(isVariadic);
12257
12258   // Context.DependentTy is used as a placeholder for a missing block
12259   // return type.  TODO:  what should we do with declarators like:
12260   //   ^ * { ... }
12261   // If the answer is "apply template argument deduction"....
12262   if (RetTy != Context.DependentTy) {
12263     CurBlock->ReturnType = RetTy;
12264     CurBlock->TheDecl->setBlockMissingReturnType(false);
12265     CurBlock->HasImplicitReturnType = false;
12266   }
12267
12268   // Push block parameters from the declarator if we had them.
12269   SmallVector<ParmVarDecl*, 8> Params;
12270   if (ExplicitSignature) {
12271     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12272       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12273       if (Param->getIdentifier() == nullptr &&
12274           !Param->isImplicit() &&
12275           !Param->isInvalidDecl() &&
12276           !getLangOpts().CPlusPlus)
12277         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12278       Params.push_back(Param);
12279     }
12280
12281   // Fake up parameter variables if we have a typedef, like
12282   //   ^ fntype { ... }
12283   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12284     for (const auto &I : Fn->param_types()) {
12285       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12286           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12287       Params.push_back(Param);
12288     }
12289   }
12290
12291   // Set the parameters on the block decl.
12292   if (!Params.empty()) {
12293     CurBlock->TheDecl->setParams(Params);
12294     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12295                              /*CheckParameterNames=*/false);
12296   }
12297   
12298   // Finally we can process decl attributes.
12299   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12300
12301   // Put the parameter variables in scope.
12302   for (auto AI : CurBlock->TheDecl->parameters()) {
12303     AI->setOwningFunction(CurBlock->TheDecl);
12304
12305     // If this has an identifier, add it to the scope stack.
12306     if (AI->getIdentifier()) {
12307       CheckShadow(CurBlock->TheScope, AI);
12308
12309       PushOnScopeChains(AI, CurBlock->TheScope);
12310     }
12311   }
12312 }
12313
12314 /// ActOnBlockError - If there is an error parsing a block, this callback
12315 /// is invoked to pop the information about the block from the action impl.
12316 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12317   // Leave the expression-evaluation context.
12318   DiscardCleanupsInEvaluationContext();
12319   PopExpressionEvaluationContext();
12320
12321   // Pop off CurBlock, handle nested blocks.
12322   PopDeclContext();
12323   PopFunctionScopeInfo();
12324 }
12325
12326 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12327 /// literal was successfully completed.  ^(int x){...}
12328 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12329                                     Stmt *Body, Scope *CurScope) {
12330   // If blocks are disabled, emit an error.
12331   if (!LangOpts.Blocks)
12332     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12333
12334   // Leave the expression-evaluation context.
12335   if (hasAnyUnrecoverableErrorsInThisFunction())
12336     DiscardCleanupsInEvaluationContext();
12337   assert(!Cleanup.exprNeedsCleanups() &&
12338          "cleanups within block not correctly bound!");
12339   PopExpressionEvaluationContext();
12340
12341   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12342
12343   if (BSI->HasImplicitReturnType)
12344     deduceClosureReturnType(*BSI);
12345
12346   PopDeclContext();
12347
12348   QualType RetTy = Context.VoidTy;
12349   if (!BSI->ReturnType.isNull())
12350     RetTy = BSI->ReturnType;
12351
12352   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12353   QualType BlockTy;
12354
12355   // Set the captured variables on the block.
12356   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12357   SmallVector<BlockDecl::Capture, 4> Captures;
12358   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12359     if (Cap.isThisCapture())
12360       continue;
12361     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12362                               Cap.isNested(), Cap.getInitExpr());
12363     Captures.push_back(NewCap);
12364   }
12365   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12366
12367   // If the user wrote a function type in some form, try to use that.
12368   if (!BSI->FunctionType.isNull()) {
12369     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12370
12371     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12372     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12373     
12374     // Turn protoless block types into nullary block types.
12375     if (isa<FunctionNoProtoType>(FTy)) {
12376       FunctionProtoType::ExtProtoInfo EPI;
12377       EPI.ExtInfo = Ext;
12378       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12379
12380     // Otherwise, if we don't need to change anything about the function type,
12381     // preserve its sugar structure.
12382     } else if (FTy->getReturnType() == RetTy &&
12383                (!NoReturn || FTy->getNoReturnAttr())) {
12384       BlockTy = BSI->FunctionType;
12385
12386     // Otherwise, make the minimal modifications to the function type.
12387     } else {
12388       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12389       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12390       EPI.TypeQuals = 0; // FIXME: silently?
12391       EPI.ExtInfo = Ext;
12392       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12393     }
12394
12395   // If we don't have a function type, just build one from nothing.
12396   } else {
12397     FunctionProtoType::ExtProtoInfo EPI;
12398     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12399     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12400   }
12401
12402   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12403   BlockTy = Context.getBlockPointerType(BlockTy);
12404
12405   // If needed, diagnose invalid gotos and switches in the block.
12406   if (getCurFunction()->NeedsScopeChecking() &&
12407       !PP.isCodeCompletionEnabled())
12408     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12409
12410   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12411
12412   // Try to apply the named return value optimization. We have to check again
12413   // if we can do this, though, because blocks keep return statements around
12414   // to deduce an implicit return type.
12415   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12416       !BSI->TheDecl->isDependentContext())
12417     computeNRVO(Body, BSI);
12418   
12419   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12420   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12421   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12422
12423   // If the block isn't obviously global, i.e. it captures anything at
12424   // all, then we need to do a few things in the surrounding context:
12425   if (Result->getBlockDecl()->hasCaptures()) {
12426     // First, this expression has a new cleanup object.
12427     ExprCleanupObjects.push_back(Result->getBlockDecl());
12428     Cleanup.setExprNeedsCleanups(true);
12429
12430     // It also gets a branch-protected scope if any of the captured
12431     // variables needs destruction.
12432     for (const auto &CI : Result->getBlockDecl()->captures()) {
12433       const VarDecl *var = CI.getVariable();
12434       if (var->getType().isDestructedType() != QualType::DK_none) {
12435         getCurFunction()->setHasBranchProtectedScope();
12436         break;
12437       }
12438     }
12439   }
12440
12441   return Result;
12442 }
12443
12444 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12445                             SourceLocation RPLoc) {
12446   TypeSourceInfo *TInfo;
12447   GetTypeFromParser(Ty, &TInfo);
12448   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12449 }
12450
12451 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12452                                 Expr *E, TypeSourceInfo *TInfo,
12453                                 SourceLocation RPLoc) {
12454   Expr *OrigExpr = E;
12455   bool IsMS = false;
12456
12457   // CUDA device code does not support varargs.
12458   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12459     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12460       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12461       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12462         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12463     }
12464   }
12465
12466   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12467   // as Microsoft ABI on an actual Microsoft platform, where
12468   // __builtin_ms_va_list and __builtin_va_list are the same.)
12469   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12470       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12471     QualType MSVaListType = Context.getBuiltinMSVaListType();
12472     if (Context.hasSameType(MSVaListType, E->getType())) {
12473       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12474         return ExprError();
12475       IsMS = true;
12476     }
12477   }
12478
12479   // Get the va_list type
12480   QualType VaListType = Context.getBuiltinVaListType();
12481   if (!IsMS) {
12482     if (VaListType->isArrayType()) {
12483       // Deal with implicit array decay; for example, on x86-64,
12484       // va_list is an array, but it's supposed to decay to
12485       // a pointer for va_arg.
12486       VaListType = Context.getArrayDecayedType(VaListType);
12487       // Make sure the input expression also decays appropriately.
12488       ExprResult Result = UsualUnaryConversions(E);
12489       if (Result.isInvalid())
12490         return ExprError();
12491       E = Result.get();
12492     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12493       // If va_list is a record type and we are compiling in C++ mode,
12494       // check the argument using reference binding.
12495       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12496           Context, Context.getLValueReferenceType(VaListType), false);
12497       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12498       if (Init.isInvalid())
12499         return ExprError();
12500       E = Init.getAs<Expr>();
12501     } else {
12502       // Otherwise, the va_list argument must be an l-value because
12503       // it is modified by va_arg.
12504       if (!E->isTypeDependent() &&
12505           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12506         return ExprError();
12507     }
12508   }
12509
12510   if (!IsMS && !E->isTypeDependent() &&
12511       !Context.hasSameType(VaListType, E->getType()))
12512     return ExprError(Diag(E->getLocStart(),
12513                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12514       << OrigExpr->getType() << E->getSourceRange());
12515
12516   if (!TInfo->getType()->isDependentType()) {
12517     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12518                             diag::err_second_parameter_to_va_arg_incomplete,
12519                             TInfo->getTypeLoc()))
12520       return ExprError();
12521
12522     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12523                                TInfo->getType(),
12524                                diag::err_second_parameter_to_va_arg_abstract,
12525                                TInfo->getTypeLoc()))
12526       return ExprError();
12527
12528     if (!TInfo->getType().isPODType(Context)) {
12529       Diag(TInfo->getTypeLoc().getBeginLoc(),
12530            TInfo->getType()->isObjCLifetimeType()
12531              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12532              : diag::warn_second_parameter_to_va_arg_not_pod)
12533         << TInfo->getType()
12534         << TInfo->getTypeLoc().getSourceRange();
12535     }
12536
12537     // Check for va_arg where arguments of the given type will be promoted
12538     // (i.e. this va_arg is guaranteed to have undefined behavior).
12539     QualType PromoteType;
12540     if (TInfo->getType()->isPromotableIntegerType()) {
12541       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12542       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12543         PromoteType = QualType();
12544     }
12545     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12546       PromoteType = Context.DoubleTy;
12547     if (!PromoteType.isNull())
12548       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12549                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12550                           << TInfo->getType()
12551                           << PromoteType
12552                           << TInfo->getTypeLoc().getSourceRange());
12553   }
12554
12555   QualType T = TInfo->getType().getNonLValueExprType(Context);
12556   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12557 }
12558
12559 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12560   // The type of __null will be int or long, depending on the size of
12561   // pointers on the target.
12562   QualType Ty;
12563   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12564   if (pw == Context.getTargetInfo().getIntWidth())
12565     Ty = Context.IntTy;
12566   else if (pw == Context.getTargetInfo().getLongWidth())
12567     Ty = Context.LongTy;
12568   else if (pw == Context.getTargetInfo().getLongLongWidth())
12569     Ty = Context.LongLongTy;
12570   else {
12571     llvm_unreachable("I don't know size of pointer!");
12572   }
12573
12574   return new (Context) GNUNullExpr(Ty, TokenLoc);
12575 }
12576
12577 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12578                                               bool Diagnose) {
12579   if (!getLangOpts().ObjC1)
12580     return false;
12581
12582   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12583   if (!PT)
12584     return false;
12585
12586   if (!PT->isObjCIdType()) {
12587     // Check if the destination is the 'NSString' interface.
12588     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12589     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12590       return false;
12591   }
12592   
12593   // Ignore any parens, implicit casts (should only be
12594   // array-to-pointer decays), and not-so-opaque values.  The last is
12595   // important for making this trigger for property assignments.
12596   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12597   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12598     if (OV->getSourceExpr())
12599       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12600
12601   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12602   if (!SL || !SL->isAscii())
12603     return false;
12604   if (Diagnose) {
12605     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12606       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12607     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12608   }
12609   return true;
12610 }
12611
12612 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12613                                               const Expr *SrcExpr) {
12614   if (!DstType->isFunctionPointerType() ||
12615       !SrcExpr->getType()->isFunctionType())
12616     return false;
12617
12618   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12619   if (!DRE)
12620     return false;
12621
12622   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12623   if (!FD)
12624     return false;
12625
12626   return !S.checkAddressOfFunctionIsAvailable(FD,
12627                                               /*Complain=*/true,
12628                                               SrcExpr->getLocStart());
12629 }
12630
12631 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12632                                     SourceLocation Loc,
12633                                     QualType DstType, QualType SrcType,
12634                                     Expr *SrcExpr, AssignmentAction Action,
12635                                     bool *Complained) {
12636   if (Complained)
12637     *Complained = false;
12638
12639   // Decode the result (notice that AST's are still created for extensions).
12640   bool CheckInferredResultType = false;
12641   bool isInvalid = false;
12642   unsigned DiagKind = 0;
12643   FixItHint Hint;
12644   ConversionFixItGenerator ConvHints;
12645   bool MayHaveConvFixit = false;
12646   bool MayHaveFunctionDiff = false;
12647   const ObjCInterfaceDecl *IFace = nullptr;
12648   const ObjCProtocolDecl *PDecl = nullptr;
12649
12650   switch (ConvTy) {
12651   case Compatible:
12652       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12653       return false;
12654
12655   case PointerToInt:
12656     DiagKind = diag::ext_typecheck_convert_pointer_int;
12657     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12658     MayHaveConvFixit = true;
12659     break;
12660   case IntToPointer:
12661     DiagKind = diag::ext_typecheck_convert_int_pointer;
12662     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12663     MayHaveConvFixit = true;
12664     break;
12665   case IncompatiblePointer:
12666     if (Action == AA_Passing_CFAudited)
12667       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12668     else if (SrcType->isFunctionPointerType() &&
12669              DstType->isFunctionPointerType())
12670       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12671     else
12672       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12673
12674     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12675       SrcType->isObjCObjectPointerType();
12676     if (Hint.isNull() && !CheckInferredResultType) {
12677       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12678     }
12679     else if (CheckInferredResultType) {
12680       SrcType = SrcType.getUnqualifiedType();
12681       DstType = DstType.getUnqualifiedType();
12682     }
12683     MayHaveConvFixit = true;
12684     break;
12685   case IncompatiblePointerSign:
12686     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12687     break;
12688   case FunctionVoidPointer:
12689     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12690     break;
12691   case IncompatiblePointerDiscardsQualifiers: {
12692     // Perform array-to-pointer decay if necessary.
12693     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12694
12695     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12696     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12697     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12698       DiagKind = diag::err_typecheck_incompatible_address_space;
12699       break;
12700
12701
12702     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12703       DiagKind = diag::err_typecheck_incompatible_ownership;
12704       break;
12705     }
12706
12707     llvm_unreachable("unknown error case for discarding qualifiers!");
12708     // fallthrough
12709   }
12710   case CompatiblePointerDiscardsQualifiers:
12711     // If the qualifiers lost were because we were applying the
12712     // (deprecated) C++ conversion from a string literal to a char*
12713     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12714     // Ideally, this check would be performed in
12715     // checkPointerTypesForAssignment. However, that would require a
12716     // bit of refactoring (so that the second argument is an
12717     // expression, rather than a type), which should be done as part
12718     // of a larger effort to fix checkPointerTypesForAssignment for
12719     // C++ semantics.
12720     if (getLangOpts().CPlusPlus &&
12721         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12722       return false;
12723     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12724     break;
12725   case IncompatibleNestedPointerQualifiers:
12726     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12727     break;
12728   case IntToBlockPointer:
12729     DiagKind = diag::err_int_to_block_pointer;
12730     break;
12731   case IncompatibleBlockPointer:
12732     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12733     break;
12734   case IncompatibleObjCQualifiedId: {
12735     if (SrcType->isObjCQualifiedIdType()) {
12736       const ObjCObjectPointerType *srcOPT =
12737                 SrcType->getAs<ObjCObjectPointerType>();
12738       for (auto *srcProto : srcOPT->quals()) {
12739         PDecl = srcProto;
12740         break;
12741       }
12742       if (const ObjCInterfaceType *IFaceT =
12743             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12744         IFace = IFaceT->getDecl();
12745     }
12746     else if (DstType->isObjCQualifiedIdType()) {
12747       const ObjCObjectPointerType *dstOPT =
12748         DstType->getAs<ObjCObjectPointerType>();
12749       for (auto *dstProto : dstOPT->quals()) {
12750         PDecl = dstProto;
12751         break;
12752       }
12753       if (const ObjCInterfaceType *IFaceT =
12754             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12755         IFace = IFaceT->getDecl();
12756     }
12757     DiagKind = diag::warn_incompatible_qualified_id;
12758     break;
12759   }
12760   case IncompatibleVectors:
12761     DiagKind = diag::warn_incompatible_vectors;
12762     break;
12763   case IncompatibleObjCWeakRef:
12764     DiagKind = diag::err_arc_weak_unavailable_assign;
12765     break;
12766   case Incompatible:
12767     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12768       if (Complained)
12769         *Complained = true;
12770       return true;
12771     }
12772
12773     DiagKind = diag::err_typecheck_convert_incompatible;
12774     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12775     MayHaveConvFixit = true;
12776     isInvalid = true;
12777     MayHaveFunctionDiff = true;
12778     break;
12779   }
12780
12781   QualType FirstType, SecondType;
12782   switch (Action) {
12783   case AA_Assigning:
12784   case AA_Initializing:
12785     // The destination type comes first.
12786     FirstType = DstType;
12787     SecondType = SrcType;
12788     break;
12789
12790   case AA_Returning:
12791   case AA_Passing:
12792   case AA_Passing_CFAudited:
12793   case AA_Converting:
12794   case AA_Sending:
12795   case AA_Casting:
12796     // The source type comes first.
12797     FirstType = SrcType;
12798     SecondType = DstType;
12799     break;
12800   }
12801
12802   PartialDiagnostic FDiag = PDiag(DiagKind);
12803   if (Action == AA_Passing_CFAudited)
12804     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12805   else
12806     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12807
12808   // If we can fix the conversion, suggest the FixIts.
12809   assert(ConvHints.isNull() || Hint.isNull());
12810   if (!ConvHints.isNull()) {
12811     for (FixItHint &H : ConvHints.Hints)
12812       FDiag << H;
12813   } else {
12814     FDiag << Hint;
12815   }
12816   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12817
12818   if (MayHaveFunctionDiff)
12819     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12820
12821   Diag(Loc, FDiag);
12822   if (DiagKind == diag::warn_incompatible_qualified_id &&
12823       PDecl && IFace && !IFace->hasDefinition())
12824       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12825         << IFace->getName() << PDecl->getName();
12826     
12827   if (SecondType == Context.OverloadTy)
12828     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12829                               FirstType, /*TakingAddress=*/true);
12830
12831   if (CheckInferredResultType)
12832     EmitRelatedResultTypeNote(SrcExpr);
12833
12834   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12835     EmitRelatedResultTypeNoteForReturn(DstType);
12836   
12837   if (Complained)
12838     *Complained = true;
12839   return isInvalid;
12840 }
12841
12842 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12843                                                  llvm::APSInt *Result) {
12844   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12845   public:
12846     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12847       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12848     }
12849   } Diagnoser;
12850   
12851   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12852 }
12853
12854 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12855                                                  llvm::APSInt *Result,
12856                                                  unsigned DiagID,
12857                                                  bool AllowFold) {
12858   class IDDiagnoser : public VerifyICEDiagnoser {
12859     unsigned DiagID;
12860     
12861   public:
12862     IDDiagnoser(unsigned DiagID)
12863       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12864     
12865     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12866       S.Diag(Loc, DiagID) << SR;
12867     }
12868   } Diagnoser(DiagID);
12869   
12870   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12871 }
12872
12873 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12874                                             SourceRange SR) {
12875   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12876 }
12877
12878 ExprResult
12879 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12880                                       VerifyICEDiagnoser &Diagnoser,
12881                                       bool AllowFold) {
12882   SourceLocation DiagLoc = E->getLocStart();
12883
12884   if (getLangOpts().CPlusPlus11) {
12885     // C++11 [expr.const]p5:
12886     //   If an expression of literal class type is used in a context where an
12887     //   integral constant expression is required, then that class type shall
12888     //   have a single non-explicit conversion function to an integral or
12889     //   unscoped enumeration type
12890     ExprResult Converted;
12891     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12892     public:
12893       CXX11ConvertDiagnoser(bool Silent)
12894           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12895                                 Silent, true) {}
12896
12897       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12898                                            QualType T) override {
12899         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12900       }
12901
12902       SemaDiagnosticBuilder diagnoseIncomplete(
12903           Sema &S, SourceLocation Loc, QualType T) override {
12904         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12905       }
12906
12907       SemaDiagnosticBuilder diagnoseExplicitConv(
12908           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12909         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12910       }
12911
12912       SemaDiagnosticBuilder noteExplicitConv(
12913           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12914         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12915                  << ConvTy->isEnumeralType() << ConvTy;
12916       }
12917
12918       SemaDiagnosticBuilder diagnoseAmbiguous(
12919           Sema &S, SourceLocation Loc, QualType T) override {
12920         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12921       }
12922
12923       SemaDiagnosticBuilder noteAmbiguous(
12924           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12925         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12926                  << ConvTy->isEnumeralType() << ConvTy;
12927       }
12928
12929       SemaDiagnosticBuilder diagnoseConversion(
12930           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12931         llvm_unreachable("conversion functions are permitted");
12932       }
12933     } ConvertDiagnoser(Diagnoser.Suppress);
12934
12935     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12936                                                     ConvertDiagnoser);
12937     if (Converted.isInvalid())
12938       return Converted;
12939     E = Converted.get();
12940     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12941       return ExprError();
12942   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12943     // An ICE must be of integral or unscoped enumeration type.
12944     if (!Diagnoser.Suppress)
12945       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12946     return ExprError();
12947   }
12948
12949   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12950   // in the non-ICE case.
12951   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12952     if (Result)
12953       *Result = E->EvaluateKnownConstInt(Context);
12954     return E;
12955   }
12956
12957   Expr::EvalResult EvalResult;
12958   SmallVector<PartialDiagnosticAt, 8> Notes;
12959   EvalResult.Diag = &Notes;
12960
12961   // Try to evaluate the expression, and produce diagnostics explaining why it's
12962   // not a constant expression as a side-effect.
12963   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12964                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12965
12966   // In C++11, we can rely on diagnostics being produced for any expression
12967   // which is not a constant expression. If no diagnostics were produced, then
12968   // this is a constant expression.
12969   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12970     if (Result)
12971       *Result = EvalResult.Val.getInt();
12972     return E;
12973   }
12974
12975   // If our only note is the usual "invalid subexpression" note, just point
12976   // the caret at its location rather than producing an essentially
12977   // redundant note.
12978   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12979         diag::note_invalid_subexpr_in_const_expr) {
12980     DiagLoc = Notes[0].first;
12981     Notes.clear();
12982   }
12983
12984   if (!Folded || !AllowFold) {
12985     if (!Diagnoser.Suppress) {
12986       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12987       for (const PartialDiagnosticAt &Note : Notes)
12988         Diag(Note.first, Note.second);
12989     }
12990
12991     return ExprError();
12992   }
12993
12994   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12995   for (const PartialDiagnosticAt &Note : Notes)
12996     Diag(Note.first, Note.second);
12997
12998   if (Result)
12999     *Result = EvalResult.Val.getInt();
13000   return E;
13001 }
13002
13003 namespace {
13004   // Handle the case where we conclude a expression which we speculatively
13005   // considered to be unevaluated is actually evaluated.
13006   class TransformToPE : public TreeTransform<TransformToPE> {
13007     typedef TreeTransform<TransformToPE> BaseTransform;
13008
13009   public:
13010     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13011
13012     // Make sure we redo semantic analysis
13013     bool AlwaysRebuild() { return true; }
13014
13015     // Make sure we handle LabelStmts correctly.
13016     // FIXME: This does the right thing, but maybe we need a more general
13017     // fix to TreeTransform?
13018     StmtResult TransformLabelStmt(LabelStmt *S) {
13019       S->getDecl()->setStmt(nullptr);
13020       return BaseTransform::TransformLabelStmt(S);
13021     }
13022
13023     // We need to special-case DeclRefExprs referring to FieldDecls which
13024     // are not part of a member pointer formation; normal TreeTransforming
13025     // doesn't catch this case because of the way we represent them in the AST.
13026     // FIXME: This is a bit ugly; is it really the best way to handle this
13027     // case?
13028     //
13029     // Error on DeclRefExprs referring to FieldDecls.
13030     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13031       if (isa<FieldDecl>(E->getDecl()) &&
13032           !SemaRef.isUnevaluatedContext())
13033         return SemaRef.Diag(E->getLocation(),
13034                             diag::err_invalid_non_static_member_use)
13035             << E->getDecl() << E->getSourceRange();
13036
13037       return BaseTransform::TransformDeclRefExpr(E);
13038     }
13039
13040     // Exception: filter out member pointer formation
13041     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13042       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13043         return E;
13044
13045       return BaseTransform::TransformUnaryOperator(E);
13046     }
13047
13048     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13049       // Lambdas never need to be transformed.
13050       return E;
13051     }
13052   };
13053 }
13054
13055 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13056   assert(isUnevaluatedContext() &&
13057          "Should only transform unevaluated expressions");
13058   ExprEvalContexts.back().Context =
13059       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13060   if (isUnevaluatedContext())
13061     return E;
13062   return TransformToPE(*this).TransformExpr(E);
13063 }
13064
13065 void
13066 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13067                                       Decl *LambdaContextDecl,
13068                                       bool IsDecltype) {
13069   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13070                                 LambdaContextDecl, IsDecltype);
13071   Cleanup.reset();
13072   if (!MaybeODRUseExprs.empty())
13073     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13074 }
13075
13076 void
13077 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13078                                       ReuseLambdaContextDecl_t,
13079                                       bool IsDecltype) {
13080   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13081   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13082 }
13083
13084 void Sema::PopExpressionEvaluationContext() {
13085   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13086   unsigned NumTypos = Rec.NumTypos;
13087
13088   if (!Rec.Lambdas.empty()) {
13089     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13090       unsigned D;
13091       if (Rec.isUnevaluated()) {
13092         // C++11 [expr.prim.lambda]p2:
13093         //   A lambda-expression shall not appear in an unevaluated operand
13094         //   (Clause 5).
13095         D = diag::err_lambda_unevaluated_operand;
13096       } else {
13097         // C++1y [expr.const]p2:
13098         //   A conditional-expression e is a core constant expression unless the
13099         //   evaluation of e, following the rules of the abstract machine, would
13100         //   evaluate [...] a lambda-expression.
13101         D = diag::err_lambda_in_constant_expression;
13102       }
13103
13104       // C++1z allows lambda expressions as core constant expressions.
13105       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13106       // 1607) from appearing within template-arguments and array-bounds that
13107       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13108       // unevaluated contexts) might lift some of these restrictions in a 
13109       // future version.
13110       if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z)
13111         for (const auto *L : Rec.Lambdas)
13112           Diag(L->getLocStart(), D);
13113     } else {
13114       // Mark the capture expressions odr-used. This was deferred
13115       // during lambda expression creation.
13116       for (auto *Lambda : Rec.Lambdas) {
13117         for (auto *C : Lambda->capture_inits())
13118           MarkDeclarationsReferencedInExpr(C);
13119       }
13120     }
13121   }
13122
13123   // When are coming out of an unevaluated context, clear out any
13124   // temporaries that we may have created as part of the evaluation of
13125   // the expression in that context: they aren't relevant because they
13126   // will never be constructed.
13127   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13128     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13129                              ExprCleanupObjects.end());
13130     Cleanup = Rec.ParentCleanup;
13131     CleanupVarDeclMarking();
13132     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13133   // Otherwise, merge the contexts together.
13134   } else {
13135     Cleanup.mergeFrom(Rec.ParentCleanup);
13136     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13137                             Rec.SavedMaybeODRUseExprs.end());
13138   }
13139
13140   // Pop the current expression evaluation context off the stack.
13141   ExprEvalContexts.pop_back();
13142
13143   if (!ExprEvalContexts.empty())
13144     ExprEvalContexts.back().NumTypos += NumTypos;
13145   else
13146     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13147                             "last ExpressionEvaluationContextRecord");
13148 }
13149
13150 void Sema::DiscardCleanupsInEvaluationContext() {
13151   ExprCleanupObjects.erase(
13152          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13153          ExprCleanupObjects.end());
13154   Cleanup.reset();
13155   MaybeODRUseExprs.clear();
13156 }
13157
13158 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13159   if (!E->getType()->isVariablyModifiedType())
13160     return E;
13161   return TransformToPotentiallyEvaluated(E);
13162 }
13163
13164 /// Are we within a context in which some evaluation could be performed (be it
13165 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13166 /// captured by C++'s idea of an "unevaluated context".
13167 static bool isEvaluatableContext(Sema &SemaRef) {
13168   switch (SemaRef.ExprEvalContexts.back().Context) {
13169     case Sema::Unevaluated:
13170     case Sema::UnevaluatedAbstract:
13171     case Sema::DiscardedStatement:
13172       // Expressions in this context are never evaluated.
13173       return false;
13174
13175     case Sema::UnevaluatedList:
13176     case Sema::ConstantEvaluated:
13177     case Sema::PotentiallyEvaluated:
13178       // Expressions in this context could be evaluated.
13179       return true;
13180
13181     case Sema::PotentiallyEvaluatedIfUsed:
13182       // Referenced declarations will only be used if the construct in the
13183       // containing expression is used, at which point we'll be given another
13184       // turn to mark them.
13185       return false;
13186   }
13187   llvm_unreachable("Invalid context");
13188 }
13189
13190 /// Are we within a context in which references to resolved functions or to
13191 /// variables result in odr-use?
13192 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13193   // An expression in a template is not really an expression until it's been
13194   // instantiated, so it doesn't trigger odr-use.
13195   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13196     return false;
13197
13198   switch (SemaRef.ExprEvalContexts.back().Context) {
13199     case Sema::Unevaluated:
13200     case Sema::UnevaluatedList:
13201     case Sema::UnevaluatedAbstract:
13202     case Sema::DiscardedStatement:
13203       return false;
13204
13205     case Sema::ConstantEvaluated:
13206     case Sema::PotentiallyEvaluated:
13207       return true;
13208
13209     case Sema::PotentiallyEvaluatedIfUsed:
13210       return false;
13211   }
13212   llvm_unreachable("Invalid context");
13213 }
13214
13215 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13216   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13217   return Func->isConstexpr() &&
13218          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13219 }
13220
13221 /// \brief Mark a function referenced, and check whether it is odr-used
13222 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13223 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13224                                   bool MightBeOdrUse) {
13225   assert(Func && "No function?");
13226
13227   Func->setReferenced();
13228
13229   // C++11 [basic.def.odr]p3:
13230   //   A function whose name appears as a potentially-evaluated expression is
13231   //   odr-used if it is the unique lookup result or the selected member of a
13232   //   set of overloaded functions [...].
13233   //
13234   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13235   // can just check that here.
13236   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13237
13238   // Determine whether we require a function definition to exist, per
13239   // C++11 [temp.inst]p3:
13240   //   Unless a function template specialization has been explicitly
13241   //   instantiated or explicitly specialized, the function template
13242   //   specialization is implicitly instantiated when the specialization is
13243   //   referenced in a context that requires a function definition to exist.
13244   //
13245   // That is either when this is an odr-use, or when a usage of a constexpr
13246   // function occurs within an evaluatable context.
13247   bool NeedDefinition =
13248       OdrUse || (isEvaluatableContext(*this) &&
13249                  isImplicitlyDefinableConstexprFunction(Func));
13250
13251   // C++14 [temp.expl.spec]p6:
13252   //   If a template [...] is explicitly specialized then that specialization
13253   //   shall be declared before the first use of that specialization that would
13254   //   cause an implicit instantiation to take place, in every translation unit
13255   //   in which such a use occurs
13256   if (NeedDefinition &&
13257       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13258        Func->getMemberSpecializationInfo()))
13259     checkSpecializationVisibility(Loc, Func);
13260
13261   // C++14 [except.spec]p17:
13262   //   An exception-specification is considered to be needed when:
13263   //   - the function is odr-used or, if it appears in an unevaluated operand,
13264   //     would be odr-used if the expression were potentially-evaluated;
13265   //
13266   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13267   // function is a pure virtual function we're calling, and in that case the
13268   // function was selected by overload resolution and we need to resolve its
13269   // exception specification for a different reason.
13270   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13271   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13272     ResolveExceptionSpec(Loc, FPT);
13273
13274   // If we don't need to mark the function as used, and we don't need to
13275   // try to provide a definition, there's nothing more to do.
13276   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13277       (!NeedDefinition || Func->getBody()))
13278     return;
13279
13280   // Note that this declaration has been used.
13281   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13282     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13283     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13284       if (Constructor->isDefaultConstructor()) {
13285         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13286           return;
13287         DefineImplicitDefaultConstructor(Loc, Constructor);
13288       } else if (Constructor->isCopyConstructor()) {
13289         DefineImplicitCopyConstructor(Loc, Constructor);
13290       } else if (Constructor->isMoveConstructor()) {
13291         DefineImplicitMoveConstructor(Loc, Constructor);
13292       }
13293     } else if (Constructor->getInheritedConstructor()) {
13294       DefineInheritingConstructor(Loc, Constructor);
13295     }
13296   } else if (CXXDestructorDecl *Destructor =
13297                  dyn_cast<CXXDestructorDecl>(Func)) {
13298     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13299     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13300       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13301         return;
13302       DefineImplicitDestructor(Loc, Destructor);
13303     }
13304     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13305       MarkVTableUsed(Loc, Destructor->getParent());
13306   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13307     if (MethodDecl->isOverloadedOperator() &&
13308         MethodDecl->getOverloadedOperator() == OO_Equal) {
13309       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13310       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13311         if (MethodDecl->isCopyAssignmentOperator())
13312           DefineImplicitCopyAssignment(Loc, MethodDecl);
13313         else if (MethodDecl->isMoveAssignmentOperator())
13314           DefineImplicitMoveAssignment(Loc, MethodDecl);
13315       }
13316     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13317                MethodDecl->getParent()->isLambda()) {
13318       CXXConversionDecl *Conversion =
13319           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13320       if (Conversion->isLambdaToBlockPointerConversion())
13321         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13322       else
13323         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13324     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13325       MarkVTableUsed(Loc, MethodDecl->getParent());
13326   }
13327
13328   // Recursive functions should be marked when used from another function.
13329   // FIXME: Is this really right?
13330   if (CurContext == Func) return;
13331
13332   // Implicit instantiation of function templates and member functions of
13333   // class templates.
13334   if (Func->isImplicitlyInstantiable()) {
13335     bool AlreadyInstantiated = false;
13336     SourceLocation PointOfInstantiation = Loc;
13337     if (FunctionTemplateSpecializationInfo *SpecInfo
13338                               = Func->getTemplateSpecializationInfo()) {
13339       if (SpecInfo->getPointOfInstantiation().isInvalid())
13340         SpecInfo->setPointOfInstantiation(Loc);
13341       else if (SpecInfo->getTemplateSpecializationKind()
13342                  == TSK_ImplicitInstantiation) {
13343         AlreadyInstantiated = true;
13344         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13345       }
13346     } else if (MemberSpecializationInfo *MSInfo
13347                                 = Func->getMemberSpecializationInfo()) {
13348       if (MSInfo->getPointOfInstantiation().isInvalid())
13349         MSInfo->setPointOfInstantiation(Loc);
13350       else if (MSInfo->getTemplateSpecializationKind()
13351                  == TSK_ImplicitInstantiation) {
13352         AlreadyInstantiated = true;
13353         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13354       }
13355     }
13356
13357     if (!AlreadyInstantiated || Func->isConstexpr()) {
13358       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13359           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13360           ActiveTemplateInstantiations.size())
13361         PendingLocalImplicitInstantiations.push_back(
13362             std::make_pair(Func, PointOfInstantiation));
13363       else if (Func->isConstexpr())
13364         // Do not defer instantiations of constexpr functions, to avoid the
13365         // expression evaluator needing to call back into Sema if it sees a
13366         // call to such a function.
13367         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13368       else {
13369         PendingInstantiations.push_back(std::make_pair(Func,
13370                                                        PointOfInstantiation));
13371         // Notify the consumer that a function was implicitly instantiated.
13372         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13373       }
13374     }
13375   } else {
13376     // Walk redefinitions, as some of them may be instantiable.
13377     for (auto i : Func->redecls()) {
13378       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13379         MarkFunctionReferenced(Loc, i, OdrUse);
13380     }
13381   }
13382
13383   if (!OdrUse) return;
13384
13385   // Keep track of used but undefined functions.
13386   if (!Func->isDefined()) {
13387     if (mightHaveNonExternalLinkage(Func))
13388       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13389     else if (Func->getMostRecentDecl()->isInlined() &&
13390              !LangOpts.GNUInline &&
13391              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13392       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13393   }
13394
13395   Func->markUsed(Context);
13396 }
13397
13398 static void
13399 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13400                                    ValueDecl *var, DeclContext *DC) {
13401   DeclContext *VarDC = var->getDeclContext();
13402
13403   //  If the parameter still belongs to the translation unit, then
13404   //  we're actually just using one parameter in the declaration of
13405   //  the next.
13406   if (isa<ParmVarDecl>(var) &&
13407       isa<TranslationUnitDecl>(VarDC))
13408     return;
13409
13410   // For C code, don't diagnose about capture if we're not actually in code
13411   // right now; it's impossible to write a non-constant expression outside of
13412   // function context, so we'll get other (more useful) diagnostics later.
13413   //
13414   // For C++, things get a bit more nasty... it would be nice to suppress this
13415   // diagnostic for certain cases like using a local variable in an array bound
13416   // for a member of a local class, but the correct predicate is not obvious.
13417   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13418     return;
13419
13420   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13421   unsigned ContextKind = 3; // unknown
13422   if (isa<CXXMethodDecl>(VarDC) &&
13423       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13424     ContextKind = 2;
13425   } else if (isa<FunctionDecl>(VarDC)) {
13426     ContextKind = 0;
13427   } else if (isa<BlockDecl>(VarDC)) {
13428     ContextKind = 1;
13429   }
13430
13431   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13432     << var << ValueKind << ContextKind << VarDC;
13433   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13434       << var;
13435
13436   // FIXME: Add additional diagnostic info about class etc. which prevents
13437   // capture.
13438 }
13439
13440  
13441 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
13442                                       bool &SubCapturesAreNested,
13443                                       QualType &CaptureType, 
13444                                       QualType &DeclRefType) {
13445    // Check whether we've already captured it.
13446   if (CSI->CaptureMap.count(Var)) {
13447     // If we found a capture, any subcaptures are nested.
13448     SubCapturesAreNested = true;
13449       
13450     // Retrieve the capture type for this variable.
13451     CaptureType = CSI->getCapture(Var).getCaptureType();
13452       
13453     // Compute the type of an expression that refers to this variable.
13454     DeclRefType = CaptureType.getNonReferenceType();
13455
13456     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13457     // are mutable in the sense that user can change their value - they are
13458     // private instances of the captured declarations.
13459     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13460     if (Cap.isCopyCapture() &&
13461         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13462         !(isa<CapturedRegionScopeInfo>(CSI) &&
13463           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13464       DeclRefType.addConst();
13465     return true;
13466   }
13467   return false;
13468 }
13469
13470 // Only block literals, captured statements, and lambda expressions can
13471 // capture; other scopes don't work.
13472 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
13473                                  SourceLocation Loc, 
13474                                  const bool Diagnose, Sema &S) {
13475   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13476     return getLambdaAwareParentOfDeclContext(DC);
13477   else if (Var->hasLocalStorage()) {
13478     if (Diagnose)
13479        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13480   }
13481   return nullptr;
13482 }
13483
13484 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13485 // certain types of variables (unnamed, variably modified types etc.)
13486 // so check for eligibility.
13487 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
13488                                  SourceLocation Loc, 
13489                                  const bool Diagnose, Sema &S) {
13490
13491   bool IsBlock = isa<BlockScopeInfo>(CSI);
13492   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13493
13494   // Lambdas are not allowed to capture unnamed variables
13495   // (e.g. anonymous unions).
13496   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13497   // assuming that's the intent.
13498   if (IsLambda && !Var->getDeclName()) {
13499     if (Diagnose) {
13500       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13501       S.Diag(Var->getLocation(), diag::note_declared_at);
13502     }
13503     return false;
13504   }
13505
13506   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13507   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13508     if (Diagnose) {
13509       S.Diag(Loc, diag::err_ref_vm_type);
13510       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13511         << Var->getDeclName();
13512     }
13513     return false;
13514   }
13515   // Prohibit structs with flexible array members too.
13516   // We cannot capture what is in the tail end of the struct.
13517   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13518     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13519       if (Diagnose) {
13520         if (IsBlock)
13521           S.Diag(Loc, diag::err_ref_flexarray_type);
13522         else
13523           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13524             << Var->getDeclName();
13525         S.Diag(Var->getLocation(), diag::note_previous_decl)
13526           << Var->getDeclName();
13527       }
13528       return false;
13529     }
13530   }
13531   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13532   // Lambdas and captured statements are not allowed to capture __block
13533   // variables; they don't support the expected semantics.
13534   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13535     if (Diagnose) {
13536       S.Diag(Loc, diag::err_capture_block_variable)
13537         << Var->getDeclName() << !IsLambda;
13538       S.Diag(Var->getLocation(), diag::note_previous_decl)
13539         << Var->getDeclName();
13540     }
13541     return false;
13542   }
13543
13544   return true;
13545 }
13546
13547 // Returns true if the capture by block was successful.
13548 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
13549                                  SourceLocation Loc, 
13550                                  const bool BuildAndDiagnose, 
13551                                  QualType &CaptureType,
13552                                  QualType &DeclRefType, 
13553                                  const bool Nested,
13554                                  Sema &S) {
13555   Expr *CopyExpr = nullptr;
13556   bool ByRef = false;
13557       
13558   // Blocks are not allowed to capture arrays.
13559   if (CaptureType->isArrayType()) {
13560     if (BuildAndDiagnose) {
13561       S.Diag(Loc, diag::err_ref_array_type);
13562       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13563       << Var->getDeclName();
13564     }
13565     return false;
13566   }
13567
13568   // Forbid the block-capture of autoreleasing variables.
13569   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13570     if (BuildAndDiagnose) {
13571       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13572         << /*block*/ 0;
13573       S.Diag(Var->getLocation(), diag::note_previous_decl)
13574         << Var->getDeclName();
13575     }
13576     return false;
13577   }
13578
13579   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13580   if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13581     QualType PointeeTy = PT->getPointeeType();
13582     if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13583         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13584         !isa<AttributedType>(PointeeTy)) {
13585       if (BuildAndDiagnose) {
13586         SourceLocation VarLoc = Var->getLocation();
13587         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13588         S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13589             FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13590         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13591       }
13592     }
13593   }
13594
13595   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13596   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13597       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13598     // Block capture by reference does not change the capture or
13599     // declaration reference types.
13600     ByRef = true;
13601   } else {
13602     // Block capture by copy introduces 'const'.
13603     CaptureType = CaptureType.getNonReferenceType().withConst();
13604     DeclRefType = CaptureType;
13605                 
13606     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13607       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13608         // The capture logic needs the destructor, so make sure we mark it.
13609         // Usually this is unnecessary because most local variables have
13610         // their destructors marked at declaration time, but parameters are
13611         // an exception because it's technically only the call site that
13612         // actually requires the destructor.
13613         if (isa<ParmVarDecl>(Var))
13614           S.FinalizeVarWithDestructor(Var, Record);
13615
13616         // Enter a new evaluation context to insulate the copy
13617         // full-expression.
13618         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13619
13620         // According to the blocks spec, the capture of a variable from
13621         // the stack requires a const copy constructor.  This is not true
13622         // of the copy/move done to move a __block variable to the heap.
13623         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13624                                                   DeclRefType.withConst(), 
13625                                                   VK_LValue, Loc);
13626             
13627         ExprResult Result
13628           = S.PerformCopyInitialization(
13629               InitializedEntity::InitializeBlock(Var->getLocation(),
13630                                                   CaptureType, false),
13631               Loc, DeclRef);
13632             
13633         // Build a full-expression copy expression if initialization
13634         // succeeded and used a non-trivial constructor.  Recover from
13635         // errors by pretending that the copy isn't necessary.
13636         if (!Result.isInvalid() &&
13637             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13638                 ->isTrivial()) {
13639           Result = S.MaybeCreateExprWithCleanups(Result);
13640           CopyExpr = Result.get();
13641         }
13642       }
13643     }
13644   }
13645
13646   // Actually capture the variable.
13647   if (BuildAndDiagnose)
13648     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
13649                     SourceLocation(), CaptureType, CopyExpr);
13650
13651   return true;
13652
13653 }
13654
13655
13656 /// \brief Capture the given variable in the captured region.
13657 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13658                                     VarDecl *Var, 
13659                                     SourceLocation Loc, 
13660                                     const bool BuildAndDiagnose, 
13661                                     QualType &CaptureType,
13662                                     QualType &DeclRefType, 
13663                                     const bool RefersToCapturedVariable,
13664                                     Sema &S) {
13665   // By default, capture variables by reference.
13666   bool ByRef = true;
13667   // Using an LValue reference type is consistent with Lambdas (see below).
13668   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13669     if (S.IsOpenMPCapturedDecl(Var))
13670       DeclRefType = DeclRefType.getUnqualifiedType();
13671     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13672   }
13673
13674   if (ByRef)
13675     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13676   else
13677     CaptureType = DeclRefType;
13678
13679   Expr *CopyExpr = nullptr;
13680   if (BuildAndDiagnose) {
13681     // The current implementation assumes that all variables are captured
13682     // by references. Since there is no capture by copy, no expression
13683     // evaluation will be needed.
13684     RecordDecl *RD = RSI->TheRecordDecl;
13685
13686     FieldDecl *Field
13687       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13688                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13689                           nullptr, false, ICIS_NoInit);
13690     Field->setImplicit(true);
13691     Field->setAccess(AS_private);
13692     RD->addDecl(Field);
13693  
13694     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13695                                             DeclRefType, VK_LValue, Loc);
13696     Var->setReferenced(true);
13697     Var->markUsed(S.Context);
13698   }
13699
13700   // Actually capture the variable.
13701   if (BuildAndDiagnose)
13702     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13703                     SourceLocation(), CaptureType, CopyExpr);
13704   
13705   
13706   return true;
13707 }
13708
13709 /// \brief Create a field within the lambda class for the variable
13710 /// being captured.
13711 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 
13712                                     QualType FieldType, QualType DeclRefType,
13713                                     SourceLocation Loc,
13714                                     bool RefersToCapturedVariable) {
13715   CXXRecordDecl *Lambda = LSI->Lambda;
13716
13717   // Build the non-static data member.
13718   FieldDecl *Field
13719     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13720                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13721                         nullptr, false, ICIS_NoInit);
13722   Field->setImplicit(true);
13723   Field->setAccess(AS_private);
13724   Lambda->addDecl(Field);
13725 }
13726
13727 /// \brief Capture the given variable in the lambda.
13728 static bool captureInLambda(LambdaScopeInfo *LSI,
13729                             VarDecl *Var, 
13730                             SourceLocation Loc, 
13731                             const bool BuildAndDiagnose, 
13732                             QualType &CaptureType,
13733                             QualType &DeclRefType, 
13734                             const bool RefersToCapturedVariable,
13735                             const Sema::TryCaptureKind Kind, 
13736                             SourceLocation EllipsisLoc,
13737                             const bool IsTopScope,
13738                             Sema &S) {
13739
13740   // Determine whether we are capturing by reference or by value.
13741   bool ByRef = false;
13742   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13743     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13744   } else {
13745     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13746   }
13747     
13748   // Compute the type of the field that will capture this variable.
13749   if (ByRef) {
13750     // C++11 [expr.prim.lambda]p15:
13751     //   An entity is captured by reference if it is implicitly or
13752     //   explicitly captured but not captured by copy. It is
13753     //   unspecified whether additional unnamed non-static data
13754     //   members are declared in the closure type for entities
13755     //   captured by reference.
13756     //
13757     // FIXME: It is not clear whether we want to build an lvalue reference
13758     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13759     // to do the former, while EDG does the latter. Core issue 1249 will 
13760     // clarify, but for now we follow GCC because it's a more permissive and
13761     // easily defensible position.
13762     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13763   } else {
13764     // C++11 [expr.prim.lambda]p14:
13765     //   For each entity captured by copy, an unnamed non-static
13766     //   data member is declared in the closure type. The
13767     //   declaration order of these members is unspecified. The type
13768     //   of such a data member is the type of the corresponding
13769     //   captured entity if the entity is not a reference to an
13770     //   object, or the referenced type otherwise. [Note: If the
13771     //   captured entity is a reference to a function, the
13772     //   corresponding data member is also a reference to a
13773     //   function. - end note ]
13774     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13775       if (!RefType->getPointeeType()->isFunctionType())
13776         CaptureType = RefType->getPointeeType();
13777     }
13778
13779     // Forbid the lambda copy-capture of autoreleasing variables.
13780     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13781       if (BuildAndDiagnose) {
13782         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13783         S.Diag(Var->getLocation(), diag::note_previous_decl)
13784           << Var->getDeclName();
13785       }
13786       return false;
13787     }
13788
13789     // Make sure that by-copy captures are of a complete and non-abstract type.
13790     if (BuildAndDiagnose) {
13791       if (!CaptureType->isDependentType() &&
13792           S.RequireCompleteType(Loc, CaptureType,
13793                                 diag::err_capture_of_incomplete_type,
13794                                 Var->getDeclName()))
13795         return false;
13796
13797       if (S.RequireNonAbstractType(Loc, CaptureType,
13798                                    diag::err_capture_of_abstract_type))
13799         return false;
13800     }
13801   }
13802
13803   // Capture this variable in the lambda.
13804   if (BuildAndDiagnose)
13805     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13806                             RefersToCapturedVariable);
13807     
13808   // Compute the type of a reference to this captured variable.
13809   if (ByRef)
13810     DeclRefType = CaptureType.getNonReferenceType();
13811   else {
13812     // C++ [expr.prim.lambda]p5:
13813     //   The closure type for a lambda-expression has a public inline 
13814     //   function call operator [...]. This function call operator is 
13815     //   declared const (9.3.1) if and only if the lambda-expression's 
13816     //   parameter-declaration-clause is not followed by mutable.
13817     DeclRefType = CaptureType.getNonReferenceType();
13818     if (!LSI->Mutable && !CaptureType->isReferenceType())
13819       DeclRefType.addConst();      
13820   }
13821     
13822   // Add the capture.
13823   if (BuildAndDiagnose)
13824     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
13825                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13826       
13827   return true;
13828 }
13829
13830 bool Sema::tryCaptureVariable(
13831     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13832     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13833     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13834   // An init-capture is notionally from the context surrounding its
13835   // declaration, but its parent DC is the lambda class.
13836   DeclContext *VarDC = Var->getDeclContext();
13837   if (Var->isInitCapture())
13838     VarDC = VarDC->getParent();
13839   
13840   DeclContext *DC = CurContext;
13841   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
13842       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
13843   // We need to sync up the Declaration Context with the
13844   // FunctionScopeIndexToStopAt
13845   if (FunctionScopeIndexToStopAt) {
13846     unsigned FSIndex = FunctionScopes.size() - 1;
13847     while (FSIndex != MaxFunctionScopesIndex) {
13848       DC = getLambdaAwareParentOfDeclContext(DC);
13849       --FSIndex;
13850     }
13851   }
13852
13853   
13854   // If the variable is declared in the current context, there is no need to
13855   // capture it.
13856   if (VarDC == DC) return true;
13857
13858   // Capture global variables if it is required to use private copy of this
13859   // variable.
13860   bool IsGlobal = !Var->hasLocalStorage();
13861   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13862     return true;
13863
13864   // Walk up the stack to determine whether we can capture the variable,
13865   // performing the "simple" checks that don't depend on type. We stop when
13866   // we've either hit the declared scope of the variable or find an existing
13867   // capture of that variable.  We start from the innermost capturing-entity
13868   // (the DC) and ensure that all intervening capturing-entities 
13869   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13870   // declcontext can either capture the variable or have already captured
13871   // the variable.
13872   CaptureType = Var->getType();
13873   DeclRefType = CaptureType.getNonReferenceType();
13874   bool Nested = false;
13875   bool Explicit = (Kind != TryCapture_Implicit);
13876   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13877   do {
13878     // Only block literals, captured statements, and lambda expressions can
13879     // capture; other scopes don't work.
13880     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
13881                                                               ExprLoc, 
13882                                                               BuildAndDiagnose,
13883                                                               *this);
13884     // We need to check for the parent *first* because, if we *have*
13885     // private-captured a global variable, we need to recursively capture it in
13886     // intermediate blocks, lambdas, etc.
13887     if (!ParentDC) {
13888       if (IsGlobal) {
13889         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13890         break;
13891       }
13892       return true;
13893     }
13894
13895     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13896     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13897
13898
13899     // Check whether we've already captured it.
13900     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
13901                                              DeclRefType)) 
13902       break;
13903     // If we are instantiating a generic lambda call operator body, 
13904     // we do not want to capture new variables.  What was captured
13905     // during either a lambdas transformation or initial parsing
13906     // should be used. 
13907     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13908       if (BuildAndDiagnose) {
13909         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
13910         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13911           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13912           Diag(Var->getLocation(), diag::note_previous_decl) 
13913              << Var->getDeclName();
13914           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
13915         } else
13916           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13917       }
13918       return true;
13919     }
13920     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13921     // certain types of variables (unnamed, variably modified types etc.)
13922     // so check for eligibility.
13923     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13924        return true;
13925
13926     // Try to capture variable-length arrays types.
13927     if (Var->getType()->isVariablyModifiedType()) {
13928       // We're going to walk down into the type and look for VLA
13929       // expressions.
13930       QualType QTy = Var->getType();
13931       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13932         QTy = PVD->getOriginalType();
13933       captureVariablyModifiedType(Context, QTy, CSI);
13934     }
13935
13936     if (getLangOpts().OpenMP) {
13937       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13938         // OpenMP private variables should not be captured in outer scope, so
13939         // just break here. Similarly, global variables that are captured in a
13940         // target region should not be captured outside the scope of the region.
13941         if (RSI->CapRegionKind == CR_OpenMP) {
13942           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13943           // When we detect target captures we are looking from inside the
13944           // target region, therefore we need to propagate the capture from the
13945           // enclosing region. Therefore, the capture is not initially nested.
13946           if (IsTargetCap)
13947             FunctionScopesIndex--;
13948
13949           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13950             Nested = !IsTargetCap;
13951             DeclRefType = DeclRefType.getUnqualifiedType();
13952             CaptureType = Context.getLValueReferenceType(DeclRefType);
13953             break;
13954           }
13955         }
13956       }
13957     }
13958     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13959       // No capture-default, and this is not an explicit capture 
13960       // so cannot capture this variable.  
13961       if (BuildAndDiagnose) {
13962         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13963         Diag(Var->getLocation(), diag::note_previous_decl) 
13964           << Var->getDeclName();
13965         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13966           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13967                diag::note_lambda_decl);
13968         // FIXME: If we error out because an outer lambda can not implicitly
13969         // capture a variable that an inner lambda explicitly captures, we
13970         // should have the inner lambda do the explicit capture - because
13971         // it makes for cleaner diagnostics later.  This would purely be done
13972         // so that the diagnostic does not misleadingly claim that a variable 
13973         // can not be captured by a lambda implicitly even though it is captured 
13974         // explicitly.  Suggestion:
13975         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
13976         //    at the function head
13977         //  - cache the StartingDeclContext - this must be a lambda 
13978         //  - captureInLambda in the innermost lambda the variable.
13979       }
13980       return true;
13981     }
13982
13983     FunctionScopesIndex--;
13984     DC = ParentDC;
13985     Explicit = false;
13986   } while (!VarDC->Equals(DC));
13987
13988   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13989   // computing the type of the capture at each step, checking type-specific 
13990   // requirements, and adding captures if requested. 
13991   // If the variable had already been captured previously, we start capturing 
13992   // at the lambda nested within that one.   
13993   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
13994        ++I) {
13995     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13996     
13997     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13998       if (!captureInBlock(BSI, Var, ExprLoc, 
13999                           BuildAndDiagnose, CaptureType, 
14000                           DeclRefType, Nested, *this))
14001         return true;
14002       Nested = true;
14003     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14004       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
14005                                    BuildAndDiagnose, CaptureType, 
14006                                    DeclRefType, Nested, *this))
14007         return true;
14008       Nested = true;
14009     } else {
14010       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14011       if (!captureInLambda(LSI, Var, ExprLoc, 
14012                            BuildAndDiagnose, CaptureType, 
14013                            DeclRefType, Nested, Kind, EllipsisLoc, 
14014                             /*IsTopScope*/I == N - 1, *this))
14015         return true;
14016       Nested = true;
14017     }
14018   }
14019   return false;
14020 }
14021
14022 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14023                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
14024   QualType CaptureType;
14025   QualType DeclRefType;
14026   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14027                             /*BuildAndDiagnose=*/true, CaptureType,
14028                             DeclRefType, nullptr);
14029 }
14030
14031 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14032   QualType CaptureType;
14033   QualType DeclRefType;
14034   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14035                              /*BuildAndDiagnose=*/false, CaptureType,
14036                              DeclRefType, nullptr);
14037 }
14038
14039 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14040   QualType CaptureType;
14041   QualType DeclRefType;
14042   
14043   // Determine whether we can capture this variable.
14044   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14045                          /*BuildAndDiagnose=*/false, CaptureType, 
14046                          DeclRefType, nullptr))
14047     return QualType();
14048
14049   return DeclRefType;
14050 }
14051
14052
14053
14054 // If either the type of the variable or the initializer is dependent, 
14055 // return false. Otherwise, determine whether the variable is a constant
14056 // expression. Use this if you need to know if a variable that might or
14057 // might not be dependent is truly a constant expression.
14058 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
14059     ASTContext &Context) {
14060  
14061   if (Var->getType()->isDependentType()) 
14062     return false;
14063   const VarDecl *DefVD = nullptr;
14064   Var->getAnyInitializer(DefVD);
14065   if (!DefVD) 
14066     return false;
14067   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14068   Expr *Init = cast<Expr>(Eval->Value);
14069   if (Init->isValueDependent()) 
14070     return false;
14071   return IsVariableAConstantExpression(Var, Context); 
14072 }
14073
14074
14075 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14076   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
14077   // an object that satisfies the requirements for appearing in a
14078   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14079   // is immediately applied."  This function handles the lvalue-to-rvalue
14080   // conversion part.
14081   MaybeODRUseExprs.erase(E->IgnoreParens());
14082   
14083   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14084   // to a variable that is a constant expression, and if so, identify it as
14085   // a reference to a variable that does not involve an odr-use of that 
14086   // variable. 
14087   if (LambdaScopeInfo *LSI = getCurLambda()) {
14088     Expr *SansParensExpr = E->IgnoreParens();
14089     VarDecl *Var = nullptr;
14090     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
14091       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14092     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14093       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14094     
14095     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
14096       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
14097   }
14098 }
14099
14100 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14101   Res = CorrectDelayedTyposInExpr(Res);
14102
14103   if (!Res.isUsable())
14104     return Res;
14105
14106   // If a constant-expression is a reference to a variable where we delay
14107   // deciding whether it is an odr-use, just assume we will apply the
14108   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14109   // (a non-type template argument), we have special handling anyway.
14110   UpdateMarkingForLValueToRValue(Res.get());
14111   return Res;
14112 }
14113
14114 void Sema::CleanupVarDeclMarking() {
14115   for (Expr *E : MaybeODRUseExprs) {
14116     VarDecl *Var;
14117     SourceLocation Loc;
14118     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14119       Var = cast<VarDecl>(DRE->getDecl());
14120       Loc = DRE->getLocation();
14121     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14122       Var = cast<VarDecl>(ME->getMemberDecl());
14123       Loc = ME->getMemberLoc();
14124     } else {
14125       llvm_unreachable("Unexpected expression");
14126     }
14127
14128     MarkVarDeclODRUsed(Var, Loc, *this,
14129                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14130   }
14131
14132   MaybeODRUseExprs.clear();
14133 }
14134
14135
14136 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14137                                     VarDecl *Var, Expr *E) {
14138   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14139          "Invalid Expr argument to DoMarkVarDeclReferenced");
14140   Var->setReferenced();
14141
14142   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14143
14144   bool OdrUseContext = isOdrUseContext(SemaRef);
14145   bool NeedDefinition =
14146       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14147                         Var->isUsableInConstantExpressions(SemaRef.Context));
14148
14149   VarTemplateSpecializationDecl *VarSpec =
14150       dyn_cast<VarTemplateSpecializationDecl>(Var);
14151   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14152          "Can't instantiate a partial template specialization.");
14153
14154   // If this might be a member specialization of a static data member, check
14155   // the specialization is visible. We already did the checks for variable
14156   // template specializations when we created them.
14157   if (NeedDefinition && TSK != TSK_Undeclared &&
14158       !isa<VarTemplateSpecializationDecl>(Var))
14159     SemaRef.checkSpecializationVisibility(Loc, Var);
14160
14161   // Perform implicit instantiation of static data members, static data member
14162   // templates of class templates, and variable template specializations. Delay
14163   // instantiations of variable templates, except for those that could be used
14164   // in a constant expression.
14165   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14166     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14167
14168     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14169       if (Var->getPointOfInstantiation().isInvalid()) {
14170         // This is a modification of an existing AST node. Notify listeners.
14171         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14172           L->StaticDataMemberInstantiated(Var);
14173       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14174         // Don't bother trying to instantiate it again, unless we might need
14175         // its initializer before we get to the end of the TU.
14176         TryInstantiating = false;
14177     }
14178
14179     if (Var->getPointOfInstantiation().isInvalid())
14180       Var->setTemplateSpecializationKind(TSK, Loc);
14181
14182     if (TryInstantiating) {
14183       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14184       bool InstantiationDependent = false;
14185       bool IsNonDependent =
14186           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14187                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14188                   : true;
14189
14190       // Do not instantiate specializations that are still type-dependent.
14191       if (IsNonDependent) {
14192         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14193           // Do not defer instantiations of variables which could be used in a
14194           // constant expression.
14195           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14196         } else {
14197           SemaRef.PendingInstantiations
14198               .push_back(std::make_pair(Var, PointOfInstantiation));
14199         }
14200       }
14201     }
14202   }
14203
14204   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14205   // the requirements for appearing in a constant expression (5.19) and, if
14206   // it is an object, the lvalue-to-rvalue conversion (4.1)
14207   // is immediately applied."  We check the first part here, and
14208   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14209   // Note that we use the C++11 definition everywhere because nothing in
14210   // C++03 depends on whether we get the C++03 version correct. The second
14211   // part does not apply to references, since they are not objects.
14212   if (OdrUseContext && E &&
14213       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14214     // A reference initialized by a constant expression can never be
14215     // odr-used, so simply ignore it.
14216     if (!Var->getType()->isReferenceType())
14217       SemaRef.MaybeODRUseExprs.insert(E);
14218   } else if (OdrUseContext) {
14219     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14220                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14221   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14222     // If this is a dependent context, we don't need to mark variables as
14223     // odr-used, but we may still need to track them for lambda capture.
14224     // FIXME: Do we also need to do this inside dependent typeid expressions
14225     // (which are modeled as unevaluated at this point)?
14226     const bool RefersToEnclosingScope =
14227         (SemaRef.CurContext != Var->getDeclContext() &&
14228          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14229     if (RefersToEnclosingScope) {
14230       if (LambdaScopeInfo *const LSI =
14231               SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14232         // If a variable could potentially be odr-used, defer marking it so
14233         // until we finish analyzing the full expression for any
14234         // lvalue-to-rvalue
14235         // or discarded value conversions that would obviate odr-use.
14236         // Add it to the list of potential captures that will be analyzed
14237         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14238         // unless the variable is a reference that was initialized by a constant
14239         // expression (this will never need to be captured or odr-used).
14240         assert(E && "Capture variable should be used in an expression.");
14241         if (!Var->getType()->isReferenceType() ||
14242             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14243           LSI->addPotentialCapture(E->IgnoreParens());
14244       }
14245     }
14246   }
14247 }
14248
14249 /// \brief Mark a variable referenced, and check whether it is odr-used
14250 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14251 /// used directly for normal expressions referring to VarDecl.
14252 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14253   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14254 }
14255
14256 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14257                                Decl *D, Expr *E, bool MightBeOdrUse) {
14258   if (SemaRef.isInOpenMPDeclareTargetContext())
14259     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14260
14261   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14262     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14263     return;
14264   }
14265
14266   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14267
14268   // If this is a call to a method via a cast, also mark the method in the
14269   // derived class used in case codegen can devirtualize the call.
14270   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14271   if (!ME)
14272     return;
14273   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14274   if (!MD)
14275     return;
14276   // Only attempt to devirtualize if this is truly a virtual call.
14277   bool IsVirtualCall = MD->isVirtual() &&
14278                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14279   if (!IsVirtualCall)
14280     return;
14281   const Expr *Base = ME->getBase();
14282   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14283   if (!MostDerivedClassDecl)
14284     return;
14285   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14286   if (!DM || DM->isPure())
14287     return;
14288   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14289
14290
14291 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14292 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14293   // TODO: update this with DR# once a defect report is filed.
14294   // C++11 defect. The address of a pure member should not be an ODR use, even
14295   // if it's a qualified reference.
14296   bool OdrUse = true;
14297   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14298     if (Method->isVirtual())
14299       OdrUse = false;
14300   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14301 }
14302
14303 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14304 void Sema::MarkMemberReferenced(MemberExpr *E) {
14305   // C++11 [basic.def.odr]p2:
14306   //   A non-overloaded function whose name appears as a potentially-evaluated
14307   //   expression or a member of a set of candidate functions, if selected by
14308   //   overload resolution when referred to from a potentially-evaluated
14309   //   expression, is odr-used, unless it is a pure virtual function and its
14310   //   name is not explicitly qualified.
14311   bool MightBeOdrUse = true;
14312   if (E->performsVirtualDispatch(getLangOpts())) {
14313     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14314       if (Method->isPure())
14315         MightBeOdrUse = false;
14316   }
14317   SourceLocation Loc = E->getMemberLoc().isValid() ?
14318                             E->getMemberLoc() : E->getLocStart();
14319   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14320 }
14321
14322 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14323 /// marks the declaration referenced, and performs odr-use checking for
14324 /// functions and variables. This method should not be used when building a
14325 /// normal expression which refers to a variable.
14326 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14327                                  bool MightBeOdrUse) {
14328   if (MightBeOdrUse) {
14329     if (auto *VD = dyn_cast<VarDecl>(D)) {
14330       MarkVariableReferenced(Loc, VD);
14331       return;
14332     }
14333   }
14334   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14335     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14336     return;
14337   }
14338   D->setReferenced();
14339 }
14340
14341 namespace {
14342   // Mark all of the declarations used by a type as referenced.
14343   // FIXME: Not fully implemented yet! We need to have a better understanding
14344   // of when we're entering a context we should not recurse into.
14345   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14346   // TreeTransforms rebuilding the type in a new context. Rather than
14347   // duplicating the TreeTransform logic, we should consider reusing it here.
14348   // Currently that causes problems when rebuilding LambdaExprs.
14349   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14350     Sema &S;
14351     SourceLocation Loc;
14352
14353   public:
14354     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14355
14356     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14357
14358     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14359   };
14360 }
14361
14362 bool MarkReferencedDecls::TraverseTemplateArgument(
14363     const TemplateArgument &Arg) {
14364   {
14365     // A non-type template argument is a constant-evaluated context.
14366     EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated);
14367     if (Arg.getKind() == TemplateArgument::Declaration) {
14368       if (Decl *D = Arg.getAsDecl())
14369         S.MarkAnyDeclReferenced(Loc, D, true);
14370     } else if (Arg.getKind() == TemplateArgument::Expression) {
14371       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14372     }
14373   }
14374
14375   return Inherited::TraverseTemplateArgument(Arg);
14376 }
14377
14378 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14379   MarkReferencedDecls Marker(*this, Loc);
14380   Marker.TraverseType(T);
14381 }
14382
14383 namespace {
14384   /// \brief Helper class that marks all of the declarations referenced by
14385   /// potentially-evaluated subexpressions as "referenced".
14386   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14387     Sema &S;
14388     bool SkipLocalVariables;
14389     
14390   public:
14391     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14392     
14393     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
14394       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14395     
14396     void VisitDeclRefExpr(DeclRefExpr *E) {
14397       // If we were asked not to visit local variables, don't.
14398       if (SkipLocalVariables) {
14399         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14400           if (VD->hasLocalStorage())
14401             return;
14402       }
14403       
14404       S.MarkDeclRefReferenced(E);
14405     }
14406
14407     void VisitMemberExpr(MemberExpr *E) {
14408       S.MarkMemberReferenced(E);
14409       Inherited::VisitMemberExpr(E);
14410     }
14411     
14412     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14413       S.MarkFunctionReferenced(E->getLocStart(),
14414             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14415       Visit(E->getSubExpr());
14416     }
14417     
14418     void VisitCXXNewExpr(CXXNewExpr *E) {
14419       if (E->getOperatorNew())
14420         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14421       if (E->getOperatorDelete())
14422         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14423       Inherited::VisitCXXNewExpr(E);
14424     }
14425
14426     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14427       if (E->getOperatorDelete())
14428         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14429       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14430       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14431         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14432         S.MarkFunctionReferenced(E->getLocStart(), 
14433                                     S.LookupDestructor(Record));
14434       }
14435       
14436       Inherited::VisitCXXDeleteExpr(E);
14437     }
14438     
14439     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14440       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14441       Inherited::VisitCXXConstructExpr(E);
14442     }
14443     
14444     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14445       Visit(E->getExpr());
14446     }
14447
14448     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14449       Inherited::VisitImplicitCastExpr(E);
14450
14451       if (E->getCastKind() == CK_LValueToRValue)
14452         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14453     }
14454   };
14455 }
14456
14457 /// \brief Mark any declarations that appear within this expression or any
14458 /// potentially-evaluated subexpressions as "referenced".
14459 ///
14460 /// \param SkipLocalVariables If true, don't mark local variables as 
14461 /// 'referenced'.
14462 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
14463                                             bool SkipLocalVariables) {
14464   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14465 }
14466
14467 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14468 /// of the program being compiled.
14469 ///
14470 /// This routine emits the given diagnostic when the code currently being
14471 /// type-checked is "potentially evaluated", meaning that there is a
14472 /// possibility that the code will actually be executable. Code in sizeof()
14473 /// expressions, code used only during overload resolution, etc., are not
14474 /// potentially evaluated. This routine will suppress such diagnostics or,
14475 /// in the absolutely nutty case of potentially potentially evaluated
14476 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14477 /// later.
14478 ///
14479 /// This routine should be used for all diagnostics that describe the run-time
14480 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14481 /// Failure to do so will likely result in spurious diagnostics or failures
14482 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14483 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14484                                const PartialDiagnostic &PD) {
14485   switch (ExprEvalContexts.back().Context) {
14486   case Unevaluated:
14487   case UnevaluatedList:
14488   case UnevaluatedAbstract:
14489   case DiscardedStatement:
14490     // The argument will never be evaluated, so don't complain.
14491     break;
14492
14493   case ConstantEvaluated:
14494     // Relevant diagnostics should be produced by constant evaluation.
14495     break;
14496
14497   case PotentiallyEvaluated:
14498   case PotentiallyEvaluatedIfUsed:
14499     if (Statement && getCurFunctionOrMethodDecl()) {
14500       FunctionScopes.back()->PossiblyUnreachableDiags.
14501         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14502     }
14503     else
14504       Diag(Loc, PD);
14505       
14506     return true;
14507   }
14508
14509   return false;
14510 }
14511
14512 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14513                                CallExpr *CE, FunctionDecl *FD) {
14514   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14515     return false;
14516
14517   // If we're inside a decltype's expression, don't check for a valid return
14518   // type or construct temporaries until we know whether this is the last call.
14519   if (ExprEvalContexts.back().IsDecltype) {
14520     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14521     return false;
14522   }
14523
14524   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14525     FunctionDecl *FD;
14526     CallExpr *CE;
14527     
14528   public:
14529     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14530       : FD(FD), CE(CE) { }
14531
14532     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14533       if (!FD) {
14534         S.Diag(Loc, diag::err_call_incomplete_return)
14535           << T << CE->getSourceRange();
14536         return;
14537       }
14538       
14539       S.Diag(Loc, diag::err_call_function_incomplete_return)
14540         << CE->getSourceRange() << FD->getDeclName() << T;
14541       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14542           << FD->getDeclName();
14543     }
14544   } Diagnoser(FD, CE);
14545   
14546   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14547     return true;
14548
14549   return false;
14550 }
14551
14552 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14553 // will prevent this condition from triggering, which is what we want.
14554 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14555   SourceLocation Loc;
14556
14557   unsigned diagnostic = diag::warn_condition_is_assignment;
14558   bool IsOrAssign = false;
14559
14560   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14561     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14562       return;
14563
14564     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14565
14566     // Greylist some idioms by putting them into a warning subcategory.
14567     if (ObjCMessageExpr *ME
14568           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14569       Selector Sel = ME->getSelector();
14570
14571       // self = [<foo> init...]
14572       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14573         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14574
14575       // <foo> = [<bar> nextObject]
14576       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14577         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14578     }
14579
14580     Loc = Op->getOperatorLoc();
14581   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14582     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14583       return;
14584
14585     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14586     Loc = Op->getOperatorLoc();
14587   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14588     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14589   else {
14590     // Not an assignment.
14591     return;
14592   }
14593
14594   Diag(Loc, diagnostic) << E->getSourceRange();
14595
14596   SourceLocation Open = E->getLocStart();
14597   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14598   Diag(Loc, diag::note_condition_assign_silence)
14599         << FixItHint::CreateInsertion(Open, "(")
14600         << FixItHint::CreateInsertion(Close, ")");
14601
14602   if (IsOrAssign)
14603     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14604       << FixItHint::CreateReplacement(Loc, "!=");
14605   else
14606     Diag(Loc, diag::note_condition_assign_to_comparison)
14607       << FixItHint::CreateReplacement(Loc, "==");
14608 }
14609
14610 /// \brief Redundant parentheses over an equality comparison can indicate
14611 /// that the user intended an assignment used as condition.
14612 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14613   // Don't warn if the parens came from a macro.
14614   SourceLocation parenLoc = ParenE->getLocStart();
14615   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14616     return;
14617   // Don't warn for dependent expressions.
14618   if (ParenE->isTypeDependent())
14619     return;
14620
14621   Expr *E = ParenE->IgnoreParens();
14622
14623   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14624     if (opE->getOpcode() == BO_EQ &&
14625         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14626                                                            == Expr::MLV_Valid) {
14627       SourceLocation Loc = opE->getOperatorLoc();
14628       
14629       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14630       SourceRange ParenERange = ParenE->getSourceRange();
14631       Diag(Loc, diag::note_equality_comparison_silence)
14632         << FixItHint::CreateRemoval(ParenERange.getBegin())
14633         << FixItHint::CreateRemoval(ParenERange.getEnd());
14634       Diag(Loc, diag::note_equality_comparison_to_assign)
14635         << FixItHint::CreateReplacement(Loc, "=");
14636     }
14637 }
14638
14639 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14640                                        bool IsConstexpr) {
14641   DiagnoseAssignmentAsCondition(E);
14642   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14643     DiagnoseEqualityWithExtraParens(parenE);
14644
14645   ExprResult result = CheckPlaceholderExpr(E);
14646   if (result.isInvalid()) return ExprError();
14647   E = result.get();
14648
14649   if (!E->isTypeDependent()) {
14650     if (getLangOpts().CPlusPlus)
14651       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14652
14653     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14654     if (ERes.isInvalid())
14655       return ExprError();
14656     E = ERes.get();
14657
14658     QualType T = E->getType();
14659     if (!T->isScalarType()) { // C99 6.8.4.1p1
14660       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14661         << T << E->getSourceRange();
14662       return ExprError();
14663     }
14664     CheckBoolLikeConversion(E, Loc);
14665   }
14666
14667   return E;
14668 }
14669
14670 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14671                                            Expr *SubExpr, ConditionKind CK) {
14672   // Empty conditions are valid in for-statements.
14673   if (!SubExpr)
14674     return ConditionResult();
14675
14676   ExprResult Cond;
14677   switch (CK) {
14678   case ConditionKind::Boolean:
14679     Cond = CheckBooleanCondition(Loc, SubExpr);
14680     break;
14681
14682   case ConditionKind::ConstexprIf:
14683     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14684     break;
14685
14686   case ConditionKind::Switch:
14687     Cond = CheckSwitchCondition(Loc, SubExpr);
14688     break;
14689   }
14690   if (Cond.isInvalid())
14691     return ConditionError();
14692
14693   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14694   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14695   if (!FullExpr.get())
14696     return ConditionError();
14697
14698   return ConditionResult(*this, nullptr, FullExpr,
14699                          CK == ConditionKind::ConstexprIf);
14700 }
14701
14702 namespace {
14703   /// A visitor for rebuilding a call to an __unknown_any expression
14704   /// to have an appropriate type.
14705   struct RebuildUnknownAnyFunction
14706     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14707
14708     Sema &S;
14709
14710     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14711
14712     ExprResult VisitStmt(Stmt *S) {
14713       llvm_unreachable("unexpected statement!");
14714     }
14715
14716     ExprResult VisitExpr(Expr *E) {
14717       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14718         << E->getSourceRange();
14719       return ExprError();
14720     }
14721
14722     /// Rebuild an expression which simply semantically wraps another
14723     /// expression which it shares the type and value kind of.
14724     template <class T> ExprResult rebuildSugarExpr(T *E) {
14725       ExprResult SubResult = Visit(E->getSubExpr());
14726       if (SubResult.isInvalid()) return ExprError();
14727
14728       Expr *SubExpr = SubResult.get();
14729       E->setSubExpr(SubExpr);
14730       E->setType(SubExpr->getType());
14731       E->setValueKind(SubExpr->getValueKind());
14732       assert(E->getObjectKind() == OK_Ordinary);
14733       return E;
14734     }
14735
14736     ExprResult VisitParenExpr(ParenExpr *E) {
14737       return rebuildSugarExpr(E);
14738     }
14739
14740     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14741       return rebuildSugarExpr(E);
14742     }
14743
14744     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14745       ExprResult SubResult = Visit(E->getSubExpr());
14746       if (SubResult.isInvalid()) return ExprError();
14747
14748       Expr *SubExpr = SubResult.get();
14749       E->setSubExpr(SubExpr);
14750       E->setType(S.Context.getPointerType(SubExpr->getType()));
14751       assert(E->getValueKind() == VK_RValue);
14752       assert(E->getObjectKind() == OK_Ordinary);
14753       return E;
14754     }
14755
14756     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14757       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14758
14759       E->setType(VD->getType());
14760
14761       assert(E->getValueKind() == VK_RValue);
14762       if (S.getLangOpts().CPlusPlus &&
14763           !(isa<CXXMethodDecl>(VD) &&
14764             cast<CXXMethodDecl>(VD)->isInstance()))
14765         E->setValueKind(VK_LValue);
14766
14767       return E;
14768     }
14769
14770     ExprResult VisitMemberExpr(MemberExpr *E) {
14771       return resolveDecl(E, E->getMemberDecl());
14772     }
14773
14774     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14775       return resolveDecl(E, E->getDecl());
14776     }
14777   };
14778 }
14779
14780 /// Given a function expression of unknown-any type, try to rebuild it
14781 /// to have a function type.
14782 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14783   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14784   if (Result.isInvalid()) return ExprError();
14785   return S.DefaultFunctionArrayConversion(Result.get());
14786 }
14787
14788 namespace {
14789   /// A visitor for rebuilding an expression of type __unknown_anytype
14790   /// into one which resolves the type directly on the referring
14791   /// expression.  Strict preservation of the original source
14792   /// structure is not a goal.
14793   struct RebuildUnknownAnyExpr
14794     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14795
14796     Sema &S;
14797
14798     /// The current destination type.
14799     QualType DestType;
14800
14801     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14802       : S(S), DestType(CastType) {}
14803
14804     ExprResult VisitStmt(Stmt *S) {
14805       llvm_unreachable("unexpected statement!");
14806     }
14807
14808     ExprResult VisitExpr(Expr *E) {
14809       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14810         << E->getSourceRange();
14811       return ExprError();
14812     }
14813
14814     ExprResult VisitCallExpr(CallExpr *E);
14815     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14816
14817     /// Rebuild an expression which simply semantically wraps another
14818     /// expression which it shares the type and value kind of.
14819     template <class T> ExprResult rebuildSugarExpr(T *E) {
14820       ExprResult SubResult = Visit(E->getSubExpr());
14821       if (SubResult.isInvalid()) return ExprError();
14822       Expr *SubExpr = SubResult.get();
14823       E->setSubExpr(SubExpr);
14824       E->setType(SubExpr->getType());
14825       E->setValueKind(SubExpr->getValueKind());
14826       assert(E->getObjectKind() == OK_Ordinary);
14827       return E;
14828     }
14829
14830     ExprResult VisitParenExpr(ParenExpr *E) {
14831       return rebuildSugarExpr(E);
14832     }
14833
14834     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14835       return rebuildSugarExpr(E);
14836     }
14837
14838     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14839       const PointerType *Ptr = DestType->getAs<PointerType>();
14840       if (!Ptr) {
14841         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14842           << E->getSourceRange();
14843         return ExprError();
14844       }
14845
14846       if (isa<CallExpr>(E->getSubExpr())) {
14847         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14848           << E->getSourceRange();
14849         return ExprError();
14850       }
14851
14852       assert(E->getValueKind() == VK_RValue);
14853       assert(E->getObjectKind() == OK_Ordinary);
14854       E->setType(DestType);
14855
14856       // Build the sub-expression as if it were an object of the pointee type.
14857       DestType = Ptr->getPointeeType();
14858       ExprResult SubResult = Visit(E->getSubExpr());
14859       if (SubResult.isInvalid()) return ExprError();
14860       E->setSubExpr(SubResult.get());
14861       return E;
14862     }
14863
14864     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14865
14866     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14867
14868     ExprResult VisitMemberExpr(MemberExpr *E) {
14869       return resolveDecl(E, E->getMemberDecl());
14870     }
14871
14872     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14873       return resolveDecl(E, E->getDecl());
14874     }
14875   };
14876 }
14877
14878 /// Rebuilds a call expression which yielded __unknown_anytype.
14879 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14880   Expr *CalleeExpr = E->getCallee();
14881
14882   enum FnKind {
14883     FK_MemberFunction,
14884     FK_FunctionPointer,
14885     FK_BlockPointer
14886   };
14887
14888   FnKind Kind;
14889   QualType CalleeType = CalleeExpr->getType();
14890   if (CalleeType == S.Context.BoundMemberTy) {
14891     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14892     Kind = FK_MemberFunction;
14893     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14894   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14895     CalleeType = Ptr->getPointeeType();
14896     Kind = FK_FunctionPointer;
14897   } else {
14898     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14899     Kind = FK_BlockPointer;
14900   }
14901   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14902
14903   // Verify that this is a legal result type of a function.
14904   if (DestType->isArrayType() || DestType->isFunctionType()) {
14905     unsigned diagID = diag::err_func_returning_array_function;
14906     if (Kind == FK_BlockPointer)
14907       diagID = diag::err_block_returning_array_function;
14908
14909     S.Diag(E->getExprLoc(), diagID)
14910       << DestType->isFunctionType() << DestType;
14911     return ExprError();
14912   }
14913
14914   // Otherwise, go ahead and set DestType as the call's result.
14915   E->setType(DestType.getNonLValueExprType(S.Context));
14916   E->setValueKind(Expr::getValueKindForType(DestType));
14917   assert(E->getObjectKind() == OK_Ordinary);
14918
14919   // Rebuild the function type, replacing the result type with DestType.
14920   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14921   if (Proto) {
14922     // __unknown_anytype(...) is a special case used by the debugger when
14923     // it has no idea what a function's signature is.
14924     //
14925     // We want to build this call essentially under the K&R
14926     // unprototyped rules, but making a FunctionNoProtoType in C++
14927     // would foul up all sorts of assumptions.  However, we cannot
14928     // simply pass all arguments as variadic arguments, nor can we
14929     // portably just call the function under a non-variadic type; see
14930     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14931     // However, it turns out that in practice it is generally safe to
14932     // call a function declared as "A foo(B,C,D);" under the prototype
14933     // "A foo(B,C,D,...);".  The only known exception is with the
14934     // Windows ABI, where any variadic function is implicitly cdecl
14935     // regardless of its normal CC.  Therefore we change the parameter
14936     // types to match the types of the arguments.
14937     //
14938     // This is a hack, but it is far superior to moving the
14939     // corresponding target-specific code from IR-gen to Sema/AST.
14940
14941     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14942     SmallVector<QualType, 8> ArgTypes;
14943     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14944       ArgTypes.reserve(E->getNumArgs());
14945       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14946         Expr *Arg = E->getArg(i);
14947         QualType ArgType = Arg->getType();
14948         if (E->isLValue()) {
14949           ArgType = S.Context.getLValueReferenceType(ArgType);
14950         } else if (E->isXValue()) {
14951           ArgType = S.Context.getRValueReferenceType(ArgType);
14952         }
14953         ArgTypes.push_back(ArgType);
14954       }
14955       ParamTypes = ArgTypes;
14956     }
14957     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14958                                          Proto->getExtProtoInfo());
14959   } else {
14960     DestType = S.Context.getFunctionNoProtoType(DestType,
14961                                                 FnType->getExtInfo());
14962   }
14963
14964   // Rebuild the appropriate pointer-to-function type.
14965   switch (Kind) { 
14966   case FK_MemberFunction:
14967     // Nothing to do.
14968     break;
14969
14970   case FK_FunctionPointer:
14971     DestType = S.Context.getPointerType(DestType);
14972     break;
14973
14974   case FK_BlockPointer:
14975     DestType = S.Context.getBlockPointerType(DestType);
14976     break;
14977   }
14978
14979   // Finally, we can recurse.
14980   ExprResult CalleeResult = Visit(CalleeExpr);
14981   if (!CalleeResult.isUsable()) return ExprError();
14982   E->setCallee(CalleeResult.get());
14983
14984   // Bind a temporary if necessary.
14985   return S.MaybeBindToTemporary(E);
14986 }
14987
14988 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14989   // Verify that this is a legal result type of a call.
14990   if (DestType->isArrayType() || DestType->isFunctionType()) {
14991     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14992       << DestType->isFunctionType() << DestType;
14993     return ExprError();
14994   }
14995
14996   // Rewrite the method result type if available.
14997   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14998     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14999     Method->setReturnType(DestType);
15000   }
15001
15002   // Change the type of the message.
15003   E->setType(DestType.getNonReferenceType());
15004   E->setValueKind(Expr::getValueKindForType(DestType));
15005
15006   return S.MaybeBindToTemporary(E);
15007 }
15008
15009 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15010   // The only case we should ever see here is a function-to-pointer decay.
15011   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15012     assert(E->getValueKind() == VK_RValue);
15013     assert(E->getObjectKind() == OK_Ordinary);
15014   
15015     E->setType(DestType);
15016   
15017     // Rebuild the sub-expression as the pointee (function) type.
15018     DestType = DestType->castAs<PointerType>()->getPointeeType();
15019   
15020     ExprResult Result = Visit(E->getSubExpr());
15021     if (!Result.isUsable()) return ExprError();
15022   
15023     E->setSubExpr(Result.get());
15024     return E;
15025   } else if (E->getCastKind() == CK_LValueToRValue) {
15026     assert(E->getValueKind() == VK_RValue);
15027     assert(E->getObjectKind() == OK_Ordinary);
15028
15029     assert(isa<BlockPointerType>(E->getType()));
15030
15031     E->setType(DestType);
15032
15033     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15034     DestType = S.Context.getLValueReferenceType(DestType);
15035
15036     ExprResult Result = Visit(E->getSubExpr());
15037     if (!Result.isUsable()) return ExprError();
15038
15039     E->setSubExpr(Result.get());
15040     return E;
15041   } else {
15042     llvm_unreachable("Unhandled cast type!");
15043   }
15044 }
15045
15046 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15047   ExprValueKind ValueKind = VK_LValue;
15048   QualType Type = DestType;
15049
15050   // We know how to make this work for certain kinds of decls:
15051
15052   //  - functions
15053   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15054     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15055       DestType = Ptr->getPointeeType();
15056       ExprResult Result = resolveDecl(E, VD);
15057       if (Result.isInvalid()) return ExprError();
15058       return S.ImpCastExprToType(Result.get(), Type,
15059                                  CK_FunctionToPointerDecay, VK_RValue);
15060     }
15061
15062     if (!Type->isFunctionType()) {
15063       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15064         << VD << E->getSourceRange();
15065       return ExprError();
15066     }
15067     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15068       // We must match the FunctionDecl's type to the hack introduced in
15069       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15070       // type. See the lengthy commentary in that routine.
15071       QualType FDT = FD->getType();
15072       const FunctionType *FnType = FDT->castAs<FunctionType>();
15073       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15074       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15075       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15076         SourceLocation Loc = FD->getLocation();
15077         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15078                                       FD->getDeclContext(),
15079                                       Loc, Loc, FD->getNameInfo().getName(),
15080                                       DestType, FD->getTypeSourceInfo(),
15081                                       SC_None, false/*isInlineSpecified*/,
15082                                       FD->hasPrototype(),
15083                                       false/*isConstexprSpecified*/);
15084           
15085         if (FD->getQualifier())
15086           NewFD->setQualifierInfo(FD->getQualifierLoc());
15087
15088         SmallVector<ParmVarDecl*, 16> Params;
15089         for (const auto &AI : FT->param_types()) {
15090           ParmVarDecl *Param =
15091             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15092           Param->setScopeInfo(0, Params.size());
15093           Params.push_back(Param);
15094         }
15095         NewFD->setParams(Params);
15096         DRE->setDecl(NewFD);
15097         VD = DRE->getDecl();
15098       }
15099     }
15100
15101     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15102       if (MD->isInstance()) {
15103         ValueKind = VK_RValue;
15104         Type = S.Context.BoundMemberTy;
15105       }
15106
15107     // Function references aren't l-values in C.
15108     if (!S.getLangOpts().CPlusPlus)
15109       ValueKind = VK_RValue;
15110
15111   //  - variables
15112   } else if (isa<VarDecl>(VD)) {
15113     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15114       Type = RefTy->getPointeeType();
15115     } else if (Type->isFunctionType()) {
15116       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15117         << VD << E->getSourceRange();
15118       return ExprError();
15119     }
15120
15121   //  - nothing else
15122   } else {
15123     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15124       << VD << E->getSourceRange();
15125     return ExprError();
15126   }
15127
15128   // Modifying the declaration like this is friendly to IR-gen but
15129   // also really dangerous.
15130   VD->setType(DestType);
15131   E->setType(Type);
15132   E->setValueKind(ValueKind);
15133   return E;
15134 }
15135
15136 /// Check a cast of an unknown-any type.  We intentionally only
15137 /// trigger this for C-style casts.
15138 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15139                                      Expr *CastExpr, CastKind &CastKind,
15140                                      ExprValueKind &VK, CXXCastPath &Path) {
15141   // The type we're casting to must be either void or complete.
15142   if (!CastType->isVoidType() &&
15143       RequireCompleteType(TypeRange.getBegin(), CastType,
15144                           diag::err_typecheck_cast_to_incomplete))
15145     return ExprError();
15146
15147   // Rewrite the casted expression from scratch.
15148   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15149   if (!result.isUsable()) return ExprError();
15150
15151   CastExpr = result.get();
15152   VK = CastExpr->getValueKind();
15153   CastKind = CK_NoOp;
15154
15155   return CastExpr;
15156 }
15157
15158 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15159   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15160 }
15161
15162 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15163                                     Expr *arg, QualType &paramType) {
15164   // If the syntactic form of the argument is not an explicit cast of
15165   // any sort, just do default argument promotion.
15166   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15167   if (!castArg) {
15168     ExprResult result = DefaultArgumentPromotion(arg);
15169     if (result.isInvalid()) return ExprError();
15170     paramType = result.get()->getType();
15171     return result;
15172   }
15173
15174   // Otherwise, use the type that was written in the explicit cast.
15175   assert(!arg->hasPlaceholderType());
15176   paramType = castArg->getTypeAsWritten();
15177
15178   // Copy-initialize a parameter of that type.
15179   InitializedEntity entity =
15180     InitializedEntity::InitializeParameter(Context, paramType,
15181                                            /*consumed*/ false);
15182   return PerformCopyInitialization(entity, callLoc, arg);
15183 }
15184
15185 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15186   Expr *orig = E;
15187   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15188   while (true) {
15189     E = E->IgnoreParenImpCasts();
15190     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15191       E = call->getCallee();
15192       diagID = diag::err_uncasted_call_of_unknown_any;
15193     } else {
15194       break;
15195     }
15196   }
15197
15198   SourceLocation loc;
15199   NamedDecl *d;
15200   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15201     loc = ref->getLocation();
15202     d = ref->getDecl();
15203   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15204     loc = mem->getMemberLoc();
15205     d = mem->getMemberDecl();
15206   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15207     diagID = diag::err_uncasted_call_of_unknown_any;
15208     loc = msg->getSelectorStartLoc();
15209     d = msg->getMethodDecl();
15210     if (!d) {
15211       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15212         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15213         << orig->getSourceRange();
15214       return ExprError();
15215     }
15216   } else {
15217     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15218       << E->getSourceRange();
15219     return ExprError();
15220   }
15221
15222   S.Diag(loc, diagID) << d << orig->getSourceRange();
15223
15224   // Never recoverable.
15225   return ExprError();
15226 }
15227
15228 /// Check for operands with placeholder types and complain if found.
15229 /// Returns true if there was an error and no recovery was possible.
15230 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15231   if (!getLangOpts().CPlusPlus) {
15232     // C cannot handle TypoExpr nodes on either side of a binop because it
15233     // doesn't handle dependent types properly, so make sure any TypoExprs have
15234     // been dealt with before checking the operands.
15235     ExprResult Result = CorrectDelayedTyposInExpr(E);
15236     if (!Result.isUsable()) return ExprError();
15237     E = Result.get();
15238   }
15239
15240   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15241   if (!placeholderType) return E;
15242
15243   switch (placeholderType->getKind()) {
15244
15245   // Overloaded expressions.
15246   case BuiltinType::Overload: {
15247     // Try to resolve a single function template specialization.
15248     // This is obligatory.
15249     ExprResult Result = E;
15250     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15251       return Result;
15252
15253     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15254     // leaves Result unchanged on failure.
15255     Result = E;
15256     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15257       return Result;
15258
15259     // If that failed, try to recover with a call.
15260     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15261                          /*complain*/ true);
15262     return Result;
15263   }
15264
15265   // Bound member functions.
15266   case BuiltinType::BoundMember: {
15267     ExprResult result = E;
15268     const Expr *BME = E->IgnoreParens();
15269     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15270     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15271     if (isa<CXXPseudoDestructorExpr>(BME)) {
15272       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15273     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15274       if (ME->getMemberNameInfo().getName().getNameKind() ==
15275           DeclarationName::CXXDestructorName)
15276         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15277     }
15278     tryToRecoverWithCall(result, PD,
15279                          /*complain*/ true);
15280     return result;
15281   }
15282
15283   // ARC unbridged casts.
15284   case BuiltinType::ARCUnbridgedCast: {
15285     Expr *realCast = stripARCUnbridgedCast(E);
15286     diagnoseARCUnbridgedCast(realCast);
15287     return realCast;
15288   }
15289
15290   // Expressions of unknown type.
15291   case BuiltinType::UnknownAny:
15292     return diagnoseUnknownAnyExpr(*this, E);
15293
15294   // Pseudo-objects.
15295   case BuiltinType::PseudoObject:
15296     return checkPseudoObjectRValue(E);
15297
15298   case BuiltinType::BuiltinFn: {
15299     // Accept __noop without parens by implicitly converting it to a call expr.
15300     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15301     if (DRE) {
15302       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15303       if (FD->getBuiltinID() == Builtin::BI__noop) {
15304         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15305                               CK_BuiltinFnToFnPtr).get();
15306         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15307                                       VK_RValue, SourceLocation());
15308       }
15309     }
15310
15311     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15312     return ExprError();
15313   }
15314
15315   // Expressions of unknown type.
15316   case BuiltinType::OMPArraySection:
15317     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15318     return ExprError();
15319
15320   // Everything else should be impossible.
15321 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15322   case BuiltinType::Id:
15323 #include "clang/Basic/OpenCLImageTypes.def"
15324 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15325 #define PLACEHOLDER_TYPE(Id, SingletonId)
15326 #include "clang/AST/BuiltinTypes.def"
15327     break;
15328   }
15329
15330   llvm_unreachable("invalid placeholder type!");
15331 }
15332
15333 bool Sema::CheckCaseExpression(Expr *E) {
15334   if (E->isTypeDependent())
15335     return true;
15336   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15337     return E->getType()->isIntegralOrEnumerationType();
15338   return false;
15339 }
15340
15341 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15342 ExprResult
15343 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15344   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15345          "Unknown Objective-C Boolean value!");
15346   QualType BoolT = Context.ObjCBuiltinBoolTy;
15347   if (!Context.getBOOLDecl()) {
15348     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15349                         Sema::LookupOrdinaryName);
15350     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15351       NamedDecl *ND = Result.getFoundDecl();
15352       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
15353         Context.setBOOLDecl(TD);
15354     }
15355   }
15356   if (Context.getBOOLDecl())
15357     BoolT = Context.getBOOLType();
15358   return new (Context)
15359       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15360 }
15361
15362 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15363     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15364     SourceLocation RParen) {
15365
15366   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15367
15368   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15369                            [&](const AvailabilitySpec &Spec) {
15370                              return Spec.getPlatform() == Platform;
15371                            });
15372
15373   VersionTuple Version;
15374   if (Spec != AvailSpecs.end())
15375     Version = Spec->getVersion();
15376
15377   return new (Context)
15378       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15379 }