]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304659, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaExpr.cpp
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73
74   return true;
75 }
76
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message);
109
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message);
117         continue;
118       }
119     }
120     break;
121   }
122
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message);
128     }
129   }
130
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message);
136     }
137
138   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161
162   return Result;
163 }
164
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173
174     if (Result == AR_NotYetIntroduced) {
175       if (S.getCurFunctionOrMethodDecl()) {
176         S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
177         return;
178       } else if (S.getCurBlock() || S.getCurLambda()) {
179         S.getCurFunction()->HasPotentialAvailabilityViolations = true;
180         return;
181       }
182     }
183
184     const ObjCPropertyDecl *ObjCPDecl = nullptr;
185     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
186       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
187         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
188         if (PDeclResult == Result)
189           ObjCPDecl = PD;
190       }
191     }
192
193     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
194                               ObjCPDecl, ObjCPropertyAccess);
195   }
196 }
197
198 /// \brief Emit a note explaining that this function is deleted.
199 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
200   assert(Decl->isDeleted());
201
202   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
203
204   if (Method && Method->isDeleted() && Method->isDefaulted()) {
205     // If the method was explicitly defaulted, point at that declaration.
206     if (!Method->isImplicit())
207       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
208
209     // Try to diagnose why this special member function was implicitly
210     // deleted. This might fail, if that reason no longer applies.
211     CXXSpecialMember CSM = getSpecialMember(Method);
212     if (CSM != CXXInvalid)
213       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
214
215     return;
216   }
217
218   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
219   if (Ctor && Ctor->isInheritingConstructor())
220     return NoteDeletedInheritingConstructor(Ctor);
221
222   Diag(Decl->getLocation(), diag::note_availability_specified_here)
223     << Decl << true;
224 }
225
226 /// \brief Determine whether a FunctionDecl was ever declared with an
227 /// explicit storage class.
228 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
229   for (auto I : D->redecls()) {
230     if (I->getStorageClass() != SC_None)
231       return true;
232   }
233   return false;
234 }
235
236 /// \brief Check whether we're in an extern inline function and referring to a
237 /// variable or function with internal linkage (C11 6.7.4p3).
238 ///
239 /// This is only a warning because we used to silently accept this code, but
240 /// in many cases it will not behave correctly. This is not enabled in C++ mode
241 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
242 /// and so while there may still be user mistakes, most of the time we can't
243 /// prove that there are errors.
244 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
245                                                       const NamedDecl *D,
246                                                       SourceLocation Loc) {
247   // This is disabled under C++; there are too many ways for this to fire in
248   // contexts where the warning is a false positive, or where it is technically
249   // correct but benign.
250   if (S.getLangOpts().CPlusPlus)
251     return;
252
253   // Check if this is an inlined function or method.
254   FunctionDecl *Current = S.getCurFunctionDecl();
255   if (!Current)
256     return;
257   if (!Current->isInlined())
258     return;
259   if (!Current->isExternallyVisible())
260     return;
261
262   // Check if the decl has internal linkage.
263   if (D->getFormalLinkage() != InternalLinkage)
264     return;
265
266   // Downgrade from ExtWarn to Extension if
267   //  (1) the supposedly external inline function is in the main file,
268   //      and probably won't be included anywhere else.
269   //  (2) the thing we're referencing is a pure function.
270   //  (3) the thing we're referencing is another inline function.
271   // This last can give us false negatives, but it's better than warning on
272   // wrappers for simple C library functions.
273   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
274   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
275   if (!DowngradeWarning && UsedFn)
276     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
277
278   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
279                                : diag::ext_internal_in_extern_inline)
280     << /*IsVar=*/!UsedFn << D;
281
282   S.MaybeSuggestAddingStaticToDecl(Current);
283
284   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
285       << D;
286 }
287
288 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
289   const FunctionDecl *First = Cur->getFirstDecl();
290
291   // Suggest "static" on the function, if possible.
292   if (!hasAnyExplicitStorageClass(First)) {
293     SourceLocation DeclBegin = First->getSourceRange().getBegin();
294     Diag(DeclBegin, diag::note_convert_inline_to_static)
295       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
296   }
297 }
298
299 /// \brief Determine whether the use of this declaration is valid, and
300 /// emit any corresponding diagnostics.
301 ///
302 /// This routine diagnoses various problems with referencing
303 /// declarations that can occur when using a declaration. For example,
304 /// it might warn if a deprecated or unavailable declaration is being
305 /// used, or produce an error (and return true) if a C++0x deleted
306 /// function is being used.
307 ///
308 /// \returns true if there was an error (this declaration cannot be
309 /// referenced), false otherwise.
310 ///
311 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
312                              const ObjCInterfaceDecl *UnknownObjCClass,
313                              bool ObjCPropertyAccess) {
314   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
315     // If there were any diagnostics suppressed by template argument deduction,
316     // emit them now.
317     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
318     if (Pos != SuppressedDiagnostics.end()) {
319       for (const PartialDiagnosticAt &Suppressed : Pos->second)
320         Diag(Suppressed.first, Suppressed.second);
321
322       // Clear out the list of suppressed diagnostics, so that we don't emit
323       // them again for this specialization. However, we don't obsolete this
324       // entry from the table, because we want to avoid ever emitting these
325       // diagnostics again.
326       Pos->second.clear();
327     }
328
329     // C++ [basic.start.main]p3:
330     //   The function 'main' shall not be used within a program.
331     if (cast<FunctionDecl>(D)->isMain())
332       Diag(Loc, diag::ext_main_used);
333   }
334
335   // See if this is an auto-typed variable whose initializer we are parsing.
336   if (ParsingInitForAutoVars.count(D)) {
337     if (isa<BindingDecl>(D)) {
338       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
339         << D->getDeclName();
340     } else {
341       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
342         << D->getDeclName() << cast<VarDecl>(D)->getType();
343     }
344     return true;
345   }
346
347   // See if this is a deleted function.
348   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
349     if (FD->isDeleted()) {
350       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
351       if (Ctor && Ctor->isInheritingConstructor())
352         Diag(Loc, diag::err_deleted_inherited_ctor_use)
353             << Ctor->getParent()
354             << Ctor->getInheritedConstructor().getConstructor()->getParent();
355       else 
356         Diag(Loc, diag::err_deleted_function_use);
357       NoteDeletedFunction(FD);
358       return true;
359     }
360
361     // If the function has a deduced return type, and we can't deduce it,
362     // then we can't use it either.
363     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
364         DeduceReturnType(FD, Loc))
365       return true;
366
367     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
368       return true;
369   }
370
371   auto getReferencedObjCProp = [](const NamedDecl *D) ->
372                                       const ObjCPropertyDecl * {
373     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
374       return MD->findPropertyDecl();
375     return nullptr;
376   };
377   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
378     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
379       return true;
380   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
381       return true;
382   }
383
384   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
385   // Only the variables omp_in and omp_out are allowed in the combiner.
386   // Only the variables omp_priv and omp_orig are allowed in the
387   // initializer-clause.
388   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
389   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
390       isa<VarDecl>(D)) {
391     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
392         << getCurFunction()->HasOMPDeclareReductionCombiner;
393     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
394     return true;
395   }
396
397   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
398                              ObjCPropertyAccess);
399
400   DiagnoseUnusedOfDecl(*this, D, Loc);
401
402   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
403
404   return false;
405 }
406
407 /// \brief Retrieve the message suffix that should be added to a
408 /// diagnostic complaining about the given function being deleted or
409 /// unavailable.
410 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
411   std::string Message;
412   if (FD->getAvailability(&Message))
413     return ": " + Message;
414
415   return std::string();
416 }
417
418 /// DiagnoseSentinelCalls - This routine checks whether a call or
419 /// message-send is to a declaration with the sentinel attribute, and
420 /// if so, it checks that the requirements of the sentinel are
421 /// satisfied.
422 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
423                                  ArrayRef<Expr *> Args) {
424   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
425   if (!attr)
426     return;
427
428   // The number of formal parameters of the declaration.
429   unsigned numFormalParams;
430
431   // The kind of declaration.  This is also an index into a %select in
432   // the diagnostic.
433   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
434
435   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
436     numFormalParams = MD->param_size();
437     calleeType = CT_Method;
438   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
439     numFormalParams = FD->param_size();
440     calleeType = CT_Function;
441   } else if (isa<VarDecl>(D)) {
442     QualType type = cast<ValueDecl>(D)->getType();
443     const FunctionType *fn = nullptr;
444     if (const PointerType *ptr = type->getAs<PointerType>()) {
445       fn = ptr->getPointeeType()->getAs<FunctionType>();
446       if (!fn) return;
447       calleeType = CT_Function;
448     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
449       fn = ptr->getPointeeType()->castAs<FunctionType>();
450       calleeType = CT_Block;
451     } else {
452       return;
453     }
454
455     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
456       numFormalParams = proto->getNumParams();
457     } else {
458       numFormalParams = 0;
459     }
460   } else {
461     return;
462   }
463
464   // "nullPos" is the number of formal parameters at the end which
465   // effectively count as part of the variadic arguments.  This is
466   // useful if you would prefer to not have *any* formal parameters,
467   // but the language forces you to have at least one.
468   unsigned nullPos = attr->getNullPos();
469   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
470   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
471
472   // The number of arguments which should follow the sentinel.
473   unsigned numArgsAfterSentinel = attr->getSentinel();
474
475   // If there aren't enough arguments for all the formal parameters,
476   // the sentinel, and the args after the sentinel, complain.
477   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
478     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
479     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
480     return;
481   }
482
483   // Otherwise, find the sentinel expression.
484   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
485   if (!sentinelExpr) return;
486   if (sentinelExpr->isValueDependent()) return;
487   if (Context.isSentinelNullExpr(sentinelExpr)) return;
488
489   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
490   // or 'NULL' if those are actually defined in the context.  Only use
491   // 'nil' for ObjC methods, where it's much more likely that the
492   // variadic arguments form a list of object pointers.
493   SourceLocation MissingNilLoc
494     = getLocForEndOfToken(sentinelExpr->getLocEnd());
495   std::string NullValue;
496   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
497     NullValue = "nil";
498   else if (getLangOpts().CPlusPlus11)
499     NullValue = "nullptr";
500   else if (PP.isMacroDefined("NULL"))
501     NullValue = "NULL";
502   else
503     NullValue = "(void*) 0";
504
505   if (MissingNilLoc.isInvalid())
506     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
507   else
508     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
509       << int(calleeType)
510       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
511   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
512 }
513
514 SourceRange Sema::getExprRange(Expr *E) const {
515   return E ? E->getSourceRange() : SourceRange();
516 }
517
518 //===----------------------------------------------------------------------===//
519 //  Standard Promotions and Conversions
520 //===----------------------------------------------------------------------===//
521
522 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
523 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
524   // Handle any placeholder expressions which made it here.
525   if (E->getType()->isPlaceholderType()) {
526     ExprResult result = CheckPlaceholderExpr(E);
527     if (result.isInvalid()) return ExprError();
528     E = result.get();
529   }
530   
531   QualType Ty = E->getType();
532   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
533
534   if (Ty->isFunctionType()) {
535     // If we are here, we are not calling a function but taking
536     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
537     if (getLangOpts().OpenCL) {
538       if (Diagnose)
539         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
540       return ExprError();
541     }
542
543     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
544       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
545         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
546           return ExprError();
547
548     E = ImpCastExprToType(E, Context.getPointerType(Ty),
549                           CK_FunctionToPointerDecay).get();
550   } else if (Ty->isArrayType()) {
551     // In C90 mode, arrays only promote to pointers if the array expression is
552     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
553     // type 'array of type' is converted to an expression that has type 'pointer
554     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
555     // that has type 'array of type' ...".  The relevant change is "an lvalue"
556     // (C90) to "an expression" (C99).
557     //
558     // C++ 4.2p1:
559     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
560     // T" can be converted to an rvalue of type "pointer to T".
561     //
562     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
563       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
564                             CK_ArrayToPointerDecay).get();
565   }
566   return E;
567 }
568
569 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
570   // Check to see if we are dereferencing a null pointer.  If so,
571   // and if not volatile-qualified, this is undefined behavior that the
572   // optimizer will delete, so warn about it.  People sometimes try to use this
573   // to get a deterministic trap and are surprised by clang's behavior.  This
574   // only handles the pattern "*null", which is a very syntactic check.
575   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
576     if (UO->getOpcode() == UO_Deref &&
577         UO->getSubExpr()->IgnoreParenCasts()->
578           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
579         !UO->getType().isVolatileQualified()) {
580     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
581                           S.PDiag(diag::warn_indirection_through_null)
582                             << UO->getSubExpr()->getSourceRange());
583     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
584                         S.PDiag(diag::note_indirection_through_null));
585   }
586 }
587
588 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589                                     SourceLocation AssignLoc,
590                                     const Expr* RHS) {
591   const ObjCIvarDecl *IV = OIRE->getDecl();
592   if (!IV)
593     return;
594   
595   DeclarationName MemberName = IV->getDeclName();
596   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
597   if (!Member || !Member->isStr("isa"))
598     return;
599   
600   const Expr *Base = OIRE->getBase();
601   QualType BaseType = Base->getType();
602   if (OIRE->isArrow())
603     BaseType = BaseType->getPointeeType();
604   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606       ObjCInterfaceDecl *ClassDeclared = nullptr;
607       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
608       if (!ClassDeclared->getSuperClass()
609           && (*ClassDeclared->ivar_begin()) == IV) {
610         if (RHS) {
611           NamedDecl *ObjectSetClass =
612             S.LookupSingleName(S.TUScope,
613                                &S.Context.Idents.get("object_setClass"),
614                                SourceLocation(), S.LookupOrdinaryName);
615           if (ObjectSetClass) {
616             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
617             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
618             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
619             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
620                                                      AssignLoc), ",") <<
621             FixItHint::CreateInsertion(RHSLocEnd, ")");
622           }
623           else
624             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
625         } else {
626           NamedDecl *ObjectGetClass =
627             S.LookupSingleName(S.TUScope,
628                                &S.Context.Idents.get("object_getClass"),
629                                SourceLocation(), S.LookupOrdinaryName);
630           if (ObjectGetClass)
631             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
632             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
633             FixItHint::CreateReplacement(
634                                          SourceRange(OIRE->getOpLoc(),
635                                                      OIRE->getLocEnd()), ")");
636           else
637             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
638         }
639         S.Diag(IV->getLocation(), diag::note_ivar_decl);
640       }
641     }
642 }
643
644 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
645   // Handle any placeholder expressions which made it here.
646   if (E->getType()->isPlaceholderType()) {
647     ExprResult result = CheckPlaceholderExpr(E);
648     if (result.isInvalid()) return ExprError();
649     E = result.get();
650   }
651   
652   // C++ [conv.lval]p1:
653   //   A glvalue of a non-function, non-array type T can be
654   //   converted to a prvalue.
655   if (!E->isGLValue()) return E;
656
657   QualType T = E->getType();
658   assert(!T.isNull() && "r-value conversion on typeless expression?");
659
660   // We don't want to throw lvalue-to-rvalue casts on top of
661   // expressions of certain types in C++.
662   if (getLangOpts().CPlusPlus &&
663       (E->getType() == Context.OverloadTy ||
664        T->isDependentType() ||
665        T->isRecordType()))
666     return E;
667
668   // The C standard is actually really unclear on this point, and
669   // DR106 tells us what the result should be but not why.  It's
670   // generally best to say that void types just doesn't undergo
671   // lvalue-to-rvalue at all.  Note that expressions of unqualified
672   // 'void' type are never l-values, but qualified void can be.
673   if (T->isVoidType())
674     return E;
675
676   // OpenCL usually rejects direct accesses to values of 'half' type.
677   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
678       T->isHalfType()) {
679     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
680       << 0 << T;
681     return ExprError();
682   }
683
684   CheckForNullPointerDereference(*this, E);
685   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
686     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
687                                      &Context.Idents.get("object_getClass"),
688                                      SourceLocation(), LookupOrdinaryName);
689     if (ObjectGetClass)
690       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
691         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
692         FixItHint::CreateReplacement(
693                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
694     else
695       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
696   }
697   else if (const ObjCIvarRefExpr *OIRE =
698             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
699     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
700
701   // C++ [conv.lval]p1:
702   //   [...] If T is a non-class type, the type of the prvalue is the
703   //   cv-unqualified version of T. Otherwise, the type of the
704   //   rvalue is T.
705   //
706   // C99 6.3.2.1p2:
707   //   If the lvalue has qualified type, the value has the unqualified
708   //   version of the type of the lvalue; otherwise, the value has the
709   //   type of the lvalue.
710   if (T.hasQualifiers())
711     T = T.getUnqualifiedType();
712
713   // Under the MS ABI, lock down the inheritance model now.
714   if (T->isMemberPointerType() &&
715       Context.getTargetInfo().getCXXABI().isMicrosoft())
716     (void)isCompleteType(E->getExprLoc(), T);
717
718   UpdateMarkingForLValueToRValue(E);
719   
720   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
721   // balance that.
722   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
723     Cleanup.setExprNeedsCleanups(true);
724
725   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
726                                             nullptr, VK_RValue);
727
728   // C11 6.3.2.1p2:
729   //   ... if the lvalue has atomic type, the value has the non-atomic version 
730   //   of the type of the lvalue ...
731   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
732     T = Atomic->getValueType().getUnqualifiedType();
733     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
734                                    nullptr, VK_RValue);
735   }
736   
737   return Res;
738 }
739
740 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
741   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
742   if (Res.isInvalid())
743     return ExprError();
744   Res = DefaultLvalueConversion(Res.get());
745   if (Res.isInvalid())
746     return ExprError();
747   return Res;
748 }
749
750 /// CallExprUnaryConversions - a special case of an unary conversion
751 /// performed on a function designator of a call expression.
752 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
753   QualType Ty = E->getType();
754   ExprResult Res = E;
755   // Only do implicit cast for a function type, but not for a pointer
756   // to function type.
757   if (Ty->isFunctionType()) {
758     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
759                             CK_FunctionToPointerDecay).get();
760     if (Res.isInvalid())
761       return ExprError();
762   }
763   Res = DefaultLvalueConversion(Res.get());
764   if (Res.isInvalid())
765     return ExprError();
766   return Res.get();
767 }
768
769 /// UsualUnaryConversions - Performs various conversions that are common to most
770 /// operators (C99 6.3). The conversions of array and function types are
771 /// sometimes suppressed. For example, the array->pointer conversion doesn't
772 /// apply if the array is an argument to the sizeof or address (&) operators.
773 /// In these instances, this routine should *not* be called.
774 ExprResult Sema::UsualUnaryConversions(Expr *E) {
775   // First, convert to an r-value.
776   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
777   if (Res.isInvalid())
778     return ExprError();
779   E = Res.get();
780
781   QualType Ty = E->getType();
782   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
783
784   // Half FP have to be promoted to float unless it is natively supported
785   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
786     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
787
788   // Try to perform integral promotions if the object has a theoretically
789   // promotable type.
790   if (Ty->isIntegralOrUnscopedEnumerationType()) {
791     // C99 6.3.1.1p2:
792     //
793     //   The following may be used in an expression wherever an int or
794     //   unsigned int may be used:
795     //     - an object or expression with an integer type whose integer
796     //       conversion rank is less than or equal to the rank of int
797     //       and unsigned int.
798     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
799     //
800     //   If an int can represent all values of the original type, the
801     //   value is converted to an int; otherwise, it is converted to an
802     //   unsigned int. These are called the integer promotions. All
803     //   other types are unchanged by the integer promotions.
804
805     QualType PTy = Context.isPromotableBitField(E);
806     if (!PTy.isNull()) {
807       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
808       return E;
809     }
810     if (Ty->isPromotableIntegerType()) {
811       QualType PT = Context.getPromotedIntegerType(Ty);
812       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
813       return E;
814     }
815   }
816   return E;
817 }
818
819 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
820 /// do not have a prototype. Arguments that have type float or __fp16
821 /// are promoted to double. All other argument types are converted by
822 /// UsualUnaryConversions().
823 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
824   QualType Ty = E->getType();
825   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
826
827   ExprResult Res = UsualUnaryConversions(E);
828   if (Res.isInvalid())
829     return ExprError();
830   E = Res.get();
831
832   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
833   // double.
834   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
835   if (BTy && (BTy->getKind() == BuiltinType::Half ||
836               BTy->getKind() == BuiltinType::Float)) {
837     if (getLangOpts().OpenCL &&
838         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
839         if (BTy->getKind() == BuiltinType::Half) {
840             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
841         }
842     } else {
843       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
844     }
845   }
846
847   // C++ performs lvalue-to-rvalue conversion as a default argument
848   // promotion, even on class types, but note:
849   //   C++11 [conv.lval]p2:
850   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
851   //     operand or a subexpression thereof the value contained in the
852   //     referenced object is not accessed. Otherwise, if the glvalue
853   //     has a class type, the conversion copy-initializes a temporary
854   //     of type T from the glvalue and the result of the conversion
855   //     is a prvalue for the temporary.
856   // FIXME: add some way to gate this entire thing for correctness in
857   // potentially potentially evaluated contexts.
858   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
859     ExprResult Temp = PerformCopyInitialization(
860                        InitializedEntity::InitializeTemporary(E->getType()),
861                                                 E->getExprLoc(), E);
862     if (Temp.isInvalid())
863       return ExprError();
864     E = Temp.get();
865   }
866
867   return E;
868 }
869
870 /// Determine the degree of POD-ness for an expression.
871 /// Incomplete types are considered POD, since this check can be performed
872 /// when we're in an unevaluated context.
873 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
874   if (Ty->isIncompleteType()) {
875     // C++11 [expr.call]p7:
876     //   After these conversions, if the argument does not have arithmetic,
877     //   enumeration, pointer, pointer to member, or class type, the program
878     //   is ill-formed.
879     //
880     // Since we've already performed array-to-pointer and function-to-pointer
881     // decay, the only such type in C++ is cv void. This also handles
882     // initializer lists as variadic arguments.
883     if (Ty->isVoidType())
884       return VAK_Invalid;
885
886     if (Ty->isObjCObjectType())
887       return VAK_Invalid;
888     return VAK_Valid;
889   }
890
891   if (Ty.isCXX98PODType(Context))
892     return VAK_Valid;
893
894   // C++11 [expr.call]p7:
895   //   Passing a potentially-evaluated argument of class type (Clause 9)
896   //   having a non-trivial copy constructor, a non-trivial move constructor,
897   //   or a non-trivial destructor, with no corresponding parameter,
898   //   is conditionally-supported with implementation-defined semantics.
899   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
900     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
901       if (!Record->hasNonTrivialCopyConstructor() &&
902           !Record->hasNonTrivialMoveConstructor() &&
903           !Record->hasNonTrivialDestructor())
904         return VAK_ValidInCXX11;
905
906   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
907     return VAK_Valid;
908
909   if (Ty->isObjCObjectType())
910     return VAK_Invalid;
911
912   if (getLangOpts().MSVCCompat)
913     return VAK_MSVCUndefined;
914
915   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
916   // permitted to reject them. We should consider doing so.
917   return VAK_Undefined;
918 }
919
920 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
921   // Don't allow one to pass an Objective-C interface to a vararg.
922   const QualType &Ty = E->getType();
923   VarArgKind VAK = isValidVarArgType(Ty);
924
925   // Complain about passing non-POD types through varargs.
926   switch (VAK) {
927   case VAK_ValidInCXX11:
928     DiagRuntimeBehavior(
929         E->getLocStart(), nullptr,
930         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
931           << Ty << CT);
932     // Fall through.
933   case VAK_Valid:
934     if (Ty->isRecordType()) {
935       // This is unlikely to be what the user intended. If the class has a
936       // 'c_str' member function, the user probably meant to call that.
937       DiagRuntimeBehavior(E->getLocStart(), nullptr,
938                           PDiag(diag::warn_pass_class_arg_to_vararg)
939                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
940     }
941     break;
942
943   case VAK_Undefined:
944   case VAK_MSVCUndefined:
945     DiagRuntimeBehavior(
946         E->getLocStart(), nullptr,
947         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
948           << getLangOpts().CPlusPlus11 << Ty << CT);
949     break;
950
951   case VAK_Invalid:
952     if (Ty->isObjCObjectType())
953       DiagRuntimeBehavior(
954           E->getLocStart(), nullptr,
955           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
956             << Ty << CT);
957     else
958       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
959         << isa<InitListExpr>(E) << Ty << CT;
960     break;
961   }
962 }
963
964 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
965 /// will create a trap if the resulting type is not a POD type.
966 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
967                                                   FunctionDecl *FDecl) {
968   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
969     // Strip the unbridged-cast placeholder expression off, if applicable.
970     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
971         (CT == VariadicMethod ||
972          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
973       E = stripARCUnbridgedCast(E);
974
975     // Otherwise, do normal placeholder checking.
976     } else {
977       ExprResult ExprRes = CheckPlaceholderExpr(E);
978       if (ExprRes.isInvalid())
979         return ExprError();
980       E = ExprRes.get();
981     }
982   }
983   
984   ExprResult ExprRes = DefaultArgumentPromotion(E);
985   if (ExprRes.isInvalid())
986     return ExprError();
987   E = ExprRes.get();
988
989   // Diagnostics regarding non-POD argument types are
990   // emitted along with format string checking in Sema::CheckFunctionCall().
991   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
992     // Turn this into a trap.
993     CXXScopeSpec SS;
994     SourceLocation TemplateKWLoc;
995     UnqualifiedId Name;
996     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
997                        E->getLocStart());
998     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
999                                           Name, true, false);
1000     if (TrapFn.isInvalid())
1001       return ExprError();
1002
1003     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
1004                                     E->getLocStart(), None,
1005                                     E->getLocEnd());
1006     if (Call.isInvalid())
1007       return ExprError();
1008
1009     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1010                                   Call.get(), E);
1011     if (Comma.isInvalid())
1012       return ExprError();
1013     return Comma.get();
1014   }
1015
1016   if (!getLangOpts().CPlusPlus &&
1017       RequireCompleteType(E->getExprLoc(), E->getType(),
1018                           diag::err_call_incomplete_argument))
1019     return ExprError();
1020
1021   return E;
1022 }
1023
1024 /// \brief Converts an integer to complex float type.  Helper function of
1025 /// UsualArithmeticConversions()
1026 ///
1027 /// \return false if the integer expression is an integer type and is
1028 /// successfully converted to the complex type.
1029 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1030                                                   ExprResult &ComplexExpr,
1031                                                   QualType IntTy,
1032                                                   QualType ComplexTy,
1033                                                   bool SkipCast) {
1034   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1035   if (SkipCast) return false;
1036   if (IntTy->isIntegerType()) {
1037     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1038     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1039     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1040                                   CK_FloatingRealToComplex);
1041   } else {
1042     assert(IntTy->isComplexIntegerType());
1043     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1044                                   CK_IntegralComplexToFloatingComplex);
1045   }
1046   return false;
1047 }
1048
1049 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1050 /// UsualArithmeticConversions()
1051 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1052                                              ExprResult &RHS, QualType LHSType,
1053                                              QualType RHSType,
1054                                              bool IsCompAssign) {
1055   // if we have an integer operand, the result is the complex type.
1056   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1057                                              /*skipCast*/false))
1058     return LHSType;
1059   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1060                                              /*skipCast*/IsCompAssign))
1061     return RHSType;
1062
1063   // This handles complex/complex, complex/float, or float/complex.
1064   // When both operands are complex, the shorter operand is converted to the
1065   // type of the longer, and that is the type of the result. This corresponds
1066   // to what is done when combining two real floating-point operands.
1067   // The fun begins when size promotion occur across type domains.
1068   // From H&S 6.3.4: When one operand is complex and the other is a real
1069   // floating-point type, the less precise type is converted, within it's
1070   // real or complex domain, to the precision of the other type. For example,
1071   // when combining a "long double" with a "double _Complex", the
1072   // "double _Complex" is promoted to "long double _Complex".
1073
1074   // Compute the rank of the two types, regardless of whether they are complex.
1075   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1076
1077   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1078   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1079   QualType LHSElementType =
1080       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1081   QualType RHSElementType =
1082       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1083
1084   QualType ResultType = S.Context.getComplexType(LHSElementType);
1085   if (Order < 0) {
1086     // Promote the precision of the LHS if not an assignment.
1087     ResultType = S.Context.getComplexType(RHSElementType);
1088     if (!IsCompAssign) {
1089       if (LHSComplexType)
1090         LHS =
1091             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1092       else
1093         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1094     }
1095   } else if (Order > 0) {
1096     // Promote the precision of the RHS.
1097     if (RHSComplexType)
1098       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1099     else
1100       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1101   }
1102   return ResultType;
1103 }
1104
1105 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1106 /// of UsualArithmeticConversions()
1107 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1108                                            ExprResult &IntExpr,
1109                                            QualType FloatTy, QualType IntTy,
1110                                            bool ConvertFloat, bool ConvertInt) {
1111   if (IntTy->isIntegerType()) {
1112     if (ConvertInt)
1113       // Convert intExpr to the lhs floating point type.
1114       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1115                                     CK_IntegralToFloating);
1116     return FloatTy;
1117   }
1118      
1119   // Convert both sides to the appropriate complex float.
1120   assert(IntTy->isComplexIntegerType());
1121   QualType result = S.Context.getComplexType(FloatTy);
1122
1123   // _Complex int -> _Complex float
1124   if (ConvertInt)
1125     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1126                                   CK_IntegralComplexToFloatingComplex);
1127
1128   // float -> _Complex float
1129   if (ConvertFloat)
1130     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1131                                     CK_FloatingRealToComplex);
1132
1133   return result;
1134 }
1135
1136 /// \brief Handle arithmethic conversion with floating point types.  Helper
1137 /// function of UsualArithmeticConversions()
1138 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1139                                       ExprResult &RHS, QualType LHSType,
1140                                       QualType RHSType, bool IsCompAssign) {
1141   bool LHSFloat = LHSType->isRealFloatingType();
1142   bool RHSFloat = RHSType->isRealFloatingType();
1143
1144   // If we have two real floating types, convert the smaller operand
1145   // to the bigger result.
1146   if (LHSFloat && RHSFloat) {
1147     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1148     if (order > 0) {
1149       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1150       return LHSType;
1151     }
1152
1153     assert(order < 0 && "illegal float comparison");
1154     if (!IsCompAssign)
1155       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1156     return RHSType;
1157   }
1158
1159   if (LHSFloat) {
1160     // Half FP has to be promoted to float unless it is natively supported
1161     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1162       LHSType = S.Context.FloatTy;
1163
1164     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1165                                       /*convertFloat=*/!IsCompAssign,
1166                                       /*convertInt=*/ true);
1167   }
1168   assert(RHSFloat);
1169   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1170                                     /*convertInt=*/ true,
1171                                     /*convertFloat=*/!IsCompAssign);
1172 }
1173
1174 /// \brief Diagnose attempts to convert between __float128 and long double if
1175 /// there is no support for such conversion. Helper function of
1176 /// UsualArithmeticConversions().
1177 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1178                                       QualType RHSType) {
1179   /*  No issue converting if at least one of the types is not a floating point
1180       type or the two types have the same rank.
1181   */
1182   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1183       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1184     return false;
1185
1186   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1187          "The remaining types must be floating point types.");
1188
1189   auto *LHSComplex = LHSType->getAs<ComplexType>();
1190   auto *RHSComplex = RHSType->getAs<ComplexType>();
1191
1192   QualType LHSElemType = LHSComplex ?
1193     LHSComplex->getElementType() : LHSType;
1194   QualType RHSElemType = RHSComplex ?
1195     RHSComplex->getElementType() : RHSType;
1196
1197   // No issue if the two types have the same representation
1198   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1199       &S.Context.getFloatTypeSemantics(RHSElemType))
1200     return false;
1201
1202   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1203                                 RHSElemType == S.Context.LongDoubleTy);
1204   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1205                             RHSElemType == S.Context.Float128Ty);
1206
1207   /* We've handled the situation where __float128 and long double have the same
1208      representation. The only other allowable conversion is if long double is
1209      really just double.
1210   */
1211   return Float128AndLongDouble &&
1212     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1213      &llvm::APFloat::IEEEdouble());
1214 }
1215
1216 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1217
1218 namespace {
1219 /// These helper callbacks are placed in an anonymous namespace to
1220 /// permit their use as function template parameters.
1221 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1222   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1223 }
1224
1225 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1226   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1227                              CK_IntegralComplexCast);
1228 }
1229 }
1230
1231 /// \brief Handle integer arithmetic conversions.  Helper function of
1232 /// UsualArithmeticConversions()
1233 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1234 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1235                                         ExprResult &RHS, QualType LHSType,
1236                                         QualType RHSType, bool IsCompAssign) {
1237   // The rules for this case are in C99 6.3.1.8
1238   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1239   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1240   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1241   if (LHSSigned == RHSSigned) {
1242     // Same signedness; use the higher-ranked type
1243     if (order >= 0) {
1244       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1245       return LHSType;
1246     } else if (!IsCompAssign)
1247       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1248     return RHSType;
1249   } else if (order != (LHSSigned ? 1 : -1)) {
1250     // The unsigned type has greater than or equal rank to the
1251     // signed type, so use the unsigned type
1252     if (RHSSigned) {
1253       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1254       return LHSType;
1255     } else if (!IsCompAssign)
1256       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1257     return RHSType;
1258   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1259     // The two types are different widths; if we are here, that
1260     // means the signed type is larger than the unsigned type, so
1261     // use the signed type.
1262     if (LHSSigned) {
1263       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1264       return LHSType;
1265     } else if (!IsCompAssign)
1266       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1267     return RHSType;
1268   } else {
1269     // The signed type is higher-ranked than the unsigned type,
1270     // but isn't actually any bigger (like unsigned int and long
1271     // on most 32-bit systems).  Use the unsigned type corresponding
1272     // to the signed type.
1273     QualType result =
1274       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1275     RHS = (*doRHSCast)(S, RHS.get(), result);
1276     if (!IsCompAssign)
1277       LHS = (*doLHSCast)(S, LHS.get(), result);
1278     return result;
1279   }
1280 }
1281
1282 /// \brief Handle conversions with GCC complex int extension.  Helper function
1283 /// of UsualArithmeticConversions()
1284 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1285                                            ExprResult &RHS, QualType LHSType,
1286                                            QualType RHSType,
1287                                            bool IsCompAssign) {
1288   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1289   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1290
1291   if (LHSComplexInt && RHSComplexInt) {
1292     QualType LHSEltType = LHSComplexInt->getElementType();
1293     QualType RHSEltType = RHSComplexInt->getElementType();
1294     QualType ScalarType =
1295       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1296         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1297
1298     return S.Context.getComplexType(ScalarType);
1299   }
1300
1301   if (LHSComplexInt) {
1302     QualType LHSEltType = LHSComplexInt->getElementType();
1303     QualType ScalarType =
1304       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1305         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1306     QualType ComplexType = S.Context.getComplexType(ScalarType);
1307     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1308                               CK_IntegralRealToComplex);
1309  
1310     return ComplexType;
1311   }
1312
1313   assert(RHSComplexInt);
1314
1315   QualType RHSEltType = RHSComplexInt->getElementType();
1316   QualType ScalarType =
1317     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1318       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1319   QualType ComplexType = S.Context.getComplexType(ScalarType);
1320   
1321   if (!IsCompAssign)
1322     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1323                               CK_IntegralRealToComplex);
1324   return ComplexType;
1325 }
1326
1327 /// UsualArithmeticConversions - Performs various conversions that are common to
1328 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1329 /// routine returns the first non-arithmetic type found. The client is
1330 /// responsible for emitting appropriate error diagnostics.
1331 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1332                                           bool IsCompAssign) {
1333   if (!IsCompAssign) {
1334     LHS = UsualUnaryConversions(LHS.get());
1335     if (LHS.isInvalid())
1336       return QualType();
1337   }
1338
1339   RHS = UsualUnaryConversions(RHS.get());
1340   if (RHS.isInvalid())
1341     return QualType();
1342
1343   // For conversion purposes, we ignore any qualifiers.
1344   // For example, "const float" and "float" are equivalent.
1345   QualType LHSType =
1346     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1347   QualType RHSType =
1348     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1349
1350   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1351   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1352     LHSType = AtomicLHS->getValueType();
1353
1354   // If both types are identical, no conversion is needed.
1355   if (LHSType == RHSType)
1356     return LHSType;
1357
1358   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1359   // The caller can deal with this (e.g. pointer + int).
1360   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1361     return QualType();
1362
1363   // Apply unary and bitfield promotions to the LHS's type.
1364   QualType LHSUnpromotedType = LHSType;
1365   if (LHSType->isPromotableIntegerType())
1366     LHSType = Context.getPromotedIntegerType(LHSType);
1367   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1368   if (!LHSBitfieldPromoteTy.isNull())
1369     LHSType = LHSBitfieldPromoteTy;
1370   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1371     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1372
1373   // If both types are identical, no conversion is needed.
1374   if (LHSType == RHSType)
1375     return LHSType;
1376
1377   // At this point, we have two different arithmetic types.
1378
1379   // Diagnose attempts to convert between __float128 and long double where
1380   // such conversions currently can't be handled.
1381   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1382     return QualType();
1383
1384   // Handle complex types first (C99 6.3.1.8p1).
1385   if (LHSType->isComplexType() || RHSType->isComplexType())
1386     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1387                                         IsCompAssign);
1388
1389   // Now handle "real" floating types (i.e. float, double, long double).
1390   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1391     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1392                                  IsCompAssign);
1393
1394   // Handle GCC complex int extension.
1395   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1396     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1397                                       IsCompAssign);
1398
1399   // Finally, we have two differing integer types.
1400   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1401            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1402 }
1403
1404
1405 //===----------------------------------------------------------------------===//
1406 //  Semantic Analysis for various Expression Types
1407 //===----------------------------------------------------------------------===//
1408
1409
1410 ExprResult
1411 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1412                                 SourceLocation DefaultLoc,
1413                                 SourceLocation RParenLoc,
1414                                 Expr *ControllingExpr,
1415                                 ArrayRef<ParsedType> ArgTypes,
1416                                 ArrayRef<Expr *> ArgExprs) {
1417   unsigned NumAssocs = ArgTypes.size();
1418   assert(NumAssocs == ArgExprs.size());
1419
1420   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1421   for (unsigned i = 0; i < NumAssocs; ++i) {
1422     if (ArgTypes[i])
1423       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1424     else
1425       Types[i] = nullptr;
1426   }
1427
1428   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1429                                              ControllingExpr,
1430                                              llvm::makeArrayRef(Types, NumAssocs),
1431                                              ArgExprs);
1432   delete [] Types;
1433   return ER;
1434 }
1435
1436 ExprResult
1437 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1438                                  SourceLocation DefaultLoc,
1439                                  SourceLocation RParenLoc,
1440                                  Expr *ControllingExpr,
1441                                  ArrayRef<TypeSourceInfo *> Types,
1442                                  ArrayRef<Expr *> Exprs) {
1443   unsigned NumAssocs = Types.size();
1444   assert(NumAssocs == Exprs.size());
1445
1446   // Decay and strip qualifiers for the controlling expression type, and handle
1447   // placeholder type replacement. See committee discussion from WG14 DR423.
1448   {
1449     EnterExpressionEvaluationContext Unevaluated(
1450         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1451     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1452     if (R.isInvalid())
1453       return ExprError();
1454     ControllingExpr = R.get();
1455   }
1456
1457   // The controlling expression is an unevaluated operand, so side effects are
1458   // likely unintended.
1459   if (!inTemplateInstantiation() &&
1460       ControllingExpr->HasSideEffects(Context, false))
1461     Diag(ControllingExpr->getExprLoc(),
1462          diag::warn_side_effects_unevaluated_context);
1463
1464   bool TypeErrorFound = false,
1465        IsResultDependent = ControllingExpr->isTypeDependent(),
1466        ContainsUnexpandedParameterPack
1467          = ControllingExpr->containsUnexpandedParameterPack();
1468
1469   for (unsigned i = 0; i < NumAssocs; ++i) {
1470     if (Exprs[i]->containsUnexpandedParameterPack())
1471       ContainsUnexpandedParameterPack = true;
1472
1473     if (Types[i]) {
1474       if (Types[i]->getType()->containsUnexpandedParameterPack())
1475         ContainsUnexpandedParameterPack = true;
1476
1477       if (Types[i]->getType()->isDependentType()) {
1478         IsResultDependent = true;
1479       } else {
1480         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1481         // complete object type other than a variably modified type."
1482         unsigned D = 0;
1483         if (Types[i]->getType()->isIncompleteType())
1484           D = diag::err_assoc_type_incomplete;
1485         else if (!Types[i]->getType()->isObjectType())
1486           D = diag::err_assoc_type_nonobject;
1487         else if (Types[i]->getType()->isVariablyModifiedType())
1488           D = diag::err_assoc_type_variably_modified;
1489
1490         if (D != 0) {
1491           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1492             << Types[i]->getTypeLoc().getSourceRange()
1493             << Types[i]->getType();
1494           TypeErrorFound = true;
1495         }
1496
1497         // C11 6.5.1.1p2 "No two generic associations in the same generic
1498         // selection shall specify compatible types."
1499         for (unsigned j = i+1; j < NumAssocs; ++j)
1500           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1501               Context.typesAreCompatible(Types[i]->getType(),
1502                                          Types[j]->getType())) {
1503             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1504                  diag::err_assoc_compatible_types)
1505               << Types[j]->getTypeLoc().getSourceRange()
1506               << Types[j]->getType()
1507               << Types[i]->getType();
1508             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1509                  diag::note_compat_assoc)
1510               << Types[i]->getTypeLoc().getSourceRange()
1511               << Types[i]->getType();
1512             TypeErrorFound = true;
1513           }
1514       }
1515     }
1516   }
1517   if (TypeErrorFound)
1518     return ExprError();
1519
1520   // If we determined that the generic selection is result-dependent, don't
1521   // try to compute the result expression.
1522   if (IsResultDependent)
1523     return new (Context) GenericSelectionExpr(
1524         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1525         ContainsUnexpandedParameterPack);
1526
1527   SmallVector<unsigned, 1> CompatIndices;
1528   unsigned DefaultIndex = -1U;
1529   for (unsigned i = 0; i < NumAssocs; ++i) {
1530     if (!Types[i])
1531       DefaultIndex = i;
1532     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1533                                         Types[i]->getType()))
1534       CompatIndices.push_back(i);
1535   }
1536
1537   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1538   // type compatible with at most one of the types named in its generic
1539   // association list."
1540   if (CompatIndices.size() > 1) {
1541     // We strip parens here because the controlling expression is typically
1542     // parenthesized in macro definitions.
1543     ControllingExpr = ControllingExpr->IgnoreParens();
1544     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1545       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1546       << (unsigned) CompatIndices.size();
1547     for (unsigned I : CompatIndices) {
1548       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1549            diag::note_compat_assoc)
1550         << Types[I]->getTypeLoc().getSourceRange()
1551         << Types[I]->getType();
1552     }
1553     return ExprError();
1554   }
1555
1556   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1557   // its controlling expression shall have type compatible with exactly one of
1558   // the types named in its generic association list."
1559   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1560     // We strip parens here because the controlling expression is typically
1561     // parenthesized in macro definitions.
1562     ControllingExpr = ControllingExpr->IgnoreParens();
1563     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1564       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1565     return ExprError();
1566   }
1567
1568   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1569   // type name that is compatible with the type of the controlling expression,
1570   // then the result expression of the generic selection is the expression
1571   // in that generic association. Otherwise, the result expression of the
1572   // generic selection is the expression in the default generic association."
1573   unsigned ResultIndex =
1574     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1575
1576   return new (Context) GenericSelectionExpr(
1577       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1578       ContainsUnexpandedParameterPack, ResultIndex);
1579 }
1580
1581 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1582 /// location of the token and the offset of the ud-suffix within it.
1583 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1584                                      unsigned Offset) {
1585   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1586                                         S.getLangOpts());
1587 }
1588
1589 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1590 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1591 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1592                                                  IdentifierInfo *UDSuffix,
1593                                                  SourceLocation UDSuffixLoc,
1594                                                  ArrayRef<Expr*> Args,
1595                                                  SourceLocation LitEndLoc) {
1596   assert(Args.size() <= 2 && "too many arguments for literal operator");
1597
1598   QualType ArgTy[2];
1599   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1600     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1601     if (ArgTy[ArgIdx]->isArrayType())
1602       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1603   }
1604
1605   DeclarationName OpName =
1606     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1607   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1608   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1609
1610   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1611   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1612                               /*AllowRaw*/false, /*AllowTemplate*/false,
1613                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1614     return ExprError();
1615
1616   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1617 }
1618
1619 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1620 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1621 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1622 /// multiple tokens.  However, the common case is that StringToks points to one
1623 /// string.
1624 ///
1625 ExprResult
1626 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1627   assert(!StringToks.empty() && "Must have at least one string!");
1628
1629   StringLiteralParser Literal(StringToks, PP);
1630   if (Literal.hadError)
1631     return ExprError();
1632
1633   SmallVector<SourceLocation, 4> StringTokLocs;
1634   for (const Token &Tok : StringToks)
1635     StringTokLocs.push_back(Tok.getLocation());
1636
1637   QualType CharTy = Context.CharTy;
1638   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1639   if (Literal.isWide()) {
1640     CharTy = Context.getWideCharType();
1641     Kind = StringLiteral::Wide;
1642   } else if (Literal.isUTF8()) {
1643     Kind = StringLiteral::UTF8;
1644   } else if (Literal.isUTF16()) {
1645     CharTy = Context.Char16Ty;
1646     Kind = StringLiteral::UTF16;
1647   } else if (Literal.isUTF32()) {
1648     CharTy = Context.Char32Ty;
1649     Kind = StringLiteral::UTF32;
1650   } else if (Literal.isPascal()) {
1651     CharTy = Context.UnsignedCharTy;
1652   }
1653
1654   QualType CharTyConst = CharTy;
1655   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1656   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1657     CharTyConst.addConst();
1658
1659   // Get an array type for the string, according to C99 6.4.5.  This includes
1660   // the nul terminator character as well as the string length for pascal
1661   // strings.
1662   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1663                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1664                                  ArrayType::Normal, 0);
1665
1666   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1667   if (getLangOpts().OpenCL) {
1668     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1669   }
1670
1671   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1672   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1673                                              Kind, Literal.Pascal, StrTy,
1674                                              &StringTokLocs[0],
1675                                              StringTokLocs.size());
1676   if (Literal.getUDSuffix().empty())
1677     return Lit;
1678
1679   // We're building a user-defined literal.
1680   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1681   SourceLocation UDSuffixLoc =
1682     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1683                    Literal.getUDSuffixOffset());
1684
1685   // Make sure we're allowed user-defined literals here.
1686   if (!UDLScope)
1687     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1688
1689   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1690   //   operator "" X (str, len)
1691   QualType SizeType = Context.getSizeType();
1692
1693   DeclarationName OpName =
1694     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1695   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1696   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1697
1698   QualType ArgTy[] = {
1699     Context.getArrayDecayedType(StrTy), SizeType
1700   };
1701
1702   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1703   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1704                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1705                                 /*AllowStringTemplate*/true)) {
1706
1707   case LOLR_Cooked: {
1708     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1709     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1710                                                     StringTokLocs[0]);
1711     Expr *Args[] = { Lit, LenArg };
1712
1713     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1714   }
1715
1716   case LOLR_StringTemplate: {
1717     TemplateArgumentListInfo ExplicitArgs;
1718
1719     unsigned CharBits = Context.getIntWidth(CharTy);
1720     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1721     llvm::APSInt Value(CharBits, CharIsUnsigned);
1722
1723     TemplateArgument TypeArg(CharTy);
1724     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1725     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1726
1727     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1728       Value = Lit->getCodeUnit(I);
1729       TemplateArgument Arg(Context, Value, CharTy);
1730       TemplateArgumentLocInfo ArgInfo;
1731       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1732     }
1733     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1734                                     &ExplicitArgs);
1735   }
1736   case LOLR_Raw:
1737   case LOLR_Template:
1738     llvm_unreachable("unexpected literal operator lookup result");
1739   case LOLR_Error:
1740     return ExprError();
1741   }
1742   llvm_unreachable("unexpected literal operator lookup result");
1743 }
1744
1745 ExprResult
1746 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1747                        SourceLocation Loc,
1748                        const CXXScopeSpec *SS) {
1749   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1750   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1751 }
1752
1753 /// BuildDeclRefExpr - Build an expression that references a
1754 /// declaration that does not require a closure capture.
1755 ExprResult
1756 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1757                        const DeclarationNameInfo &NameInfo,
1758                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1759                        const TemplateArgumentListInfo *TemplateArgs) {
1760   bool RefersToCapturedVariable =
1761       isa<VarDecl>(D) &&
1762       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1763
1764   DeclRefExpr *E;
1765   if (isa<VarTemplateSpecializationDecl>(D)) {
1766     VarTemplateSpecializationDecl *VarSpec =
1767         cast<VarTemplateSpecializationDecl>(D);
1768
1769     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1770                                         : NestedNameSpecifierLoc(),
1771                             VarSpec->getTemplateKeywordLoc(), D,
1772                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1773                             FoundD, TemplateArgs);
1774   } else {
1775     assert(!TemplateArgs && "No template arguments for non-variable"
1776                             " template specialization references");
1777     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1778                                         : NestedNameSpecifierLoc(),
1779                             SourceLocation(), D, RefersToCapturedVariable,
1780                             NameInfo, Ty, VK, FoundD);
1781   }
1782
1783   MarkDeclRefReferenced(E);
1784
1785   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1786       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1787       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1788       recordUseOfEvaluatedWeak(E);
1789
1790   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1791   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1792     FD = IFD->getAnonField();
1793   if (FD) {
1794     UnusedPrivateFields.remove(FD);
1795     // Just in case we're building an illegal pointer-to-member.
1796     if (FD->isBitField())
1797       E->setObjectKind(OK_BitField);
1798   }
1799
1800   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1801   // designates a bit-field.
1802   if (auto *BD = dyn_cast<BindingDecl>(D))
1803     if (auto *BE = BD->getBinding())
1804       E->setObjectKind(BE->getObjectKind());
1805
1806   return E;
1807 }
1808
1809 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1810 /// possibly a list of template arguments.
1811 ///
1812 /// If this produces template arguments, it is permitted to call
1813 /// DecomposeTemplateName.
1814 ///
1815 /// This actually loses a lot of source location information for
1816 /// non-standard name kinds; we should consider preserving that in
1817 /// some way.
1818 void
1819 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1820                              TemplateArgumentListInfo &Buffer,
1821                              DeclarationNameInfo &NameInfo,
1822                              const TemplateArgumentListInfo *&TemplateArgs) {
1823   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1824     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1825     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1826
1827     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1828                                        Id.TemplateId->NumArgs);
1829     translateTemplateArguments(TemplateArgsPtr, Buffer);
1830
1831     TemplateName TName = Id.TemplateId->Template.get();
1832     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1833     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1834     TemplateArgs = &Buffer;
1835   } else {
1836     NameInfo = GetNameFromUnqualifiedId(Id);
1837     TemplateArgs = nullptr;
1838   }
1839 }
1840
1841 static void emitEmptyLookupTypoDiagnostic(
1842     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1843     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1844     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1845   DeclContext *Ctx =
1846       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1847   if (!TC) {
1848     // Emit a special diagnostic for failed member lookups.
1849     // FIXME: computing the declaration context might fail here (?)
1850     if (Ctx)
1851       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1852                                                  << SS.getRange();
1853     else
1854       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1855     return;
1856   }
1857
1858   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1859   bool DroppedSpecifier =
1860       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1861   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1862                         ? diag::note_implicit_param_decl
1863                         : diag::note_previous_decl;
1864   if (!Ctx)
1865     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1866                          SemaRef.PDiag(NoteID));
1867   else
1868     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1869                                  << Typo << Ctx << DroppedSpecifier
1870                                  << SS.getRange(),
1871                          SemaRef.PDiag(NoteID));
1872 }
1873
1874 /// Diagnose an empty lookup.
1875 ///
1876 /// \return false if new lookup candidates were found
1877 bool
1878 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1879                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1880                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1881                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1882   DeclarationName Name = R.getLookupName();
1883
1884   unsigned diagnostic = diag::err_undeclared_var_use;
1885   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1886   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1887       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1888       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1889     diagnostic = diag::err_undeclared_use;
1890     diagnostic_suggest = diag::err_undeclared_use_suggest;
1891   }
1892
1893   // If the original lookup was an unqualified lookup, fake an
1894   // unqualified lookup.  This is useful when (for example) the
1895   // original lookup would not have found something because it was a
1896   // dependent name.
1897   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1898   while (DC) {
1899     if (isa<CXXRecordDecl>(DC)) {
1900       LookupQualifiedName(R, DC);
1901
1902       if (!R.empty()) {
1903         // Don't give errors about ambiguities in this lookup.
1904         R.suppressDiagnostics();
1905
1906         // During a default argument instantiation the CurContext points
1907         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1908         // function parameter list, hence add an explicit check.
1909         bool isDefaultArgument =
1910             !CodeSynthesisContexts.empty() &&
1911             CodeSynthesisContexts.back().Kind ==
1912                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1913         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1914         bool isInstance = CurMethod &&
1915                           CurMethod->isInstance() &&
1916                           DC == CurMethod->getParent() && !isDefaultArgument;
1917
1918         // Give a code modification hint to insert 'this->'.
1919         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1920         // Actually quite difficult!
1921         if (getLangOpts().MSVCCompat)
1922           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1923         if (isInstance) {
1924           Diag(R.getNameLoc(), diagnostic) << Name
1925             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1926           CheckCXXThisCapture(R.getNameLoc());
1927         } else {
1928           Diag(R.getNameLoc(), diagnostic) << Name;
1929         }
1930
1931         // Do we really want to note all of these?
1932         for (NamedDecl *D : R)
1933           Diag(D->getLocation(), diag::note_dependent_var_use);
1934
1935         // Return true if we are inside a default argument instantiation
1936         // and the found name refers to an instance member function, otherwise
1937         // the function calling DiagnoseEmptyLookup will try to create an
1938         // implicit member call and this is wrong for default argument.
1939         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1940           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1941           return true;
1942         }
1943
1944         // Tell the callee to try to recover.
1945         return false;
1946       }
1947
1948       R.clear();
1949     }
1950
1951     // In Microsoft mode, if we are performing lookup from within a friend
1952     // function definition declared at class scope then we must set
1953     // DC to the lexical parent to be able to search into the parent
1954     // class.
1955     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1956         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1957         DC->getLexicalParent()->isRecord())
1958       DC = DC->getLexicalParent();
1959     else
1960       DC = DC->getParent();
1961   }
1962
1963   // We didn't find anything, so try to correct for a typo.
1964   TypoCorrection Corrected;
1965   if (S && Out) {
1966     SourceLocation TypoLoc = R.getNameLoc();
1967     assert(!ExplicitTemplateArgs &&
1968            "Diagnosing an empty lookup with explicit template args!");
1969     *Out = CorrectTypoDelayed(
1970         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1971         [=](const TypoCorrection &TC) {
1972           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1973                                         diagnostic, diagnostic_suggest);
1974         },
1975         nullptr, CTK_ErrorRecovery);
1976     if (*Out)
1977       return true;
1978   } else if (S && (Corrected =
1979                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1980                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1981     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1982     bool DroppedSpecifier =
1983         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1984     R.setLookupName(Corrected.getCorrection());
1985
1986     bool AcceptableWithRecovery = false;
1987     bool AcceptableWithoutRecovery = false;
1988     NamedDecl *ND = Corrected.getFoundDecl();
1989     if (ND) {
1990       if (Corrected.isOverloaded()) {
1991         OverloadCandidateSet OCS(R.getNameLoc(),
1992                                  OverloadCandidateSet::CSK_Normal);
1993         OverloadCandidateSet::iterator Best;
1994         for (NamedDecl *CD : Corrected) {
1995           if (FunctionTemplateDecl *FTD =
1996                    dyn_cast<FunctionTemplateDecl>(CD))
1997             AddTemplateOverloadCandidate(
1998                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1999                 Args, OCS);
2000           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2001             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2002               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2003                                    Args, OCS);
2004         }
2005         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2006         case OR_Success:
2007           ND = Best->FoundDecl;
2008           Corrected.setCorrectionDecl(ND);
2009           break;
2010         default:
2011           // FIXME: Arbitrarily pick the first declaration for the note.
2012           Corrected.setCorrectionDecl(ND);
2013           break;
2014         }
2015       }
2016       R.addDecl(ND);
2017       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2018         CXXRecordDecl *Record = nullptr;
2019         if (Corrected.getCorrectionSpecifier()) {
2020           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2021           Record = Ty->getAsCXXRecordDecl();
2022         }
2023         if (!Record)
2024           Record = cast<CXXRecordDecl>(
2025               ND->getDeclContext()->getRedeclContext());
2026         R.setNamingClass(Record);
2027       }
2028
2029       auto *UnderlyingND = ND->getUnderlyingDecl();
2030       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2031                                isa<FunctionTemplateDecl>(UnderlyingND);
2032       // FIXME: If we ended up with a typo for a type name or
2033       // Objective-C class name, we're in trouble because the parser
2034       // is in the wrong place to recover. Suggest the typo
2035       // correction, but don't make it a fix-it since we're not going
2036       // to recover well anyway.
2037       AcceptableWithoutRecovery =
2038           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2039     } else {
2040       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2041       // because we aren't able to recover.
2042       AcceptableWithoutRecovery = true;
2043     }
2044
2045     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2046       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2047                             ? diag::note_implicit_param_decl
2048                             : diag::note_previous_decl;
2049       if (SS.isEmpty())
2050         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2051                      PDiag(NoteID), AcceptableWithRecovery);
2052       else
2053         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2054                                   << Name << computeDeclContext(SS, false)
2055                                   << DroppedSpecifier << SS.getRange(),
2056                      PDiag(NoteID), AcceptableWithRecovery);
2057
2058       // Tell the callee whether to try to recover.
2059       return !AcceptableWithRecovery;
2060     }
2061   }
2062   R.clear();
2063
2064   // Emit a special diagnostic for failed member lookups.
2065   // FIXME: computing the declaration context might fail here (?)
2066   if (!SS.isEmpty()) {
2067     Diag(R.getNameLoc(), diag::err_no_member)
2068       << Name << computeDeclContext(SS, false)
2069       << SS.getRange();
2070     return true;
2071   }
2072
2073   // Give up, we can't recover.
2074   Diag(R.getNameLoc(), diagnostic) << Name;
2075   return true;
2076 }
2077
2078 /// In Microsoft mode, if we are inside a template class whose parent class has
2079 /// dependent base classes, and we can't resolve an unqualified identifier, then
2080 /// assume the identifier is a member of a dependent base class.  We can only
2081 /// recover successfully in static methods, instance methods, and other contexts
2082 /// where 'this' is available.  This doesn't precisely match MSVC's
2083 /// instantiation model, but it's close enough.
2084 static Expr *
2085 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2086                                DeclarationNameInfo &NameInfo,
2087                                SourceLocation TemplateKWLoc,
2088                                const TemplateArgumentListInfo *TemplateArgs) {
2089   // Only try to recover from lookup into dependent bases in static methods or
2090   // contexts where 'this' is available.
2091   QualType ThisType = S.getCurrentThisType();
2092   const CXXRecordDecl *RD = nullptr;
2093   if (!ThisType.isNull())
2094     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2095   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2096     RD = MD->getParent();
2097   if (!RD || !RD->hasAnyDependentBases())
2098     return nullptr;
2099
2100   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2101   // is available, suggest inserting 'this->' as a fixit.
2102   SourceLocation Loc = NameInfo.getLoc();
2103   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2104   DB << NameInfo.getName() << RD;
2105
2106   if (!ThisType.isNull()) {
2107     DB << FixItHint::CreateInsertion(Loc, "this->");
2108     return CXXDependentScopeMemberExpr::Create(
2109         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2110         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2111         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2112   }
2113
2114   // Synthesize a fake NNS that points to the derived class.  This will
2115   // perform name lookup during template instantiation.
2116   CXXScopeSpec SS;
2117   auto *NNS =
2118       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2119   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2120   return DependentScopeDeclRefExpr::Create(
2121       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2122       TemplateArgs);
2123 }
2124
2125 ExprResult
2126 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2127                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2128                         bool HasTrailingLParen, bool IsAddressOfOperand,
2129                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2130                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2131   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2132          "cannot be direct & operand and have a trailing lparen");
2133   if (SS.isInvalid())
2134     return ExprError();
2135
2136   TemplateArgumentListInfo TemplateArgsBuffer;
2137
2138   // Decompose the UnqualifiedId into the following data.
2139   DeclarationNameInfo NameInfo;
2140   const TemplateArgumentListInfo *TemplateArgs;
2141   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2142
2143   DeclarationName Name = NameInfo.getName();
2144   IdentifierInfo *II = Name.getAsIdentifierInfo();
2145   SourceLocation NameLoc = NameInfo.getLoc();
2146
2147   if (II && II->isEditorPlaceholder()) {
2148     // FIXME: When typed placeholders are supported we can create a typed
2149     // placeholder expression node.
2150     return ExprError();
2151   }
2152
2153   // C++ [temp.dep.expr]p3:
2154   //   An id-expression is type-dependent if it contains:
2155   //     -- an identifier that was declared with a dependent type,
2156   //        (note: handled after lookup)
2157   //     -- a template-id that is dependent,
2158   //        (note: handled in BuildTemplateIdExpr)
2159   //     -- a conversion-function-id that specifies a dependent type,
2160   //     -- a nested-name-specifier that contains a class-name that
2161   //        names a dependent type.
2162   // Determine whether this is a member of an unknown specialization;
2163   // we need to handle these differently.
2164   bool DependentID = false;
2165   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2166       Name.getCXXNameType()->isDependentType()) {
2167     DependentID = true;
2168   } else if (SS.isSet()) {
2169     if (DeclContext *DC = computeDeclContext(SS, false)) {
2170       if (RequireCompleteDeclContext(SS, DC))
2171         return ExprError();
2172     } else {
2173       DependentID = true;
2174     }
2175   }
2176
2177   if (DependentID)
2178     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2179                                       IsAddressOfOperand, TemplateArgs);
2180
2181   // Perform the required lookup.
2182   LookupResult R(*this, NameInfo, 
2183                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2184                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2185   if (TemplateArgs) {
2186     // Lookup the template name again to correctly establish the context in
2187     // which it was found. This is really unfortunate as we already did the
2188     // lookup to determine that it was a template name in the first place. If
2189     // this becomes a performance hit, we can work harder to preserve those
2190     // results until we get here but it's likely not worth it.
2191     bool MemberOfUnknownSpecialization;
2192     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2193                        MemberOfUnknownSpecialization);
2194     
2195     if (MemberOfUnknownSpecialization ||
2196         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2197       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2198                                         IsAddressOfOperand, TemplateArgs);
2199   } else {
2200     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2201     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2202
2203     // If the result might be in a dependent base class, this is a dependent 
2204     // id-expression.
2205     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2206       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2207                                         IsAddressOfOperand, TemplateArgs);
2208
2209     // If this reference is in an Objective-C method, then we need to do
2210     // some special Objective-C lookup, too.
2211     if (IvarLookupFollowUp) {
2212       ExprResult E(LookupInObjCMethod(R, S, II, true));
2213       if (E.isInvalid())
2214         return ExprError();
2215
2216       if (Expr *Ex = E.getAs<Expr>())
2217         return Ex;
2218     }
2219   }
2220
2221   if (R.isAmbiguous())
2222     return ExprError();
2223
2224   // This could be an implicitly declared function reference (legal in C90,
2225   // extension in C99, forbidden in C++).
2226   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2227     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2228     if (D) R.addDecl(D);
2229   }
2230
2231   // Determine whether this name might be a candidate for
2232   // argument-dependent lookup.
2233   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2234
2235   if (R.empty() && !ADL) {
2236     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2237       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2238                                                    TemplateKWLoc, TemplateArgs))
2239         return E;
2240     }
2241
2242     // Don't diagnose an empty lookup for inline assembly.
2243     if (IsInlineAsmIdentifier)
2244       return ExprError();
2245
2246     // If this name wasn't predeclared and if this is not a function
2247     // call, diagnose the problem.
2248     TypoExpr *TE = nullptr;
2249     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2250         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2251     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2252     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2253            "Typo correction callback misconfigured");
2254     if (CCC) {
2255       // Make sure the callback knows what the typo being diagnosed is.
2256       CCC->setTypoName(II);
2257       if (SS.isValid())
2258         CCC->setTypoNNS(SS.getScopeRep());
2259     }
2260     if (DiagnoseEmptyLookup(S, SS, R,
2261                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2262                             nullptr, None, &TE)) {
2263       if (TE && KeywordReplacement) {
2264         auto &State = getTypoExprState(TE);
2265         auto BestTC = State.Consumer->getNextCorrection();
2266         if (BestTC.isKeyword()) {
2267           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2268           if (State.DiagHandler)
2269             State.DiagHandler(BestTC);
2270           KeywordReplacement->startToken();
2271           KeywordReplacement->setKind(II->getTokenID());
2272           KeywordReplacement->setIdentifierInfo(II);
2273           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2274           // Clean up the state associated with the TypoExpr, since it has
2275           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2276           clearDelayedTypo(TE);
2277           // Signal that a correction to a keyword was performed by returning a
2278           // valid-but-null ExprResult.
2279           return (Expr*)nullptr;
2280         }
2281         State.Consumer->resetCorrectionStream();
2282       }
2283       return TE ? TE : ExprError();
2284     }
2285
2286     assert(!R.empty() &&
2287            "DiagnoseEmptyLookup returned false but added no results");
2288
2289     // If we found an Objective-C instance variable, let
2290     // LookupInObjCMethod build the appropriate expression to
2291     // reference the ivar.
2292     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2293       R.clear();
2294       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2295       // In a hopelessly buggy code, Objective-C instance variable
2296       // lookup fails and no expression will be built to reference it.
2297       if (!E.isInvalid() && !E.get())
2298         return ExprError();
2299       return E;
2300     }
2301   }
2302
2303   // This is guaranteed from this point on.
2304   assert(!R.empty() || ADL);
2305
2306   // Check whether this might be a C++ implicit instance member access.
2307   // C++ [class.mfct.non-static]p3:
2308   //   When an id-expression that is not part of a class member access
2309   //   syntax and not used to form a pointer to member is used in the
2310   //   body of a non-static member function of class X, if name lookup
2311   //   resolves the name in the id-expression to a non-static non-type
2312   //   member of some class C, the id-expression is transformed into a
2313   //   class member access expression using (*this) as the
2314   //   postfix-expression to the left of the . operator.
2315   //
2316   // But we don't actually need to do this for '&' operands if R
2317   // resolved to a function or overloaded function set, because the
2318   // expression is ill-formed if it actually works out to be a
2319   // non-static member function:
2320   //
2321   // C++ [expr.ref]p4:
2322   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2323   //   [t]he expression can be used only as the left-hand operand of a
2324   //   member function call.
2325   //
2326   // There are other safeguards against such uses, but it's important
2327   // to get this right here so that we don't end up making a
2328   // spuriously dependent expression if we're inside a dependent
2329   // instance method.
2330   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2331     bool MightBeImplicitMember;
2332     if (!IsAddressOfOperand)
2333       MightBeImplicitMember = true;
2334     else if (!SS.isEmpty())
2335       MightBeImplicitMember = false;
2336     else if (R.isOverloadedResult())
2337       MightBeImplicitMember = false;
2338     else if (R.isUnresolvableResult())
2339       MightBeImplicitMember = true;
2340     else
2341       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2342                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2343                               isa<MSPropertyDecl>(R.getFoundDecl());
2344
2345     if (MightBeImplicitMember)
2346       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2347                                              R, TemplateArgs, S);
2348   }
2349
2350   if (TemplateArgs || TemplateKWLoc.isValid()) {
2351
2352     // In C++1y, if this is a variable template id, then check it
2353     // in BuildTemplateIdExpr().
2354     // The single lookup result must be a variable template declaration.
2355     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2356         Id.TemplateId->Kind == TNK_Var_template) {
2357       assert(R.getAsSingle<VarTemplateDecl>() &&
2358              "There should only be one declaration found.");
2359     }
2360
2361     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2362   }
2363
2364   return BuildDeclarationNameExpr(SS, R, ADL);
2365 }
2366
2367 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2368 /// declaration name, generally during template instantiation.
2369 /// There's a large number of things which don't need to be done along
2370 /// this path.
2371 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2372     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2373     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2374   DeclContext *DC = computeDeclContext(SS, false);
2375   if (!DC)
2376     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2377                                      NameInfo, /*TemplateArgs=*/nullptr);
2378
2379   if (RequireCompleteDeclContext(SS, DC))
2380     return ExprError();
2381
2382   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2383   LookupQualifiedName(R, DC);
2384
2385   if (R.isAmbiguous())
2386     return ExprError();
2387
2388   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2389     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2390                                      NameInfo, /*TemplateArgs=*/nullptr);
2391
2392   if (R.empty()) {
2393     Diag(NameInfo.getLoc(), diag::err_no_member)
2394       << NameInfo.getName() << DC << SS.getRange();
2395     return ExprError();
2396   }
2397
2398   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2399     // Diagnose a missing typename if this resolved unambiguously to a type in
2400     // a dependent context.  If we can recover with a type, downgrade this to
2401     // a warning in Microsoft compatibility mode.
2402     unsigned DiagID = diag::err_typename_missing;
2403     if (RecoveryTSI && getLangOpts().MSVCCompat)
2404       DiagID = diag::ext_typename_missing;
2405     SourceLocation Loc = SS.getBeginLoc();
2406     auto D = Diag(Loc, DiagID);
2407     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2408       << SourceRange(Loc, NameInfo.getEndLoc());
2409
2410     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2411     // context.
2412     if (!RecoveryTSI)
2413       return ExprError();
2414
2415     // Only issue the fixit if we're prepared to recover.
2416     D << FixItHint::CreateInsertion(Loc, "typename ");
2417
2418     // Recover by pretending this was an elaborated type.
2419     QualType Ty = Context.getTypeDeclType(TD);
2420     TypeLocBuilder TLB;
2421     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2422
2423     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2424     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2425     QTL.setElaboratedKeywordLoc(SourceLocation());
2426     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2427
2428     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2429
2430     return ExprEmpty();
2431   }
2432
2433   // Defend against this resolving to an implicit member access. We usually
2434   // won't get here if this might be a legitimate a class member (we end up in
2435   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2436   // a pointer-to-member or in an unevaluated context in C++11.
2437   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2438     return BuildPossibleImplicitMemberExpr(SS,
2439                                            /*TemplateKWLoc=*/SourceLocation(),
2440                                            R, /*TemplateArgs=*/nullptr, S);
2441
2442   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2443 }
2444
2445 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2446 /// detected that we're currently inside an ObjC method.  Perform some
2447 /// additional lookup.
2448 ///
2449 /// Ideally, most of this would be done by lookup, but there's
2450 /// actually quite a lot of extra work involved.
2451 ///
2452 /// Returns a null sentinel to indicate trivial success.
2453 ExprResult
2454 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2455                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2456   SourceLocation Loc = Lookup.getNameLoc();
2457   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2458   
2459   // Check for error condition which is already reported.
2460   if (!CurMethod)
2461     return ExprError();
2462
2463   // There are two cases to handle here.  1) scoped lookup could have failed,
2464   // in which case we should look for an ivar.  2) scoped lookup could have
2465   // found a decl, but that decl is outside the current instance method (i.e.
2466   // a global variable).  In these two cases, we do a lookup for an ivar with
2467   // this name, if the lookup sucedes, we replace it our current decl.
2468
2469   // If we're in a class method, we don't normally want to look for
2470   // ivars.  But if we don't find anything else, and there's an
2471   // ivar, that's an error.
2472   bool IsClassMethod = CurMethod->isClassMethod();
2473
2474   bool LookForIvars;
2475   if (Lookup.empty())
2476     LookForIvars = true;
2477   else if (IsClassMethod)
2478     LookForIvars = false;
2479   else
2480     LookForIvars = (Lookup.isSingleResult() &&
2481                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2482   ObjCInterfaceDecl *IFace = nullptr;
2483   if (LookForIvars) {
2484     IFace = CurMethod->getClassInterface();
2485     ObjCInterfaceDecl *ClassDeclared;
2486     ObjCIvarDecl *IV = nullptr;
2487     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2488       // Diagnose using an ivar in a class method.
2489       if (IsClassMethod)
2490         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2491                          << IV->getDeclName());
2492
2493       // If we're referencing an invalid decl, just return this as a silent
2494       // error node.  The error diagnostic was already emitted on the decl.
2495       if (IV->isInvalidDecl())
2496         return ExprError();
2497
2498       // Check if referencing a field with __attribute__((deprecated)).
2499       if (DiagnoseUseOfDecl(IV, Loc))
2500         return ExprError();
2501
2502       // Diagnose the use of an ivar outside of the declaring class.
2503       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2504           !declaresSameEntity(ClassDeclared, IFace) &&
2505           !getLangOpts().DebuggerSupport)
2506         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2507
2508       // FIXME: This should use a new expr for a direct reference, don't
2509       // turn this into Self->ivar, just return a BareIVarExpr or something.
2510       IdentifierInfo &II = Context.Idents.get("self");
2511       UnqualifiedId SelfName;
2512       SelfName.setIdentifier(&II, SourceLocation());
2513       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2514       CXXScopeSpec SelfScopeSpec;
2515       SourceLocation TemplateKWLoc;
2516       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2517                                               SelfName, false, false);
2518       if (SelfExpr.isInvalid())
2519         return ExprError();
2520
2521       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2522       if (SelfExpr.isInvalid())
2523         return ExprError();
2524
2525       MarkAnyDeclReferenced(Loc, IV, true);
2526
2527       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2528       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2529           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2530         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2531
2532       ObjCIvarRefExpr *Result = new (Context)
2533           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2534                           IV->getLocation(), SelfExpr.get(), true, true);
2535
2536       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2537         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2538           recordUseOfEvaluatedWeak(Result);
2539       }
2540       if (getLangOpts().ObjCAutoRefCount) {
2541         if (CurContext->isClosure())
2542           Diag(Loc, diag::warn_implicitly_retains_self)
2543             << FixItHint::CreateInsertion(Loc, "self->");
2544       }
2545       
2546       return Result;
2547     }
2548   } else if (CurMethod->isInstanceMethod()) {
2549     // We should warn if a local variable hides an ivar.
2550     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2551       ObjCInterfaceDecl *ClassDeclared;
2552       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2553         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2554             declaresSameEntity(IFace, ClassDeclared))
2555           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2556       }
2557     }
2558   } else if (Lookup.isSingleResult() &&
2559              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2560     // If accessing a stand-alone ivar in a class method, this is an error.
2561     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2562       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2563                        << IV->getDeclName());
2564   }
2565
2566   if (Lookup.empty() && II && AllowBuiltinCreation) {
2567     // FIXME. Consolidate this with similar code in LookupName.
2568     if (unsigned BuiltinID = II->getBuiltinID()) {
2569       if (!(getLangOpts().CPlusPlus &&
2570             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2571         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2572                                            S, Lookup.isForRedeclaration(),
2573                                            Lookup.getNameLoc());
2574         if (D) Lookup.addDecl(D);
2575       }
2576     }
2577   }
2578   // Sentinel value saying that we didn't do anything special.
2579   return ExprResult((Expr *)nullptr);
2580 }
2581
2582 /// \brief Cast a base object to a member's actual type.
2583 ///
2584 /// Logically this happens in three phases:
2585 ///
2586 /// * First we cast from the base type to the naming class.
2587 ///   The naming class is the class into which we were looking
2588 ///   when we found the member;  it's the qualifier type if a
2589 ///   qualifier was provided, and otherwise it's the base type.
2590 ///
2591 /// * Next we cast from the naming class to the declaring class.
2592 ///   If the member we found was brought into a class's scope by
2593 ///   a using declaration, this is that class;  otherwise it's
2594 ///   the class declaring the member.
2595 ///
2596 /// * Finally we cast from the declaring class to the "true"
2597 ///   declaring class of the member.  This conversion does not
2598 ///   obey access control.
2599 ExprResult
2600 Sema::PerformObjectMemberConversion(Expr *From,
2601                                     NestedNameSpecifier *Qualifier,
2602                                     NamedDecl *FoundDecl,
2603                                     NamedDecl *Member) {
2604   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2605   if (!RD)
2606     return From;
2607
2608   QualType DestRecordType;
2609   QualType DestType;
2610   QualType FromRecordType;
2611   QualType FromType = From->getType();
2612   bool PointerConversions = false;
2613   if (isa<FieldDecl>(Member)) {
2614     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2615
2616     if (FromType->getAs<PointerType>()) {
2617       DestType = Context.getPointerType(DestRecordType);
2618       FromRecordType = FromType->getPointeeType();
2619       PointerConversions = true;
2620     } else {
2621       DestType = DestRecordType;
2622       FromRecordType = FromType;
2623     }
2624   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2625     if (Method->isStatic())
2626       return From;
2627
2628     DestType = Method->getThisType(Context);
2629     DestRecordType = DestType->getPointeeType();
2630
2631     if (FromType->getAs<PointerType>()) {
2632       FromRecordType = FromType->getPointeeType();
2633       PointerConversions = true;
2634     } else {
2635       FromRecordType = FromType;
2636       DestType = DestRecordType;
2637     }
2638   } else {
2639     // No conversion necessary.
2640     return From;
2641   }
2642
2643   if (DestType->isDependentType() || FromType->isDependentType())
2644     return From;
2645
2646   // If the unqualified types are the same, no conversion is necessary.
2647   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2648     return From;
2649
2650   SourceRange FromRange = From->getSourceRange();
2651   SourceLocation FromLoc = FromRange.getBegin();
2652
2653   ExprValueKind VK = From->getValueKind();
2654
2655   // C++ [class.member.lookup]p8:
2656   //   [...] Ambiguities can often be resolved by qualifying a name with its
2657   //   class name.
2658   //
2659   // If the member was a qualified name and the qualified referred to a
2660   // specific base subobject type, we'll cast to that intermediate type
2661   // first and then to the object in which the member is declared. That allows
2662   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2663   //
2664   //   class Base { public: int x; };
2665   //   class Derived1 : public Base { };
2666   //   class Derived2 : public Base { };
2667   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2668   //
2669   //   void VeryDerived::f() {
2670   //     x = 17; // error: ambiguous base subobjects
2671   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2672   //   }
2673   if (Qualifier && Qualifier->getAsType()) {
2674     QualType QType = QualType(Qualifier->getAsType(), 0);
2675     assert(QType->isRecordType() && "lookup done with non-record type");
2676
2677     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2678
2679     // In C++98, the qualifier type doesn't actually have to be a base
2680     // type of the object type, in which case we just ignore it.
2681     // Otherwise build the appropriate casts.
2682     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2683       CXXCastPath BasePath;
2684       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2685                                        FromLoc, FromRange, &BasePath))
2686         return ExprError();
2687
2688       if (PointerConversions)
2689         QType = Context.getPointerType(QType);
2690       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2691                                VK, &BasePath).get();
2692
2693       FromType = QType;
2694       FromRecordType = QRecordType;
2695
2696       // If the qualifier type was the same as the destination type,
2697       // we're done.
2698       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2699         return From;
2700     }
2701   }
2702
2703   bool IgnoreAccess = false;
2704
2705   // If we actually found the member through a using declaration, cast
2706   // down to the using declaration's type.
2707   //
2708   // Pointer equality is fine here because only one declaration of a
2709   // class ever has member declarations.
2710   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2711     assert(isa<UsingShadowDecl>(FoundDecl));
2712     QualType URecordType = Context.getTypeDeclType(
2713                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2714
2715     // We only need to do this if the naming-class to declaring-class
2716     // conversion is non-trivial.
2717     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2718       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2719       CXXCastPath BasePath;
2720       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2721                                        FromLoc, FromRange, &BasePath))
2722         return ExprError();
2723
2724       QualType UType = URecordType;
2725       if (PointerConversions)
2726         UType = Context.getPointerType(UType);
2727       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2728                                VK, &BasePath).get();
2729       FromType = UType;
2730       FromRecordType = URecordType;
2731     }
2732
2733     // We don't do access control for the conversion from the
2734     // declaring class to the true declaring class.
2735     IgnoreAccess = true;
2736   }
2737
2738   CXXCastPath BasePath;
2739   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2740                                    FromLoc, FromRange, &BasePath,
2741                                    IgnoreAccess))
2742     return ExprError();
2743
2744   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2745                            VK, &BasePath);
2746 }
2747
2748 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2749                                       const LookupResult &R,
2750                                       bool HasTrailingLParen) {
2751   // Only when used directly as the postfix-expression of a call.
2752   if (!HasTrailingLParen)
2753     return false;
2754
2755   // Never if a scope specifier was provided.
2756   if (SS.isSet())
2757     return false;
2758
2759   // Only in C++ or ObjC++.
2760   if (!getLangOpts().CPlusPlus)
2761     return false;
2762
2763   // Turn off ADL when we find certain kinds of declarations during
2764   // normal lookup:
2765   for (NamedDecl *D : R) {
2766     // C++0x [basic.lookup.argdep]p3:
2767     //     -- a declaration of a class member
2768     // Since using decls preserve this property, we check this on the
2769     // original decl.
2770     if (D->isCXXClassMember())
2771       return false;
2772
2773     // C++0x [basic.lookup.argdep]p3:
2774     //     -- a block-scope function declaration that is not a
2775     //        using-declaration
2776     // NOTE: we also trigger this for function templates (in fact, we
2777     // don't check the decl type at all, since all other decl types
2778     // turn off ADL anyway).
2779     if (isa<UsingShadowDecl>(D))
2780       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2781     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2782       return false;
2783
2784     // C++0x [basic.lookup.argdep]p3:
2785     //     -- a declaration that is neither a function or a function
2786     //        template
2787     // And also for builtin functions.
2788     if (isa<FunctionDecl>(D)) {
2789       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2790
2791       // But also builtin functions.
2792       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2793         return false;
2794     } else if (!isa<FunctionTemplateDecl>(D))
2795       return false;
2796   }
2797
2798   return true;
2799 }
2800
2801
2802 /// Diagnoses obvious problems with the use of the given declaration
2803 /// as an expression.  This is only actually called for lookups that
2804 /// were not overloaded, and it doesn't promise that the declaration
2805 /// will in fact be used.
2806 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2807   if (D->isInvalidDecl())
2808     return true;
2809
2810   if (isa<TypedefNameDecl>(D)) {
2811     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2812     return true;
2813   }
2814
2815   if (isa<ObjCInterfaceDecl>(D)) {
2816     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2817     return true;
2818   }
2819
2820   if (isa<NamespaceDecl>(D)) {
2821     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2822     return true;
2823   }
2824
2825   return false;
2826 }
2827
2828 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2829                                           LookupResult &R, bool NeedsADL,
2830                                           bool AcceptInvalidDecl) {
2831   // If this is a single, fully-resolved result and we don't need ADL,
2832   // just build an ordinary singleton decl ref.
2833   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2834     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2835                                     R.getRepresentativeDecl(), nullptr,
2836                                     AcceptInvalidDecl);
2837
2838   // We only need to check the declaration if there's exactly one
2839   // result, because in the overloaded case the results can only be
2840   // functions and function templates.
2841   if (R.isSingleResult() &&
2842       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2843     return ExprError();
2844
2845   // Otherwise, just build an unresolved lookup expression.  Suppress
2846   // any lookup-related diagnostics; we'll hash these out later, when
2847   // we've picked a target.
2848   R.suppressDiagnostics();
2849
2850   UnresolvedLookupExpr *ULE
2851     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2852                                    SS.getWithLocInContext(Context),
2853                                    R.getLookupNameInfo(),
2854                                    NeedsADL, R.isOverloadedResult(),
2855                                    R.begin(), R.end());
2856
2857   return ULE;
2858 }
2859
2860 static void
2861 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2862                                    ValueDecl *var, DeclContext *DC);
2863
2864 /// \brief Complete semantic analysis for a reference to the given declaration.
2865 ExprResult Sema::BuildDeclarationNameExpr(
2866     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2867     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2868     bool AcceptInvalidDecl) {
2869   assert(D && "Cannot refer to a NULL declaration");
2870   assert(!isa<FunctionTemplateDecl>(D) &&
2871          "Cannot refer unambiguously to a function template");
2872
2873   SourceLocation Loc = NameInfo.getLoc();
2874   if (CheckDeclInExpr(*this, Loc, D))
2875     return ExprError();
2876
2877   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2878     // Specifically diagnose references to class templates that are missing
2879     // a template argument list.
2880     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2881                                            << Template << SS.getRange();
2882     Diag(Template->getLocation(), diag::note_template_decl_here);
2883     return ExprError();
2884   }
2885
2886   // Make sure that we're referring to a value.
2887   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2888   if (!VD) {
2889     Diag(Loc, diag::err_ref_non_value)
2890       << D << SS.getRange();
2891     Diag(D->getLocation(), diag::note_declared_at);
2892     return ExprError();
2893   }
2894
2895   // Check whether this declaration can be used. Note that we suppress
2896   // this check when we're going to perform argument-dependent lookup
2897   // on this function name, because this might not be the function
2898   // that overload resolution actually selects.
2899   if (DiagnoseUseOfDecl(VD, Loc))
2900     return ExprError();
2901
2902   // Only create DeclRefExpr's for valid Decl's.
2903   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2904     return ExprError();
2905
2906   // Handle members of anonymous structs and unions.  If we got here,
2907   // and the reference is to a class member indirect field, then this
2908   // must be the subject of a pointer-to-member expression.
2909   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2910     if (!indirectField->isCXXClassMember())
2911       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2912                                                       indirectField);
2913
2914   {
2915     QualType type = VD->getType();
2916     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2917       // C++ [except.spec]p17:
2918       //   An exception-specification is considered to be needed when:
2919       //   - in an expression, the function is the unique lookup result or
2920       //     the selected member of a set of overloaded functions.
2921       ResolveExceptionSpec(Loc, FPT);
2922       type = VD->getType();
2923     }
2924     ExprValueKind valueKind = VK_RValue;
2925
2926     switch (D->getKind()) {
2927     // Ignore all the non-ValueDecl kinds.
2928 #define ABSTRACT_DECL(kind)
2929 #define VALUE(type, base)
2930 #define DECL(type, base) \
2931     case Decl::type:
2932 #include "clang/AST/DeclNodes.inc"
2933       llvm_unreachable("invalid value decl kind");
2934
2935     // These shouldn't make it here.
2936     case Decl::ObjCAtDefsField:
2937     case Decl::ObjCIvar:
2938       llvm_unreachable("forming non-member reference to ivar?");
2939
2940     // Enum constants are always r-values and never references.
2941     // Unresolved using declarations are dependent.
2942     case Decl::EnumConstant:
2943     case Decl::UnresolvedUsingValue:
2944     case Decl::OMPDeclareReduction:
2945       valueKind = VK_RValue;
2946       break;
2947
2948     // Fields and indirect fields that got here must be for
2949     // pointer-to-member expressions; we just call them l-values for
2950     // internal consistency, because this subexpression doesn't really
2951     // exist in the high-level semantics.
2952     case Decl::Field:
2953     case Decl::IndirectField:
2954       assert(getLangOpts().CPlusPlus &&
2955              "building reference to field in C?");
2956
2957       // These can't have reference type in well-formed programs, but
2958       // for internal consistency we do this anyway.
2959       type = type.getNonReferenceType();
2960       valueKind = VK_LValue;
2961       break;
2962
2963     // Non-type template parameters are either l-values or r-values
2964     // depending on the type.
2965     case Decl::NonTypeTemplateParm: {
2966       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2967         type = reftype->getPointeeType();
2968         valueKind = VK_LValue; // even if the parameter is an r-value reference
2969         break;
2970       }
2971
2972       // For non-references, we need to strip qualifiers just in case
2973       // the template parameter was declared as 'const int' or whatever.
2974       valueKind = VK_RValue;
2975       type = type.getUnqualifiedType();
2976       break;
2977     }
2978
2979     case Decl::Var:
2980     case Decl::VarTemplateSpecialization:
2981     case Decl::VarTemplatePartialSpecialization:
2982     case Decl::Decomposition:
2983     case Decl::OMPCapturedExpr:
2984       // In C, "extern void blah;" is valid and is an r-value.
2985       if (!getLangOpts().CPlusPlus &&
2986           !type.hasQualifiers() &&
2987           type->isVoidType()) {
2988         valueKind = VK_RValue;
2989         break;
2990       }
2991       // fallthrough
2992
2993     case Decl::ImplicitParam:
2994     case Decl::ParmVar: {
2995       // These are always l-values.
2996       valueKind = VK_LValue;
2997       type = type.getNonReferenceType();
2998
2999       // FIXME: Does the addition of const really only apply in
3000       // potentially-evaluated contexts? Since the variable isn't actually
3001       // captured in an unevaluated context, it seems that the answer is no.
3002       if (!isUnevaluatedContext()) {
3003         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3004         if (!CapturedType.isNull())
3005           type = CapturedType;
3006       }
3007       
3008       break;
3009     }
3010
3011     case Decl::Binding: {
3012       // These are always lvalues.
3013       valueKind = VK_LValue;
3014       type = type.getNonReferenceType();
3015       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3016       // decides how that's supposed to work.
3017       auto *BD = cast<BindingDecl>(VD);
3018       if (BD->getDeclContext()->isFunctionOrMethod() &&
3019           BD->getDeclContext() != CurContext)
3020         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3021       break;
3022     }
3023         
3024     case Decl::Function: {
3025       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3026         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3027           type = Context.BuiltinFnTy;
3028           valueKind = VK_RValue;
3029           break;
3030         }
3031       }
3032
3033       const FunctionType *fty = type->castAs<FunctionType>();
3034
3035       // If we're referring to a function with an __unknown_anytype
3036       // result type, make the entire expression __unknown_anytype.
3037       if (fty->getReturnType() == Context.UnknownAnyTy) {
3038         type = Context.UnknownAnyTy;
3039         valueKind = VK_RValue;
3040         break;
3041       }
3042
3043       // Functions are l-values in C++.
3044       if (getLangOpts().CPlusPlus) {
3045         valueKind = VK_LValue;
3046         break;
3047       }
3048       
3049       // C99 DR 316 says that, if a function type comes from a
3050       // function definition (without a prototype), that type is only
3051       // used for checking compatibility. Therefore, when referencing
3052       // the function, we pretend that we don't have the full function
3053       // type.
3054       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3055           isa<FunctionProtoType>(fty))
3056         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3057                                               fty->getExtInfo());
3058
3059       // Functions are r-values in C.
3060       valueKind = VK_RValue;
3061       break;
3062     }
3063
3064     case Decl::CXXDeductionGuide:
3065       llvm_unreachable("building reference to deduction guide");
3066
3067     case Decl::MSProperty:
3068       valueKind = VK_LValue;
3069       break;
3070
3071     case Decl::CXXMethod:
3072       // If we're referring to a method with an __unknown_anytype
3073       // result type, make the entire expression __unknown_anytype.
3074       // This should only be possible with a type written directly.
3075       if (const FunctionProtoType *proto
3076             = dyn_cast<FunctionProtoType>(VD->getType()))
3077         if (proto->getReturnType() == Context.UnknownAnyTy) {
3078           type = Context.UnknownAnyTy;
3079           valueKind = VK_RValue;
3080           break;
3081         }
3082
3083       // C++ methods are l-values if static, r-values if non-static.
3084       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3085         valueKind = VK_LValue;
3086         break;
3087       }
3088       // fallthrough
3089
3090     case Decl::CXXConversion:
3091     case Decl::CXXDestructor:
3092     case Decl::CXXConstructor:
3093       valueKind = VK_RValue;
3094       break;
3095     }
3096
3097     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3098                             TemplateArgs);
3099   }
3100 }
3101
3102 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3103                                     SmallString<32> &Target) {
3104   Target.resize(CharByteWidth * (Source.size() + 1));
3105   char *ResultPtr = &Target[0];
3106   const llvm::UTF8 *ErrorPtr;
3107   bool success =
3108       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3109   (void)success;
3110   assert(success);
3111   Target.resize(ResultPtr - &Target[0]);
3112 }
3113
3114 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3115                                      PredefinedExpr::IdentType IT) {
3116   // Pick the current block, lambda, captured statement or function.
3117   Decl *currentDecl = nullptr;
3118   if (const BlockScopeInfo *BSI = getCurBlock())
3119     currentDecl = BSI->TheDecl;
3120   else if (const LambdaScopeInfo *LSI = getCurLambda())
3121     currentDecl = LSI->CallOperator;
3122   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3123     currentDecl = CSI->TheCapturedDecl;
3124   else
3125     currentDecl = getCurFunctionOrMethodDecl();
3126
3127   if (!currentDecl) {
3128     Diag(Loc, diag::ext_predef_outside_function);
3129     currentDecl = Context.getTranslationUnitDecl();
3130   }
3131
3132   QualType ResTy;
3133   StringLiteral *SL = nullptr;
3134   if (cast<DeclContext>(currentDecl)->isDependentContext())
3135     ResTy = Context.DependentTy;
3136   else {
3137     // Pre-defined identifiers are of type char[x], where x is the length of
3138     // the string.
3139     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3140     unsigned Length = Str.length();
3141
3142     llvm::APInt LengthI(32, Length + 1);
3143     if (IT == PredefinedExpr::LFunction) {
3144       ResTy = Context.WideCharTy.withConst();
3145       SmallString<32> RawChars;
3146       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3147                               Str, RawChars);
3148       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3149                                            /*IndexTypeQuals*/ 0);
3150       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3151                                  /*Pascal*/ false, ResTy, Loc);
3152     } else {
3153       ResTy = Context.CharTy.withConst();
3154       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3155                                            /*IndexTypeQuals*/ 0);
3156       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3157                                  /*Pascal*/ false, ResTy, Loc);
3158     }
3159   }
3160
3161   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3162 }
3163
3164 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3165   PredefinedExpr::IdentType IT;
3166
3167   switch (Kind) {
3168   default: llvm_unreachable("Unknown simple primary expr!");
3169   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3170   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3171   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3172   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3173   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3174   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3175   }
3176
3177   return BuildPredefinedExpr(Loc, IT);
3178 }
3179
3180 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3181   SmallString<16> CharBuffer;
3182   bool Invalid = false;
3183   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3184   if (Invalid)
3185     return ExprError();
3186
3187   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3188                             PP, Tok.getKind());
3189   if (Literal.hadError())
3190     return ExprError();
3191
3192   QualType Ty;
3193   if (Literal.isWide())
3194     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3195   else if (Literal.isUTF16())
3196     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3197   else if (Literal.isUTF32())
3198     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3199   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3200     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3201   else
3202     Ty = Context.CharTy;  // 'x' -> char in C++
3203
3204   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3205   if (Literal.isWide())
3206     Kind = CharacterLiteral::Wide;
3207   else if (Literal.isUTF16())
3208     Kind = CharacterLiteral::UTF16;
3209   else if (Literal.isUTF32())
3210     Kind = CharacterLiteral::UTF32;
3211   else if (Literal.isUTF8())
3212     Kind = CharacterLiteral::UTF8;
3213
3214   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3215                                              Tok.getLocation());
3216
3217   if (Literal.getUDSuffix().empty())
3218     return Lit;
3219
3220   // We're building a user-defined literal.
3221   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3222   SourceLocation UDSuffixLoc =
3223     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3224
3225   // Make sure we're allowed user-defined literals here.
3226   if (!UDLScope)
3227     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3228
3229   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3230   //   operator "" X (ch)
3231   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3232                                         Lit, Tok.getLocation());
3233 }
3234
3235 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3236   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3237   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3238                                 Context.IntTy, Loc);
3239 }
3240
3241 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3242                                   QualType Ty, SourceLocation Loc) {
3243   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3244
3245   using llvm::APFloat;
3246   APFloat Val(Format);
3247
3248   APFloat::opStatus result = Literal.GetFloatValue(Val);
3249
3250   // Overflow is always an error, but underflow is only an error if
3251   // we underflowed to zero (APFloat reports denormals as underflow).
3252   if ((result & APFloat::opOverflow) ||
3253       ((result & APFloat::opUnderflow) && Val.isZero())) {
3254     unsigned diagnostic;
3255     SmallString<20> buffer;
3256     if (result & APFloat::opOverflow) {
3257       diagnostic = diag::warn_float_overflow;
3258       APFloat::getLargest(Format).toString(buffer);
3259     } else {
3260       diagnostic = diag::warn_float_underflow;
3261       APFloat::getSmallest(Format).toString(buffer);
3262     }
3263
3264     S.Diag(Loc, diagnostic)
3265       << Ty
3266       << StringRef(buffer.data(), buffer.size());
3267   }
3268
3269   bool isExact = (result == APFloat::opOK);
3270   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3271 }
3272
3273 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3274   assert(E && "Invalid expression");
3275
3276   if (E->isValueDependent())
3277     return false;
3278
3279   QualType QT = E->getType();
3280   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3281     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3282     return true;
3283   }
3284
3285   llvm::APSInt ValueAPS;
3286   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3287
3288   if (R.isInvalid())
3289     return true;
3290
3291   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3292   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3293     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3294         << ValueAPS.toString(10) << ValueIsPositive;
3295     return true;
3296   }
3297
3298   return false;
3299 }
3300
3301 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3302   // Fast path for a single digit (which is quite common).  A single digit
3303   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3304   if (Tok.getLength() == 1) {
3305     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3306     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3307   }
3308
3309   SmallString<128> SpellingBuffer;
3310   // NumericLiteralParser wants to overread by one character.  Add padding to
3311   // the buffer in case the token is copied to the buffer.  If getSpelling()
3312   // returns a StringRef to the memory buffer, it should have a null char at
3313   // the EOF, so it is also safe.
3314   SpellingBuffer.resize(Tok.getLength() + 1);
3315
3316   // Get the spelling of the token, which eliminates trigraphs, etc.
3317   bool Invalid = false;
3318   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3319   if (Invalid)
3320     return ExprError();
3321
3322   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3323   if (Literal.hadError)
3324     return ExprError();
3325
3326   if (Literal.hasUDSuffix()) {
3327     // We're building a user-defined literal.
3328     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3329     SourceLocation UDSuffixLoc =
3330       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3331
3332     // Make sure we're allowed user-defined literals here.
3333     if (!UDLScope)
3334       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3335
3336     QualType CookedTy;
3337     if (Literal.isFloatingLiteral()) {
3338       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3339       // long double, the literal is treated as a call of the form
3340       //   operator "" X (f L)
3341       CookedTy = Context.LongDoubleTy;
3342     } else {
3343       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3344       // unsigned long long, the literal is treated as a call of the form
3345       //   operator "" X (n ULL)
3346       CookedTy = Context.UnsignedLongLongTy;
3347     }
3348
3349     DeclarationName OpName =
3350       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3351     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3352     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3353
3354     SourceLocation TokLoc = Tok.getLocation();
3355
3356     // Perform literal operator lookup to determine if we're building a raw
3357     // literal or a cooked one.
3358     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3359     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3360                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3361                                   /*AllowStringTemplate*/false)) {
3362     case LOLR_Error:
3363       return ExprError();
3364
3365     case LOLR_Cooked: {
3366       Expr *Lit;
3367       if (Literal.isFloatingLiteral()) {
3368         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3369       } else {
3370         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3371         if (Literal.GetIntegerValue(ResultVal))
3372           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3373               << /* Unsigned */ 1;
3374         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3375                                      Tok.getLocation());
3376       }
3377       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3378     }
3379
3380     case LOLR_Raw: {
3381       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3382       // literal is treated as a call of the form
3383       //   operator "" X ("n")
3384       unsigned Length = Literal.getUDSuffixOffset();
3385       QualType StrTy = Context.getConstantArrayType(
3386           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3387           ArrayType::Normal, 0);
3388       Expr *Lit = StringLiteral::Create(
3389           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3390           /*Pascal*/false, StrTy, &TokLoc, 1);
3391       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3392     }
3393
3394     case LOLR_Template: {
3395       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3396       // template), L is treated as a call fo the form
3397       //   operator "" X <'c1', 'c2', ... 'ck'>()
3398       // where n is the source character sequence c1 c2 ... ck.
3399       TemplateArgumentListInfo ExplicitArgs;
3400       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3401       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3402       llvm::APSInt Value(CharBits, CharIsUnsigned);
3403       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3404         Value = TokSpelling[I];
3405         TemplateArgument Arg(Context, Value, Context.CharTy);
3406         TemplateArgumentLocInfo ArgInfo;
3407         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3408       }
3409       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3410                                       &ExplicitArgs);
3411     }
3412     case LOLR_StringTemplate:
3413       llvm_unreachable("unexpected literal operator lookup result");
3414     }
3415   }
3416
3417   Expr *Res;
3418
3419   if (Literal.isFloatingLiteral()) {
3420     QualType Ty;
3421     if (Literal.isHalf){
3422       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3423         Ty = Context.HalfTy;
3424       else {
3425         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3426         return ExprError();
3427       }
3428     } else if (Literal.isFloat)
3429       Ty = Context.FloatTy;
3430     else if (Literal.isLong)
3431       Ty = Context.LongDoubleTy;
3432     else if (Literal.isFloat128)
3433       Ty = Context.Float128Ty;
3434     else
3435       Ty = Context.DoubleTy;
3436
3437     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3438
3439     if (Ty == Context.DoubleTy) {
3440       if (getLangOpts().SinglePrecisionConstants) {
3441         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3442         if (BTy->getKind() != BuiltinType::Float) {
3443           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3444         }
3445       } else if (getLangOpts().OpenCL &&
3446                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3447         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3448         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3449         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3450       }
3451     }
3452   } else if (!Literal.isIntegerLiteral()) {
3453     return ExprError();
3454   } else {
3455     QualType Ty;
3456
3457     // 'long long' is a C99 or C++11 feature.
3458     if (!getLangOpts().C99 && Literal.isLongLong) {
3459       if (getLangOpts().CPlusPlus)
3460         Diag(Tok.getLocation(),
3461              getLangOpts().CPlusPlus11 ?
3462              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3463       else
3464         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3465     }
3466
3467     // Get the value in the widest-possible width.
3468     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3469     llvm::APInt ResultVal(MaxWidth, 0);
3470
3471     if (Literal.GetIntegerValue(ResultVal)) {
3472       // If this value didn't fit into uintmax_t, error and force to ull.
3473       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3474           << /* Unsigned */ 1;
3475       Ty = Context.UnsignedLongLongTy;
3476       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3477              "long long is not intmax_t?");
3478     } else {
3479       // If this value fits into a ULL, try to figure out what else it fits into
3480       // according to the rules of C99 6.4.4.1p5.
3481
3482       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3483       // be an unsigned int.
3484       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3485
3486       // Check from smallest to largest, picking the smallest type we can.
3487       unsigned Width = 0;
3488
3489       // Microsoft specific integer suffixes are explicitly sized.
3490       if (Literal.MicrosoftInteger) {
3491         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3492           Width = 8;
3493           Ty = Context.CharTy;
3494         } else {
3495           Width = Literal.MicrosoftInteger;
3496           Ty = Context.getIntTypeForBitwidth(Width,
3497                                              /*Signed=*/!Literal.isUnsigned);
3498         }
3499       }
3500
3501       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3502         // Are int/unsigned possibilities?
3503         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3504
3505         // Does it fit in a unsigned int?
3506         if (ResultVal.isIntN(IntSize)) {
3507           // Does it fit in a signed int?
3508           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3509             Ty = Context.IntTy;
3510           else if (AllowUnsigned)
3511             Ty = Context.UnsignedIntTy;
3512           Width = IntSize;
3513         }
3514       }
3515
3516       // Are long/unsigned long possibilities?
3517       if (Ty.isNull() && !Literal.isLongLong) {
3518         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3519
3520         // Does it fit in a unsigned long?
3521         if (ResultVal.isIntN(LongSize)) {
3522           // Does it fit in a signed long?
3523           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3524             Ty = Context.LongTy;
3525           else if (AllowUnsigned)
3526             Ty = Context.UnsignedLongTy;
3527           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3528           // is compatible.
3529           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3530             const unsigned LongLongSize =
3531                 Context.getTargetInfo().getLongLongWidth();
3532             Diag(Tok.getLocation(),
3533                  getLangOpts().CPlusPlus
3534                      ? Literal.isLong
3535                            ? diag::warn_old_implicitly_unsigned_long_cxx
3536                            : /*C++98 UB*/ diag::
3537                                  ext_old_implicitly_unsigned_long_cxx
3538                      : diag::warn_old_implicitly_unsigned_long)
3539                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3540                                             : /*will be ill-formed*/ 1);
3541             Ty = Context.UnsignedLongTy;
3542           }
3543           Width = LongSize;
3544         }
3545       }
3546
3547       // Check long long if needed.
3548       if (Ty.isNull()) {
3549         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3550
3551         // Does it fit in a unsigned long long?
3552         if (ResultVal.isIntN(LongLongSize)) {
3553           // Does it fit in a signed long long?
3554           // To be compatible with MSVC, hex integer literals ending with the
3555           // LL or i64 suffix are always signed in Microsoft mode.
3556           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3557               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3558             Ty = Context.LongLongTy;
3559           else if (AllowUnsigned)
3560             Ty = Context.UnsignedLongLongTy;
3561           Width = LongLongSize;
3562         }
3563       }
3564
3565       // If we still couldn't decide a type, we probably have something that
3566       // does not fit in a signed long long, but has no U suffix.
3567       if (Ty.isNull()) {
3568         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3569         Ty = Context.UnsignedLongLongTy;
3570         Width = Context.getTargetInfo().getLongLongWidth();
3571       }
3572
3573       if (ResultVal.getBitWidth() != Width)
3574         ResultVal = ResultVal.trunc(Width);
3575     }
3576     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3577   }
3578
3579   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3580   if (Literal.isImaginary)
3581     Res = new (Context) ImaginaryLiteral(Res,
3582                                         Context.getComplexType(Res->getType()));
3583
3584   return Res;
3585 }
3586
3587 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3588   assert(E && "ActOnParenExpr() missing expr");
3589   return new (Context) ParenExpr(L, R, E);
3590 }
3591
3592 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3593                                          SourceLocation Loc,
3594                                          SourceRange ArgRange) {
3595   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3596   // scalar or vector data type argument..."
3597   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3598   // type (C99 6.2.5p18) or void.
3599   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3600     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3601       << T << ArgRange;
3602     return true;
3603   }
3604
3605   assert((T->isVoidType() || !T->isIncompleteType()) &&
3606          "Scalar types should always be complete");
3607   return false;
3608 }
3609
3610 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3611                                            SourceLocation Loc,
3612                                            SourceRange ArgRange,
3613                                            UnaryExprOrTypeTrait TraitKind) {
3614   // Invalid types must be hard errors for SFINAE in C++.
3615   if (S.LangOpts.CPlusPlus)
3616     return true;
3617
3618   // C99 6.5.3.4p1:
3619   if (T->isFunctionType() &&
3620       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3621     // sizeof(function)/alignof(function) is allowed as an extension.
3622     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3623       << TraitKind << ArgRange;
3624     return false;
3625   }
3626
3627   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3628   // this is an error (OpenCL v1.1 s6.3.k)
3629   if (T->isVoidType()) {
3630     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3631                                         : diag::ext_sizeof_alignof_void_type;
3632     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3633     return false;
3634   }
3635
3636   return true;
3637 }
3638
3639 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3640                                              SourceLocation Loc,
3641                                              SourceRange ArgRange,
3642                                              UnaryExprOrTypeTrait TraitKind) {
3643   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3644   // runtime doesn't allow it.
3645   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3646     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3647       << T << (TraitKind == UETT_SizeOf)
3648       << ArgRange;
3649     return true;
3650   }
3651
3652   return false;
3653 }
3654
3655 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3656 /// pointer type is equal to T) and emit a warning if it is.
3657 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3658                                      Expr *E) {
3659   // Don't warn if the operation changed the type.
3660   if (T != E->getType())
3661     return;
3662
3663   // Now look for array decays.
3664   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3665   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3666     return;
3667
3668   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3669                                              << ICE->getType()
3670                                              << ICE->getSubExpr()->getType();
3671 }
3672
3673 /// \brief Check the constraints on expression operands to unary type expression
3674 /// and type traits.
3675 ///
3676 /// Completes any types necessary and validates the constraints on the operand
3677 /// expression. The logic mostly mirrors the type-based overload, but may modify
3678 /// the expression as it completes the type for that expression through template
3679 /// instantiation, etc.
3680 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3681                                             UnaryExprOrTypeTrait ExprKind) {
3682   QualType ExprTy = E->getType();
3683   assert(!ExprTy->isReferenceType());
3684
3685   if (ExprKind == UETT_VecStep)
3686     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3687                                         E->getSourceRange());
3688
3689   // Whitelist some types as extensions
3690   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3691                                       E->getSourceRange(), ExprKind))
3692     return false;
3693
3694   // 'alignof' applied to an expression only requires the base element type of
3695   // the expression to be complete. 'sizeof' requires the expression's type to
3696   // be complete (and will attempt to complete it if it's an array of unknown
3697   // bound).
3698   if (ExprKind == UETT_AlignOf) {
3699     if (RequireCompleteType(E->getExprLoc(),
3700                             Context.getBaseElementType(E->getType()),
3701                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3702                             E->getSourceRange()))
3703       return true;
3704   } else {
3705     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3706                                 ExprKind, E->getSourceRange()))
3707       return true;
3708   }
3709
3710   // Completing the expression's type may have changed it.
3711   ExprTy = E->getType();
3712   assert(!ExprTy->isReferenceType());
3713
3714   if (ExprTy->isFunctionType()) {
3715     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3716       << ExprKind << E->getSourceRange();
3717     return true;
3718   }
3719
3720   // The operand for sizeof and alignof is in an unevaluated expression context,
3721   // so side effects could result in unintended consequences.
3722   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3723       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3724     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3725
3726   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3727                                        E->getSourceRange(), ExprKind))
3728     return true;
3729
3730   if (ExprKind == UETT_SizeOf) {
3731     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3732       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3733         QualType OType = PVD->getOriginalType();
3734         QualType Type = PVD->getType();
3735         if (Type->isPointerType() && OType->isArrayType()) {
3736           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3737             << Type << OType;
3738           Diag(PVD->getLocation(), diag::note_declared_at);
3739         }
3740       }
3741     }
3742
3743     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3744     // decays into a pointer and returns an unintended result. This is most
3745     // likely a typo for "sizeof(array) op x".
3746     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3747       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3748                                BO->getLHS());
3749       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3750                                BO->getRHS());
3751     }
3752   }
3753
3754   return false;
3755 }
3756
3757 /// \brief Check the constraints on operands to unary expression and type
3758 /// traits.
3759 ///
3760 /// This will complete any types necessary, and validate the various constraints
3761 /// on those operands.
3762 ///
3763 /// The UsualUnaryConversions() function is *not* called by this routine.
3764 /// C99 6.3.2.1p[2-4] all state:
3765 ///   Except when it is the operand of the sizeof operator ...
3766 ///
3767 /// C++ [expr.sizeof]p4
3768 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3769 ///   standard conversions are not applied to the operand of sizeof.
3770 ///
3771 /// This policy is followed for all of the unary trait expressions.
3772 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3773                                             SourceLocation OpLoc,
3774                                             SourceRange ExprRange,
3775                                             UnaryExprOrTypeTrait ExprKind) {
3776   if (ExprType->isDependentType())
3777     return false;
3778
3779   // C++ [expr.sizeof]p2:
3780   //     When applied to a reference or a reference type, the result
3781   //     is the size of the referenced type.
3782   // C++11 [expr.alignof]p3:
3783   //     When alignof is applied to a reference type, the result
3784   //     shall be the alignment of the referenced type.
3785   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3786     ExprType = Ref->getPointeeType();
3787
3788   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3789   //   When alignof or _Alignof is applied to an array type, the result
3790   //   is the alignment of the element type.
3791   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3792     ExprType = Context.getBaseElementType(ExprType);
3793
3794   if (ExprKind == UETT_VecStep)
3795     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3796
3797   // Whitelist some types as extensions
3798   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3799                                       ExprKind))
3800     return false;
3801
3802   if (RequireCompleteType(OpLoc, ExprType,
3803                           diag::err_sizeof_alignof_incomplete_type,
3804                           ExprKind, ExprRange))
3805     return true;
3806
3807   if (ExprType->isFunctionType()) {
3808     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3809       << ExprKind << ExprRange;
3810     return true;
3811   }
3812
3813   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3814                                        ExprKind))
3815     return true;
3816
3817   return false;
3818 }
3819
3820 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3821   E = E->IgnoreParens();
3822
3823   // Cannot know anything else if the expression is dependent.
3824   if (E->isTypeDependent())
3825     return false;
3826
3827   if (E->getObjectKind() == OK_BitField) {
3828     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3829        << 1 << E->getSourceRange();
3830     return true;
3831   }
3832
3833   ValueDecl *D = nullptr;
3834   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3835     D = DRE->getDecl();
3836   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3837     D = ME->getMemberDecl();
3838   }
3839
3840   // If it's a field, require the containing struct to have a
3841   // complete definition so that we can compute the layout.
3842   //
3843   // This can happen in C++11 onwards, either by naming the member
3844   // in a way that is not transformed into a member access expression
3845   // (in an unevaluated operand, for instance), or by naming the member
3846   // in a trailing-return-type.
3847   //
3848   // For the record, since __alignof__ on expressions is a GCC
3849   // extension, GCC seems to permit this but always gives the
3850   // nonsensical answer 0.
3851   //
3852   // We don't really need the layout here --- we could instead just
3853   // directly check for all the appropriate alignment-lowing
3854   // attributes --- but that would require duplicating a lot of
3855   // logic that just isn't worth duplicating for such a marginal
3856   // use-case.
3857   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3858     // Fast path this check, since we at least know the record has a
3859     // definition if we can find a member of it.
3860     if (!FD->getParent()->isCompleteDefinition()) {
3861       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3862         << E->getSourceRange();
3863       return true;
3864     }
3865
3866     // Otherwise, if it's a field, and the field doesn't have
3867     // reference type, then it must have a complete type (or be a
3868     // flexible array member, which we explicitly want to
3869     // white-list anyway), which makes the following checks trivial.
3870     if (!FD->getType()->isReferenceType())
3871       return false;
3872   }
3873
3874   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3875 }
3876
3877 bool Sema::CheckVecStepExpr(Expr *E) {
3878   E = E->IgnoreParens();
3879
3880   // Cannot know anything else if the expression is dependent.
3881   if (E->isTypeDependent())
3882     return false;
3883
3884   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3885 }
3886
3887 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3888                                         CapturingScopeInfo *CSI) {
3889   assert(T->isVariablyModifiedType());
3890   assert(CSI != nullptr);
3891
3892   // We're going to walk down into the type and look for VLA expressions.
3893   do {
3894     const Type *Ty = T.getTypePtr();
3895     switch (Ty->getTypeClass()) {
3896 #define TYPE(Class, Base)
3897 #define ABSTRACT_TYPE(Class, Base)
3898 #define NON_CANONICAL_TYPE(Class, Base)
3899 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3900 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3901 #include "clang/AST/TypeNodes.def"
3902       T = QualType();
3903       break;
3904     // These types are never variably-modified.
3905     case Type::Builtin:
3906     case Type::Complex:
3907     case Type::Vector:
3908     case Type::ExtVector:
3909     case Type::Record:
3910     case Type::Enum:
3911     case Type::Elaborated:
3912     case Type::TemplateSpecialization:
3913     case Type::ObjCObject:
3914     case Type::ObjCInterface:
3915     case Type::ObjCObjectPointer:
3916     case Type::ObjCTypeParam:
3917     case Type::Pipe:
3918       llvm_unreachable("type class is never variably-modified!");
3919     case Type::Adjusted:
3920       T = cast<AdjustedType>(Ty)->getOriginalType();
3921       break;
3922     case Type::Decayed:
3923       T = cast<DecayedType>(Ty)->getPointeeType();
3924       break;
3925     case Type::Pointer:
3926       T = cast<PointerType>(Ty)->getPointeeType();
3927       break;
3928     case Type::BlockPointer:
3929       T = cast<BlockPointerType>(Ty)->getPointeeType();
3930       break;
3931     case Type::LValueReference:
3932     case Type::RValueReference:
3933       T = cast<ReferenceType>(Ty)->getPointeeType();
3934       break;
3935     case Type::MemberPointer:
3936       T = cast<MemberPointerType>(Ty)->getPointeeType();
3937       break;
3938     case Type::ConstantArray:
3939     case Type::IncompleteArray:
3940       // Losing element qualification here is fine.
3941       T = cast<ArrayType>(Ty)->getElementType();
3942       break;
3943     case Type::VariableArray: {
3944       // Losing element qualification here is fine.
3945       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3946
3947       // Unknown size indication requires no size computation.
3948       // Otherwise, evaluate and record it.
3949       if (auto Size = VAT->getSizeExpr()) {
3950         if (!CSI->isVLATypeCaptured(VAT)) {
3951           RecordDecl *CapRecord = nullptr;
3952           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3953             CapRecord = LSI->Lambda;
3954           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3955             CapRecord = CRSI->TheRecordDecl;
3956           }
3957           if (CapRecord) {
3958             auto ExprLoc = Size->getExprLoc();
3959             auto SizeType = Context.getSizeType();
3960             // Build the non-static data member.
3961             auto Field =
3962                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3963                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3964                                   /*BW*/ nullptr, /*Mutable*/ false,
3965                                   /*InitStyle*/ ICIS_NoInit);
3966             Field->setImplicit(true);
3967             Field->setAccess(AS_private);
3968             Field->setCapturedVLAType(VAT);
3969             CapRecord->addDecl(Field);
3970
3971             CSI->addVLATypeCapture(ExprLoc, SizeType);
3972           }
3973         }
3974       }
3975       T = VAT->getElementType();
3976       break;
3977     }
3978     case Type::FunctionProto:
3979     case Type::FunctionNoProto:
3980       T = cast<FunctionType>(Ty)->getReturnType();
3981       break;
3982     case Type::Paren:
3983     case Type::TypeOf:
3984     case Type::UnaryTransform:
3985     case Type::Attributed:
3986     case Type::SubstTemplateTypeParm:
3987     case Type::PackExpansion:
3988       // Keep walking after single level desugaring.
3989       T = T.getSingleStepDesugaredType(Context);
3990       break;
3991     case Type::Typedef:
3992       T = cast<TypedefType>(Ty)->desugar();
3993       break;
3994     case Type::Decltype:
3995       T = cast<DecltypeType>(Ty)->desugar();
3996       break;
3997     case Type::Auto:
3998     case Type::DeducedTemplateSpecialization:
3999       T = cast<DeducedType>(Ty)->getDeducedType();
4000       break;
4001     case Type::TypeOfExpr:
4002       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4003       break;
4004     case Type::Atomic:
4005       T = cast<AtomicType>(Ty)->getValueType();
4006       break;
4007     }
4008   } while (!T.isNull() && T->isVariablyModifiedType());
4009 }
4010
4011 /// \brief Build a sizeof or alignof expression given a type operand.
4012 ExprResult
4013 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4014                                      SourceLocation OpLoc,
4015                                      UnaryExprOrTypeTrait ExprKind,
4016                                      SourceRange R) {
4017   if (!TInfo)
4018     return ExprError();
4019
4020   QualType T = TInfo->getType();
4021
4022   if (!T->isDependentType() &&
4023       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4024     return ExprError();
4025
4026   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4027     if (auto *TT = T->getAs<TypedefType>()) {
4028       for (auto I = FunctionScopes.rbegin(),
4029                 E = std::prev(FunctionScopes.rend());
4030            I != E; ++I) {
4031         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4032         if (CSI == nullptr)
4033           break;
4034         DeclContext *DC = nullptr;
4035         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4036           DC = LSI->CallOperator;
4037         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4038           DC = CRSI->TheCapturedDecl;
4039         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4040           DC = BSI->TheDecl;
4041         if (DC) {
4042           if (DC->containsDecl(TT->getDecl()))
4043             break;
4044           captureVariablyModifiedType(Context, T, CSI);
4045         }
4046       }
4047     }
4048   }
4049
4050   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4051   return new (Context) UnaryExprOrTypeTraitExpr(
4052       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4053 }
4054
4055 /// \brief Build a sizeof or alignof expression given an expression
4056 /// operand.
4057 ExprResult
4058 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4059                                      UnaryExprOrTypeTrait ExprKind) {
4060   ExprResult PE = CheckPlaceholderExpr(E);
4061   if (PE.isInvalid()) 
4062     return ExprError();
4063
4064   E = PE.get();
4065   
4066   // Verify that the operand is valid.
4067   bool isInvalid = false;
4068   if (E->isTypeDependent()) {
4069     // Delay type-checking for type-dependent expressions.
4070   } else if (ExprKind == UETT_AlignOf) {
4071     isInvalid = CheckAlignOfExpr(*this, E);
4072   } else if (ExprKind == UETT_VecStep) {
4073     isInvalid = CheckVecStepExpr(E);
4074   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4075       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4076       isInvalid = true;
4077   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4078     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4079     isInvalid = true;
4080   } else {
4081     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4082   }
4083
4084   if (isInvalid)
4085     return ExprError();
4086
4087   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4088     PE = TransformToPotentiallyEvaluated(E);
4089     if (PE.isInvalid()) return ExprError();
4090     E = PE.get();
4091   }
4092
4093   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4094   return new (Context) UnaryExprOrTypeTraitExpr(
4095       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4096 }
4097
4098 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4099 /// expr and the same for @c alignof and @c __alignof
4100 /// Note that the ArgRange is invalid if isType is false.
4101 ExprResult
4102 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4103                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4104                                     void *TyOrEx, SourceRange ArgRange) {
4105   // If error parsing type, ignore.
4106   if (!TyOrEx) return ExprError();
4107
4108   if (IsType) {
4109     TypeSourceInfo *TInfo;
4110     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4111     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4112   }
4113
4114   Expr *ArgEx = (Expr *)TyOrEx;
4115   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4116   return Result;
4117 }
4118
4119 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4120                                      bool IsReal) {
4121   if (V.get()->isTypeDependent())
4122     return S.Context.DependentTy;
4123
4124   // _Real and _Imag are only l-values for normal l-values.
4125   if (V.get()->getObjectKind() != OK_Ordinary) {
4126     V = S.DefaultLvalueConversion(V.get());
4127     if (V.isInvalid())
4128       return QualType();
4129   }
4130
4131   // These operators return the element type of a complex type.
4132   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4133     return CT->getElementType();
4134
4135   // Otherwise they pass through real integer and floating point types here.
4136   if (V.get()->getType()->isArithmeticType())
4137     return V.get()->getType();
4138
4139   // Test for placeholders.
4140   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4141   if (PR.isInvalid()) return QualType();
4142   if (PR.get() != V.get()) {
4143     V = PR;
4144     return CheckRealImagOperand(S, V, Loc, IsReal);
4145   }
4146
4147   // Reject anything else.
4148   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4149     << (IsReal ? "__real" : "__imag");
4150   return QualType();
4151 }
4152
4153
4154
4155 ExprResult
4156 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4157                           tok::TokenKind Kind, Expr *Input) {
4158   UnaryOperatorKind Opc;
4159   switch (Kind) {
4160   default: llvm_unreachable("Unknown unary op!");
4161   case tok::plusplus:   Opc = UO_PostInc; break;
4162   case tok::minusminus: Opc = UO_PostDec; break;
4163   }
4164
4165   // Since this might is a postfix expression, get rid of ParenListExprs.
4166   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4167   if (Result.isInvalid()) return ExprError();
4168   Input = Result.get();
4169
4170   return BuildUnaryOp(S, OpLoc, Opc, Input);
4171 }
4172
4173 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4174 ///
4175 /// \return true on error
4176 static bool checkArithmeticOnObjCPointer(Sema &S,
4177                                          SourceLocation opLoc,
4178                                          Expr *op) {
4179   assert(op->getType()->isObjCObjectPointerType());
4180   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4181       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4182     return false;
4183
4184   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4185     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4186     << op->getSourceRange();
4187   return true;
4188 }
4189
4190 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4191   auto *BaseNoParens = Base->IgnoreParens();
4192   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4193     return MSProp->getPropertyDecl()->getType()->isArrayType();
4194   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4195 }
4196
4197 ExprResult
4198 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4199                               Expr *idx, SourceLocation rbLoc) {
4200   if (base && !base->getType().isNull() &&
4201       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4202     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4203                                     /*Length=*/nullptr, rbLoc);
4204
4205   // Since this might be a postfix expression, get rid of ParenListExprs.
4206   if (isa<ParenListExpr>(base)) {
4207     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4208     if (result.isInvalid()) return ExprError();
4209     base = result.get();
4210   }
4211
4212   // Handle any non-overload placeholder types in the base and index
4213   // expressions.  We can't handle overloads here because the other
4214   // operand might be an overloadable type, in which case the overload
4215   // resolution for the operator overload should get the first crack
4216   // at the overload.
4217   bool IsMSPropertySubscript = false;
4218   if (base->getType()->isNonOverloadPlaceholderType()) {
4219     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4220     if (!IsMSPropertySubscript) {
4221       ExprResult result = CheckPlaceholderExpr(base);
4222       if (result.isInvalid())
4223         return ExprError();
4224       base = result.get();
4225     }
4226   }
4227   if (idx->getType()->isNonOverloadPlaceholderType()) {
4228     ExprResult result = CheckPlaceholderExpr(idx);
4229     if (result.isInvalid()) return ExprError();
4230     idx = result.get();
4231   }
4232
4233   // Build an unanalyzed expression if either operand is type-dependent.
4234   if (getLangOpts().CPlusPlus &&
4235       (base->isTypeDependent() || idx->isTypeDependent())) {
4236     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4237                                             VK_LValue, OK_Ordinary, rbLoc);
4238   }
4239
4240   // MSDN, property (C++)
4241   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4242   // This attribute can also be used in the declaration of an empty array in a
4243   // class or structure definition. For example:
4244   // __declspec(property(get=GetX, put=PutX)) int x[];
4245   // The above statement indicates that x[] can be used with one or more array
4246   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4247   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4248   if (IsMSPropertySubscript) {
4249     // Build MS property subscript expression if base is MS property reference
4250     // or MS property subscript.
4251     return new (Context) MSPropertySubscriptExpr(
4252         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4253   }
4254
4255   // Use C++ overloaded-operator rules if either operand has record
4256   // type.  The spec says to do this if either type is *overloadable*,
4257   // but enum types can't declare subscript operators or conversion
4258   // operators, so there's nothing interesting for overload resolution
4259   // to do if there aren't any record types involved.
4260   //
4261   // ObjC pointers have their own subscripting logic that is not tied
4262   // to overload resolution and so should not take this path.
4263   if (getLangOpts().CPlusPlus &&
4264       (base->getType()->isRecordType() ||
4265        (!base->getType()->isObjCObjectPointerType() &&
4266         idx->getType()->isRecordType()))) {
4267     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4268   }
4269
4270   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4271 }
4272
4273 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4274                                           Expr *LowerBound,
4275                                           SourceLocation ColonLoc, Expr *Length,
4276                                           SourceLocation RBLoc) {
4277   if (Base->getType()->isPlaceholderType() &&
4278       !Base->getType()->isSpecificPlaceholderType(
4279           BuiltinType::OMPArraySection)) {
4280     ExprResult Result = CheckPlaceholderExpr(Base);
4281     if (Result.isInvalid())
4282       return ExprError();
4283     Base = Result.get();
4284   }
4285   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4286     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4287     if (Result.isInvalid())
4288       return ExprError();
4289     Result = DefaultLvalueConversion(Result.get());
4290     if (Result.isInvalid())
4291       return ExprError();
4292     LowerBound = Result.get();
4293   }
4294   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4295     ExprResult Result = CheckPlaceholderExpr(Length);
4296     if (Result.isInvalid())
4297       return ExprError();
4298     Result = DefaultLvalueConversion(Result.get());
4299     if (Result.isInvalid())
4300       return ExprError();
4301     Length = Result.get();
4302   }
4303
4304   // Build an unanalyzed expression if either operand is type-dependent.
4305   if (Base->isTypeDependent() ||
4306       (LowerBound &&
4307        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4308       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4309     return new (Context)
4310         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4311                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4312   }
4313
4314   // Perform default conversions.
4315   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4316   QualType ResultTy;
4317   if (OriginalTy->isAnyPointerType()) {
4318     ResultTy = OriginalTy->getPointeeType();
4319   } else if (OriginalTy->isArrayType()) {
4320     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4321   } else {
4322     return ExprError(
4323         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4324         << Base->getSourceRange());
4325   }
4326   // C99 6.5.2.1p1
4327   if (LowerBound) {
4328     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4329                                                       LowerBound);
4330     if (Res.isInvalid())
4331       return ExprError(Diag(LowerBound->getExprLoc(),
4332                             diag::err_omp_typecheck_section_not_integer)
4333                        << 0 << LowerBound->getSourceRange());
4334     LowerBound = Res.get();
4335
4336     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4337         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4338       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4339           << 0 << LowerBound->getSourceRange();
4340   }
4341   if (Length) {
4342     auto Res =
4343         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4344     if (Res.isInvalid())
4345       return ExprError(Diag(Length->getExprLoc(),
4346                             diag::err_omp_typecheck_section_not_integer)
4347                        << 1 << Length->getSourceRange());
4348     Length = Res.get();
4349
4350     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4351         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4352       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4353           << 1 << Length->getSourceRange();
4354   }
4355
4356   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4357   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4358   // type. Note that functions are not objects, and that (in C99 parlance)
4359   // incomplete types are not object types.
4360   if (ResultTy->isFunctionType()) {
4361     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4362         << ResultTy << Base->getSourceRange();
4363     return ExprError();
4364   }
4365
4366   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4367                           diag::err_omp_section_incomplete_type, Base))
4368     return ExprError();
4369
4370   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4371     llvm::APSInt LowerBoundValue;
4372     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4373       // OpenMP 4.5, [2.4 Array Sections]
4374       // The array section must be a subset of the original array.
4375       if (LowerBoundValue.isNegative()) {
4376         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4377             << LowerBound->getSourceRange();
4378         return ExprError();
4379       }
4380     }
4381   }
4382
4383   if (Length) {
4384     llvm::APSInt LengthValue;
4385     if (Length->EvaluateAsInt(LengthValue, Context)) {
4386       // OpenMP 4.5, [2.4 Array Sections]
4387       // The length must evaluate to non-negative integers.
4388       if (LengthValue.isNegative()) {
4389         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4390             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4391             << Length->getSourceRange();
4392         return ExprError();
4393       }
4394     }
4395   } else if (ColonLoc.isValid() &&
4396              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4397                                       !OriginalTy->isVariableArrayType()))) {
4398     // OpenMP 4.5, [2.4 Array Sections]
4399     // When the size of the array dimension is not known, the length must be
4400     // specified explicitly.
4401     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4402         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4403     return ExprError();
4404   }
4405
4406   if (!Base->getType()->isSpecificPlaceholderType(
4407           BuiltinType::OMPArraySection)) {
4408     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4409     if (Result.isInvalid())
4410       return ExprError();
4411     Base = Result.get();
4412   }
4413   return new (Context)
4414       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4415                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4416 }
4417
4418 ExprResult
4419 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4420                                       Expr *Idx, SourceLocation RLoc) {
4421   Expr *LHSExp = Base;
4422   Expr *RHSExp = Idx;
4423
4424   ExprValueKind VK = VK_LValue;
4425   ExprObjectKind OK = OK_Ordinary;
4426
4427   // Per C++ core issue 1213, the result is an xvalue if either operand is
4428   // a non-lvalue array, and an lvalue otherwise.
4429   if (getLangOpts().CPlusPlus11 &&
4430       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4431        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4432     VK = VK_XValue;
4433
4434   // Perform default conversions.
4435   if (!LHSExp->getType()->getAs<VectorType>()) {
4436     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4437     if (Result.isInvalid())
4438       return ExprError();
4439     LHSExp = Result.get();
4440   }
4441   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4442   if (Result.isInvalid())
4443     return ExprError();
4444   RHSExp = Result.get();
4445
4446   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4447
4448   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4449   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4450   // in the subscript position. As a result, we need to derive the array base
4451   // and index from the expression types.
4452   Expr *BaseExpr, *IndexExpr;
4453   QualType ResultType;
4454   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4455     BaseExpr = LHSExp;
4456     IndexExpr = RHSExp;
4457     ResultType = Context.DependentTy;
4458   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4459     BaseExpr = LHSExp;
4460     IndexExpr = RHSExp;
4461     ResultType = PTy->getPointeeType();
4462   } else if (const ObjCObjectPointerType *PTy =
4463                LHSTy->getAs<ObjCObjectPointerType>()) {
4464     BaseExpr = LHSExp;
4465     IndexExpr = RHSExp;
4466
4467     // Use custom logic if this should be the pseudo-object subscript
4468     // expression.
4469     if (!LangOpts.isSubscriptPointerArithmetic())
4470       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4471                                           nullptr);
4472
4473     ResultType = PTy->getPointeeType();
4474   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4475      // Handle the uncommon case of "123[Ptr]".
4476     BaseExpr = RHSExp;
4477     IndexExpr = LHSExp;
4478     ResultType = PTy->getPointeeType();
4479   } else if (const ObjCObjectPointerType *PTy =
4480                RHSTy->getAs<ObjCObjectPointerType>()) {
4481      // Handle the uncommon case of "123[Ptr]".
4482     BaseExpr = RHSExp;
4483     IndexExpr = LHSExp;
4484     ResultType = PTy->getPointeeType();
4485     if (!LangOpts.isSubscriptPointerArithmetic()) {
4486       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4487         << ResultType << BaseExpr->getSourceRange();
4488       return ExprError();
4489     }
4490   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4491     BaseExpr = LHSExp;    // vectors: V[123]
4492     IndexExpr = RHSExp;
4493     VK = LHSExp->getValueKind();
4494     if (VK != VK_RValue)
4495       OK = OK_VectorComponent;
4496
4497     // FIXME: need to deal with const...
4498     ResultType = VTy->getElementType();
4499   } else if (LHSTy->isArrayType()) {
4500     // If we see an array that wasn't promoted by
4501     // DefaultFunctionArrayLvalueConversion, it must be an array that
4502     // wasn't promoted because of the C90 rule that doesn't
4503     // allow promoting non-lvalue arrays.  Warn, then
4504     // force the promotion here.
4505     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4506         LHSExp->getSourceRange();
4507     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4508                                CK_ArrayToPointerDecay).get();
4509     LHSTy = LHSExp->getType();
4510
4511     BaseExpr = LHSExp;
4512     IndexExpr = RHSExp;
4513     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4514   } else if (RHSTy->isArrayType()) {
4515     // Same as previous, except for 123[f().a] case
4516     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4517         RHSExp->getSourceRange();
4518     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4519                                CK_ArrayToPointerDecay).get();
4520     RHSTy = RHSExp->getType();
4521
4522     BaseExpr = RHSExp;
4523     IndexExpr = LHSExp;
4524     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4525   } else {
4526     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4527        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4528   }
4529   // C99 6.5.2.1p1
4530   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4531     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4532                      << IndexExpr->getSourceRange());
4533
4534   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4535        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4536          && !IndexExpr->isTypeDependent())
4537     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4538
4539   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4540   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4541   // type. Note that Functions are not objects, and that (in C99 parlance)
4542   // incomplete types are not object types.
4543   if (ResultType->isFunctionType()) {
4544     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4545       << ResultType << BaseExpr->getSourceRange();
4546     return ExprError();
4547   }
4548
4549   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4550     // GNU extension: subscripting on pointer to void
4551     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4552       << BaseExpr->getSourceRange();
4553
4554     // C forbids expressions of unqualified void type from being l-values.
4555     // See IsCForbiddenLValueType.
4556     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4557   } else if (!ResultType->isDependentType() &&
4558       RequireCompleteType(LLoc, ResultType,
4559                           diag::err_subscript_incomplete_type, BaseExpr))
4560     return ExprError();
4561
4562   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4563          !ResultType.isCForbiddenLValueType());
4564
4565   return new (Context)
4566       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4567 }
4568
4569 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4570                                   ParmVarDecl *Param) {
4571   if (Param->hasUnparsedDefaultArg()) {
4572     Diag(CallLoc,
4573          diag::err_use_of_default_argument_to_function_declared_later) <<
4574       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4575     Diag(UnparsedDefaultArgLocs[Param],
4576          diag::note_default_argument_declared_here);
4577     return true;
4578   }
4579   
4580   if (Param->hasUninstantiatedDefaultArg()) {
4581     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4582
4583     EnterExpressionEvaluationContext EvalContext(
4584         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4585
4586     // Instantiate the expression.
4587     MultiLevelTemplateArgumentList MutiLevelArgList
4588       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4589
4590     InstantiatingTemplate Inst(*this, CallLoc, Param,
4591                                MutiLevelArgList.getInnermost());
4592     if (Inst.isInvalid())
4593       return true;
4594     if (Inst.isAlreadyInstantiating()) {
4595       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4596       Param->setInvalidDecl();
4597       return true;
4598     }
4599
4600     ExprResult Result;
4601     {
4602       // C++ [dcl.fct.default]p5:
4603       //   The names in the [default argument] expression are bound, and
4604       //   the semantic constraints are checked, at the point where the
4605       //   default argument expression appears.
4606       ContextRAII SavedContext(*this, FD);
4607       LocalInstantiationScope Local(*this);
4608       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4609                                 /*DirectInit*/false);
4610     }
4611     if (Result.isInvalid())
4612       return true;
4613
4614     // Check the expression as an initializer for the parameter.
4615     InitializedEntity Entity
4616       = InitializedEntity::InitializeParameter(Context, Param);
4617     InitializationKind Kind
4618       = InitializationKind::CreateCopy(Param->getLocation(),
4619              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4620     Expr *ResultE = Result.getAs<Expr>();
4621
4622     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4623     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4624     if (Result.isInvalid())
4625       return true;
4626
4627     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4628                                  Param->getOuterLocStart());
4629     if (Result.isInvalid())
4630       return true;
4631
4632     // Remember the instantiated default argument.
4633     Param->setDefaultArg(Result.getAs<Expr>());
4634     if (ASTMutationListener *L = getASTMutationListener()) {
4635       L->DefaultArgumentInstantiated(Param);
4636     }
4637   }
4638
4639   // If the default argument expression is not set yet, we are building it now.
4640   if (!Param->hasInit()) {
4641     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4642     Param->setInvalidDecl();
4643     return true;
4644   }
4645
4646   // If the default expression creates temporaries, we need to
4647   // push them to the current stack of expression temporaries so they'll
4648   // be properly destroyed.
4649   // FIXME: We should really be rebuilding the default argument with new
4650   // bound temporaries; see the comment in PR5810.
4651   // We don't need to do that with block decls, though, because
4652   // blocks in default argument expression can never capture anything.
4653   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4654     // Set the "needs cleanups" bit regardless of whether there are
4655     // any explicit objects.
4656     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4657
4658     // Append all the objects to the cleanup list.  Right now, this
4659     // should always be a no-op, because blocks in default argument
4660     // expressions should never be able to capture anything.
4661     assert(!Init->getNumObjects() &&
4662            "default argument expression has capturing blocks?");
4663   }
4664
4665   // We already type-checked the argument, so we know it works. 
4666   // Just mark all of the declarations in this potentially-evaluated expression
4667   // as being "referenced".
4668   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4669                                    /*SkipLocalVariables=*/true);
4670   return false;
4671 }
4672
4673 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4674                                         FunctionDecl *FD, ParmVarDecl *Param) {
4675   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4676     return ExprError();
4677   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4678 }
4679
4680 Sema::VariadicCallType
4681 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4682                           Expr *Fn) {
4683   if (Proto && Proto->isVariadic()) {
4684     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4685       return VariadicConstructor;
4686     else if (Fn && Fn->getType()->isBlockPointerType())
4687       return VariadicBlock;
4688     else if (FDecl) {
4689       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4690         if (Method->isInstance())
4691           return VariadicMethod;
4692     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4693       return VariadicMethod;
4694     return VariadicFunction;
4695   }
4696   return VariadicDoesNotApply;
4697 }
4698
4699 namespace {
4700 class FunctionCallCCC : public FunctionCallFilterCCC {
4701 public:
4702   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4703                   unsigned NumArgs, MemberExpr *ME)
4704       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4705         FunctionName(FuncName) {}
4706
4707   bool ValidateCandidate(const TypoCorrection &candidate) override {
4708     if (!candidate.getCorrectionSpecifier() ||
4709         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4710       return false;
4711     }
4712
4713     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4714   }
4715
4716 private:
4717   const IdentifierInfo *const FunctionName;
4718 };
4719 }
4720
4721 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4722                                                FunctionDecl *FDecl,
4723                                                ArrayRef<Expr *> Args) {
4724   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4725   DeclarationName FuncName = FDecl->getDeclName();
4726   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4727
4728   if (TypoCorrection Corrected = S.CorrectTypo(
4729           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4730           S.getScopeForContext(S.CurContext), nullptr,
4731           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4732                                              Args.size(), ME),
4733           Sema::CTK_ErrorRecovery)) {
4734     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4735       if (Corrected.isOverloaded()) {
4736         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4737         OverloadCandidateSet::iterator Best;
4738         for (NamedDecl *CD : Corrected) {
4739           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4740             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4741                                    OCS);
4742         }
4743         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4744         case OR_Success:
4745           ND = Best->FoundDecl;
4746           Corrected.setCorrectionDecl(ND);
4747           break;
4748         default:
4749           break;
4750         }
4751       }
4752       ND = ND->getUnderlyingDecl();
4753       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4754         return Corrected;
4755     }
4756   }
4757   return TypoCorrection();
4758 }
4759
4760 /// ConvertArgumentsForCall - Converts the arguments specified in
4761 /// Args/NumArgs to the parameter types of the function FDecl with
4762 /// function prototype Proto. Call is the call expression itself, and
4763 /// Fn is the function expression. For a C++ member function, this
4764 /// routine does not attempt to convert the object argument. Returns
4765 /// true if the call is ill-formed.
4766 bool
4767 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4768                               FunctionDecl *FDecl,
4769                               const FunctionProtoType *Proto,
4770                               ArrayRef<Expr *> Args,
4771                               SourceLocation RParenLoc,
4772                               bool IsExecConfig) {
4773   // Bail out early if calling a builtin with custom typechecking.
4774   if (FDecl)
4775     if (unsigned ID = FDecl->getBuiltinID())
4776       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4777         return false;
4778
4779   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4780   // assignment, to the types of the corresponding parameter, ...
4781   unsigned NumParams = Proto->getNumParams();
4782   bool Invalid = false;
4783   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4784   unsigned FnKind = Fn->getType()->isBlockPointerType()
4785                        ? 1 /* block */
4786                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4787                                        : 0 /* function */);
4788
4789   // If too few arguments are available (and we don't have default
4790   // arguments for the remaining parameters), don't make the call.
4791   if (Args.size() < NumParams) {
4792     if (Args.size() < MinArgs) {
4793       TypoCorrection TC;
4794       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4795         unsigned diag_id =
4796             MinArgs == NumParams && !Proto->isVariadic()
4797                 ? diag::err_typecheck_call_too_few_args_suggest
4798                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4799         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4800                                         << static_cast<unsigned>(Args.size())
4801                                         << TC.getCorrectionRange());
4802       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4803         Diag(RParenLoc,
4804              MinArgs == NumParams && !Proto->isVariadic()
4805                  ? diag::err_typecheck_call_too_few_args_one
4806                  : diag::err_typecheck_call_too_few_args_at_least_one)
4807             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4808       else
4809         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4810                             ? diag::err_typecheck_call_too_few_args
4811                             : diag::err_typecheck_call_too_few_args_at_least)
4812             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4813             << Fn->getSourceRange();
4814
4815       // Emit the location of the prototype.
4816       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4817         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4818           << FDecl;
4819
4820       return true;
4821     }
4822     Call->setNumArgs(Context, NumParams);
4823   }
4824
4825   // If too many are passed and not variadic, error on the extras and drop
4826   // them.
4827   if (Args.size() > NumParams) {
4828     if (!Proto->isVariadic()) {
4829       TypoCorrection TC;
4830       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4831         unsigned diag_id =
4832             MinArgs == NumParams && !Proto->isVariadic()
4833                 ? diag::err_typecheck_call_too_many_args_suggest
4834                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4835         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4836                                         << static_cast<unsigned>(Args.size())
4837                                         << TC.getCorrectionRange());
4838       } else if (NumParams == 1 && FDecl &&
4839                  FDecl->getParamDecl(0)->getDeclName())
4840         Diag(Args[NumParams]->getLocStart(),
4841              MinArgs == NumParams
4842                  ? diag::err_typecheck_call_too_many_args_one
4843                  : diag::err_typecheck_call_too_many_args_at_most_one)
4844             << FnKind << FDecl->getParamDecl(0)
4845             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4846             << SourceRange(Args[NumParams]->getLocStart(),
4847                            Args.back()->getLocEnd());
4848       else
4849         Diag(Args[NumParams]->getLocStart(),
4850              MinArgs == NumParams
4851                  ? diag::err_typecheck_call_too_many_args
4852                  : diag::err_typecheck_call_too_many_args_at_most)
4853             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4854             << Fn->getSourceRange()
4855             << SourceRange(Args[NumParams]->getLocStart(),
4856                            Args.back()->getLocEnd());
4857
4858       // Emit the location of the prototype.
4859       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4860         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4861           << FDecl;
4862       
4863       // This deletes the extra arguments.
4864       Call->setNumArgs(Context, NumParams);
4865       return true;
4866     }
4867   }
4868   SmallVector<Expr *, 8> AllArgs;
4869   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4870   
4871   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4872                                    Proto, 0, Args, AllArgs, CallType);
4873   if (Invalid)
4874     return true;
4875   unsigned TotalNumArgs = AllArgs.size();
4876   for (unsigned i = 0; i < TotalNumArgs; ++i)
4877     Call->setArg(i, AllArgs[i]);
4878
4879   return false;
4880 }
4881
4882 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4883                                   const FunctionProtoType *Proto,
4884                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4885                                   SmallVectorImpl<Expr *> &AllArgs,
4886                                   VariadicCallType CallType, bool AllowExplicit,
4887                                   bool IsListInitialization) {
4888   unsigned NumParams = Proto->getNumParams();
4889   bool Invalid = false;
4890   size_t ArgIx = 0;
4891   // Continue to check argument types (even if we have too few/many args).
4892   for (unsigned i = FirstParam; i < NumParams; i++) {
4893     QualType ProtoArgType = Proto->getParamType(i);
4894
4895     Expr *Arg;
4896     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4897     if (ArgIx < Args.size()) {
4898       Arg = Args[ArgIx++];
4899
4900       if (RequireCompleteType(Arg->getLocStart(),
4901                               ProtoArgType,
4902                               diag::err_call_incomplete_argument, Arg))
4903         return true;
4904
4905       // Strip the unbridged-cast placeholder expression off, if applicable.
4906       bool CFAudited = false;
4907       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4908           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4909           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4910         Arg = stripARCUnbridgedCast(Arg);
4911       else if (getLangOpts().ObjCAutoRefCount &&
4912                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4913                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4914         CFAudited = true;
4915
4916       InitializedEntity Entity =
4917           Param ? InitializedEntity::InitializeParameter(Context, Param,
4918                                                          ProtoArgType)
4919                 : InitializedEntity::InitializeParameter(
4920                       Context, ProtoArgType, Proto->isParamConsumed(i));
4921
4922       // Remember that parameter belongs to a CF audited API.
4923       if (CFAudited)
4924         Entity.setParameterCFAudited();
4925
4926       ExprResult ArgE = PerformCopyInitialization(
4927           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4928       if (ArgE.isInvalid())
4929         return true;
4930
4931       Arg = ArgE.getAs<Expr>();
4932     } else {
4933       assert(Param && "can't use default arguments without a known callee");
4934
4935       ExprResult ArgExpr =
4936         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4937       if (ArgExpr.isInvalid())
4938         return true;
4939
4940       Arg = ArgExpr.getAs<Expr>();
4941     }
4942
4943     // Check for array bounds violations for each argument to the call. This
4944     // check only triggers warnings when the argument isn't a more complex Expr
4945     // with its own checking, such as a BinaryOperator.
4946     CheckArrayAccess(Arg);
4947
4948     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4949     CheckStaticArrayArgument(CallLoc, Param, Arg);
4950
4951     AllArgs.push_back(Arg);
4952   }
4953
4954   // If this is a variadic call, handle args passed through "...".
4955   if (CallType != VariadicDoesNotApply) {
4956     // Assume that extern "C" functions with variadic arguments that
4957     // return __unknown_anytype aren't *really* variadic.
4958     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4959         FDecl->isExternC()) {
4960       for (Expr *A : Args.slice(ArgIx)) {
4961         QualType paramType; // ignored
4962         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4963         Invalid |= arg.isInvalid();
4964         AllArgs.push_back(arg.get());
4965       }
4966
4967     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4968     } else {
4969       for (Expr *A : Args.slice(ArgIx)) {
4970         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4971         Invalid |= Arg.isInvalid();
4972         AllArgs.push_back(Arg.get());
4973       }
4974     }
4975
4976     // Check for array bounds violations.
4977     for (Expr *A : Args.slice(ArgIx))
4978       CheckArrayAccess(A);
4979   }
4980   return Invalid;
4981 }
4982
4983 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4984   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4985   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4986     TL = DTL.getOriginalLoc();
4987   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4988     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4989       << ATL.getLocalSourceRange();
4990 }
4991
4992 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4993 /// array parameter, check that it is non-null, and that if it is formed by
4994 /// array-to-pointer decay, the underlying array is sufficiently large.
4995 ///
4996 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4997 /// array type derivation, then for each call to the function, the value of the
4998 /// corresponding actual argument shall provide access to the first element of
4999 /// an array with at least as many elements as specified by the size expression.
5000 void
5001 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5002                                ParmVarDecl *Param,
5003                                const Expr *ArgExpr) {
5004   // Static array parameters are not supported in C++.
5005   if (!Param || getLangOpts().CPlusPlus)
5006     return;
5007
5008   QualType OrigTy = Param->getOriginalType();
5009
5010   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5011   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5012     return;
5013
5014   if (ArgExpr->isNullPointerConstant(Context,
5015                                      Expr::NPC_NeverValueDependent)) {
5016     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5017     DiagnoseCalleeStaticArrayParam(*this, Param);
5018     return;
5019   }
5020
5021   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5022   if (!CAT)
5023     return;
5024
5025   const ConstantArrayType *ArgCAT =
5026     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5027   if (!ArgCAT)
5028     return;
5029
5030   if (ArgCAT->getSize().ult(CAT->getSize())) {
5031     Diag(CallLoc, diag::warn_static_array_too_small)
5032       << ArgExpr->getSourceRange()
5033       << (unsigned) ArgCAT->getSize().getZExtValue()
5034       << (unsigned) CAT->getSize().getZExtValue();
5035     DiagnoseCalleeStaticArrayParam(*this, Param);
5036   }
5037 }
5038
5039 /// Given a function expression of unknown-any type, try to rebuild it
5040 /// to have a function type.
5041 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5042
5043 /// Is the given type a placeholder that we need to lower out
5044 /// immediately during argument processing?
5045 static bool isPlaceholderToRemoveAsArg(QualType type) {
5046   // Placeholders are never sugared.
5047   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5048   if (!placeholder) return false;
5049
5050   switch (placeholder->getKind()) {
5051   // Ignore all the non-placeholder types.
5052 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5053   case BuiltinType::Id:
5054 #include "clang/Basic/OpenCLImageTypes.def"
5055 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5056 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5057 #include "clang/AST/BuiltinTypes.def"
5058     return false;
5059
5060   // We cannot lower out overload sets; they might validly be resolved
5061   // by the call machinery.
5062   case BuiltinType::Overload:
5063     return false;
5064
5065   // Unbridged casts in ARC can be handled in some call positions and
5066   // should be left in place.
5067   case BuiltinType::ARCUnbridgedCast:
5068     return false;
5069
5070   // Pseudo-objects should be converted as soon as possible.
5071   case BuiltinType::PseudoObject:
5072     return true;
5073
5074   // The debugger mode could theoretically but currently does not try
5075   // to resolve unknown-typed arguments based on known parameter types.
5076   case BuiltinType::UnknownAny:
5077     return true;
5078
5079   // These are always invalid as call arguments and should be reported.
5080   case BuiltinType::BoundMember:
5081   case BuiltinType::BuiltinFn:
5082   case BuiltinType::OMPArraySection:
5083     return true;
5084
5085   }
5086   llvm_unreachable("bad builtin type kind");
5087 }
5088
5089 /// Check an argument list for placeholders that we won't try to
5090 /// handle later.
5091 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5092   // Apply this processing to all the arguments at once instead of
5093   // dying at the first failure.
5094   bool hasInvalid = false;
5095   for (size_t i = 0, e = args.size(); i != e; i++) {
5096     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5097       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5098       if (result.isInvalid()) hasInvalid = true;
5099       else args[i] = result.get();
5100     } else if (hasInvalid) {
5101       (void)S.CorrectDelayedTyposInExpr(args[i]);
5102     }
5103   }
5104   return hasInvalid;
5105 }
5106
5107 /// If a builtin function has a pointer argument with no explicit address
5108 /// space, then it should be able to accept a pointer to any address
5109 /// space as input.  In order to do this, we need to replace the
5110 /// standard builtin declaration with one that uses the same address space
5111 /// as the call.
5112 ///
5113 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5114 ///                  it does not contain any pointer arguments without
5115 ///                  an address space qualifer.  Otherwise the rewritten
5116 ///                  FunctionDecl is returned.
5117 /// TODO: Handle pointer return types.
5118 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5119                                                 const FunctionDecl *FDecl,
5120                                                 MultiExprArg ArgExprs) {
5121
5122   QualType DeclType = FDecl->getType();
5123   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5124
5125   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5126       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5127     return nullptr;
5128
5129   bool NeedsNewDecl = false;
5130   unsigned i = 0;
5131   SmallVector<QualType, 8> OverloadParams;
5132
5133   for (QualType ParamType : FT->param_types()) {
5134
5135     // Convert array arguments to pointer to simplify type lookup.
5136     ExprResult ArgRes =
5137         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5138     if (ArgRes.isInvalid())
5139       return nullptr;
5140     Expr *Arg = ArgRes.get();
5141     QualType ArgType = Arg->getType();
5142     if (!ParamType->isPointerType() ||
5143         ParamType.getQualifiers().hasAddressSpace() ||
5144         !ArgType->isPointerType() ||
5145         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5146       OverloadParams.push_back(ParamType);
5147       continue;
5148     }
5149
5150     NeedsNewDecl = true;
5151     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5152
5153     QualType PointeeType = ParamType->getPointeeType();
5154     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5155     OverloadParams.push_back(Context.getPointerType(PointeeType));
5156   }
5157
5158   if (!NeedsNewDecl)
5159     return nullptr;
5160
5161   FunctionProtoType::ExtProtoInfo EPI;
5162   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5163                                                 OverloadParams, EPI);
5164   DeclContext *Parent = Context.getTranslationUnitDecl();
5165   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5166                                                     FDecl->getLocation(),
5167                                                     FDecl->getLocation(),
5168                                                     FDecl->getIdentifier(),
5169                                                     OverloadTy,
5170                                                     /*TInfo=*/nullptr,
5171                                                     SC_Extern, false,
5172                                                     /*hasPrototype=*/true);
5173   SmallVector<ParmVarDecl*, 16> Params;
5174   FT = cast<FunctionProtoType>(OverloadTy);
5175   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5176     QualType ParamType = FT->getParamType(i);
5177     ParmVarDecl *Parm =
5178         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5179                                 SourceLocation(), nullptr, ParamType,
5180                                 /*TInfo=*/nullptr, SC_None, nullptr);
5181     Parm->setScopeInfo(0, i);
5182     Params.push_back(Parm);
5183   }
5184   OverloadDecl->setParams(Params);
5185   return OverloadDecl;
5186 }
5187
5188 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5189                                     FunctionDecl *Callee,
5190                                     MultiExprArg ArgExprs) {
5191   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5192   // similar attributes) really don't like it when functions are called with an
5193   // invalid number of args.
5194   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5195                          /*PartialOverloading=*/false) &&
5196       !Callee->isVariadic())
5197     return;
5198   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5199     return;
5200
5201   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5202     S.Diag(Fn->getLocStart(),
5203            isa<CXXMethodDecl>(Callee)
5204                ? diag::err_ovl_no_viable_member_function_in_call
5205                : diag::err_ovl_no_viable_function_in_call)
5206         << Callee << Callee->getSourceRange();
5207     S.Diag(Callee->getLocation(),
5208            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5209         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5210     return;
5211   }
5212 }
5213
5214 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5215 /// This provides the location of the left/right parens and a list of comma
5216 /// locations.
5217 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5218                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5219                                Expr *ExecConfig, bool IsExecConfig) {
5220   // Since this might be a postfix expression, get rid of ParenListExprs.
5221   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5222   if (Result.isInvalid()) return ExprError();
5223   Fn = Result.get();
5224
5225   if (checkArgsForPlaceholders(*this, ArgExprs))
5226     return ExprError();
5227
5228   if (getLangOpts().CPlusPlus) {
5229     // If this is a pseudo-destructor expression, build the call immediately.
5230     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5231       if (!ArgExprs.empty()) {
5232         // Pseudo-destructor calls should not have any arguments.
5233         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5234             << FixItHint::CreateRemoval(
5235                    SourceRange(ArgExprs.front()->getLocStart(),
5236                                ArgExprs.back()->getLocEnd()));
5237       }
5238
5239       return new (Context)
5240           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5241     }
5242     if (Fn->getType() == Context.PseudoObjectTy) {
5243       ExprResult result = CheckPlaceholderExpr(Fn);
5244       if (result.isInvalid()) return ExprError();
5245       Fn = result.get();
5246     }
5247
5248     // Determine whether this is a dependent call inside a C++ template,
5249     // in which case we won't do any semantic analysis now.
5250     bool Dependent = false;
5251     if (Fn->isTypeDependent())
5252       Dependent = true;
5253     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5254       Dependent = true;
5255
5256     if (Dependent) {
5257       if (ExecConfig) {
5258         return new (Context) CUDAKernelCallExpr(
5259             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5260             Context.DependentTy, VK_RValue, RParenLoc);
5261       } else {
5262         return new (Context) CallExpr(
5263             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5264       }
5265     }
5266
5267     // Determine whether this is a call to an object (C++ [over.call.object]).
5268     if (Fn->getType()->isRecordType())
5269       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5270                                           RParenLoc);
5271
5272     if (Fn->getType() == Context.UnknownAnyTy) {
5273       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5274       if (result.isInvalid()) return ExprError();
5275       Fn = result.get();
5276     }
5277
5278     if (Fn->getType() == Context.BoundMemberTy) {
5279       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5280                                        RParenLoc);
5281     }
5282   }
5283
5284   // Check for overloaded calls.  This can happen even in C due to extensions.
5285   if (Fn->getType() == Context.OverloadTy) {
5286     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5287
5288     // We aren't supposed to apply this logic if there's an '&' involved.
5289     if (!find.HasFormOfMemberPointer) {
5290       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5291         return new (Context) CallExpr(
5292             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5293       OverloadExpr *ovl = find.Expression;
5294       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5295         return BuildOverloadedCallExpr(
5296             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5297             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5298       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5299                                        RParenLoc);
5300     }
5301   }
5302
5303   // If we're directly calling a function, get the appropriate declaration.
5304   if (Fn->getType() == Context.UnknownAnyTy) {
5305     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5306     if (result.isInvalid()) return ExprError();
5307     Fn = result.get();
5308   }
5309
5310   Expr *NakedFn = Fn->IgnoreParens();
5311
5312   bool CallingNDeclIndirectly = false;
5313   NamedDecl *NDecl = nullptr;
5314   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5315     if (UnOp->getOpcode() == UO_AddrOf) {
5316       CallingNDeclIndirectly = true;
5317       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5318     }
5319   }
5320
5321   if (isa<DeclRefExpr>(NakedFn)) {
5322     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5323
5324     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5325     if (FDecl && FDecl->getBuiltinID()) {
5326       // Rewrite the function decl for this builtin by replacing parameters
5327       // with no explicit address space with the address space of the arguments
5328       // in ArgExprs.
5329       if ((FDecl =
5330                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5331         NDecl = FDecl;
5332         Fn = DeclRefExpr::Create(
5333             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5334             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5335       }
5336     }
5337   } else if (isa<MemberExpr>(NakedFn))
5338     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5339
5340   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5341     if (CallingNDeclIndirectly &&
5342         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5343                                            Fn->getLocStart()))
5344       return ExprError();
5345
5346     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5347       return ExprError();
5348
5349     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5350   }
5351
5352   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5353                                ExecConfig, IsExecConfig);
5354 }
5355
5356 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5357 ///
5358 /// __builtin_astype( value, dst type )
5359 ///
5360 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5361                                  SourceLocation BuiltinLoc,
5362                                  SourceLocation RParenLoc) {
5363   ExprValueKind VK = VK_RValue;
5364   ExprObjectKind OK = OK_Ordinary;
5365   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5366   QualType SrcTy = E->getType();
5367   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5368     return ExprError(Diag(BuiltinLoc,
5369                           diag::err_invalid_astype_of_different_size)
5370                      << DstTy
5371                      << SrcTy
5372                      << E->getSourceRange());
5373   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5374 }
5375
5376 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5377 /// provided arguments.
5378 ///
5379 /// __builtin_convertvector( value, dst type )
5380 ///
5381 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5382                                         SourceLocation BuiltinLoc,
5383                                         SourceLocation RParenLoc) {
5384   TypeSourceInfo *TInfo;
5385   GetTypeFromParser(ParsedDestTy, &TInfo);
5386   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5387 }
5388
5389 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5390 /// i.e. an expression not of \p OverloadTy.  The expression should
5391 /// unary-convert to an expression of function-pointer or
5392 /// block-pointer type.
5393 ///
5394 /// \param NDecl the declaration being called, if available
5395 ExprResult
5396 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5397                             SourceLocation LParenLoc,
5398                             ArrayRef<Expr *> Args,
5399                             SourceLocation RParenLoc,
5400                             Expr *Config, bool IsExecConfig) {
5401   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5402   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5403
5404   // Functions with 'interrupt' attribute cannot be called directly.
5405   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5406     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5407     return ExprError();
5408   }
5409
5410   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5411   // so there's some risk when calling out to non-interrupt handler functions
5412   // that the callee might not preserve them. This is easy to diagnose here,
5413   // but can be very challenging to debug.
5414   if (auto *Caller = getCurFunctionDecl())
5415     if (Caller->hasAttr<ARMInterruptAttr>()) {
5416       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5417       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5418         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5419     }
5420
5421   // Promote the function operand.
5422   // We special-case function promotion here because we only allow promoting
5423   // builtin functions to function pointers in the callee of a call.
5424   ExprResult Result;
5425   if (BuiltinID &&
5426       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5427     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5428                                CK_BuiltinFnToFnPtr).get();
5429   } else {
5430     Result = CallExprUnaryConversions(Fn);
5431   }
5432   if (Result.isInvalid())
5433     return ExprError();
5434   Fn = Result.get();
5435
5436   // Make the call expr early, before semantic checks.  This guarantees cleanup
5437   // of arguments and function on error.
5438   CallExpr *TheCall;
5439   if (Config)
5440     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5441                                                cast<CallExpr>(Config), Args,
5442                                                Context.BoolTy, VK_RValue,
5443                                                RParenLoc);
5444   else
5445     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5446                                      VK_RValue, RParenLoc);
5447
5448   if (!getLangOpts().CPlusPlus) {
5449     // C cannot always handle TypoExpr nodes in builtin calls and direct
5450     // function calls as their argument checking don't necessarily handle
5451     // dependent types properly, so make sure any TypoExprs have been
5452     // dealt with.
5453     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5454     if (!Result.isUsable()) return ExprError();
5455     TheCall = dyn_cast<CallExpr>(Result.get());
5456     if (!TheCall) return Result;
5457     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5458   }
5459
5460   // Bail out early if calling a builtin with custom typechecking.
5461   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5462     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5463
5464  retry:
5465   const FunctionType *FuncT;
5466   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5467     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5468     // have type pointer to function".
5469     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5470     if (!FuncT)
5471       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5472                          << Fn->getType() << Fn->getSourceRange());
5473   } else if (const BlockPointerType *BPT =
5474                Fn->getType()->getAs<BlockPointerType>()) {
5475     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5476   } else {
5477     // Handle calls to expressions of unknown-any type.
5478     if (Fn->getType() == Context.UnknownAnyTy) {
5479       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5480       if (rewrite.isInvalid()) return ExprError();
5481       Fn = rewrite.get();
5482       TheCall->setCallee(Fn);
5483       goto retry;
5484     }
5485
5486     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5487       << Fn->getType() << Fn->getSourceRange());
5488   }
5489
5490   if (getLangOpts().CUDA) {
5491     if (Config) {
5492       // CUDA: Kernel calls must be to global functions
5493       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5494         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5495             << FDecl->getName() << Fn->getSourceRange());
5496
5497       // CUDA: Kernel function must have 'void' return type
5498       if (!FuncT->getReturnType()->isVoidType())
5499         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5500             << Fn->getType() << Fn->getSourceRange());
5501     } else {
5502       // CUDA: Calls to global functions must be configured
5503       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5504         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5505             << FDecl->getName() << Fn->getSourceRange());
5506     }
5507   }
5508
5509   // Check for a valid return type
5510   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5511                           FDecl))
5512     return ExprError();
5513
5514   // We know the result type of the call, set it.
5515   TheCall->setType(FuncT->getCallResultType(Context));
5516   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5517
5518   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5519   if (Proto) {
5520     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5521                                 IsExecConfig))
5522       return ExprError();
5523   } else {
5524     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5525
5526     if (FDecl) {
5527       // Check if we have too few/too many template arguments, based
5528       // on our knowledge of the function definition.
5529       const FunctionDecl *Def = nullptr;
5530       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5531         Proto = Def->getType()->getAs<FunctionProtoType>();
5532        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5533           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5534           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5535       }
5536       
5537       // If the function we're calling isn't a function prototype, but we have
5538       // a function prototype from a prior declaratiom, use that prototype.
5539       if (!FDecl->hasPrototype())
5540         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5541     }
5542
5543     // Promote the arguments (C99 6.5.2.2p6).
5544     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5545       Expr *Arg = Args[i];
5546
5547       if (Proto && i < Proto->getNumParams()) {
5548         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5549             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5550         ExprResult ArgE =
5551             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5552         if (ArgE.isInvalid())
5553           return true;
5554         
5555         Arg = ArgE.getAs<Expr>();
5556
5557       } else {
5558         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5559
5560         if (ArgE.isInvalid())
5561           return true;
5562
5563         Arg = ArgE.getAs<Expr>();
5564       }
5565       
5566       if (RequireCompleteType(Arg->getLocStart(),
5567                               Arg->getType(),
5568                               diag::err_call_incomplete_argument, Arg))
5569         return ExprError();
5570
5571       TheCall->setArg(i, Arg);
5572     }
5573   }
5574
5575   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5576     if (!Method->isStatic())
5577       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5578         << Fn->getSourceRange());
5579
5580   // Check for sentinels
5581   if (NDecl)
5582     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5583
5584   // Do special checking on direct calls to functions.
5585   if (FDecl) {
5586     if (CheckFunctionCall(FDecl, TheCall, Proto))
5587       return ExprError();
5588
5589     if (BuiltinID)
5590       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5591   } else if (NDecl) {
5592     if (CheckPointerCall(NDecl, TheCall, Proto))
5593       return ExprError();
5594   } else {
5595     if (CheckOtherCall(TheCall, Proto))
5596       return ExprError();
5597   }
5598
5599   return MaybeBindToTemporary(TheCall);
5600 }
5601
5602 ExprResult
5603 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5604                            SourceLocation RParenLoc, Expr *InitExpr) {
5605   assert(Ty && "ActOnCompoundLiteral(): missing type");
5606   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5607
5608   TypeSourceInfo *TInfo;
5609   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5610   if (!TInfo)
5611     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5612
5613   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5614 }
5615
5616 ExprResult
5617 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5618                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5619   QualType literalType = TInfo->getType();
5620
5621   if (literalType->isArrayType()) {
5622     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5623           diag::err_illegal_decl_array_incomplete_type,
5624           SourceRange(LParenLoc,
5625                       LiteralExpr->getSourceRange().getEnd())))
5626       return ExprError();
5627     if (literalType->isVariableArrayType())
5628       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5629         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5630   } else if (!literalType->isDependentType() &&
5631              RequireCompleteType(LParenLoc, literalType,
5632                diag::err_typecheck_decl_incomplete_type,
5633                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5634     return ExprError();
5635
5636   InitializedEntity Entity
5637     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5638   InitializationKind Kind
5639     = InitializationKind::CreateCStyleCast(LParenLoc, 
5640                                            SourceRange(LParenLoc, RParenLoc),
5641                                            /*InitList=*/true);
5642   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5643   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5644                                       &literalType);
5645   if (Result.isInvalid())
5646     return ExprError();
5647   LiteralExpr = Result.get();
5648
5649   bool isFileScope = !CurContext->isFunctionOrMethod();
5650   if (isFileScope &&
5651       !LiteralExpr->isTypeDependent() &&
5652       !LiteralExpr->isValueDependent() &&
5653       !literalType->isDependentType()) { // 6.5.2.5p3
5654     if (CheckForConstantInitializer(LiteralExpr, literalType))
5655       return ExprError();
5656   }
5657
5658   // In C, compound literals are l-values for some reason.
5659   // For GCC compatibility, in C++, file-scope array compound literals with
5660   // constant initializers are also l-values, and compound literals are
5661   // otherwise prvalues.
5662   //
5663   // (GCC also treats C++ list-initialized file-scope array prvalues with
5664   // constant initializers as l-values, but that's non-conforming, so we don't
5665   // follow it there.)
5666   //
5667   // FIXME: It would be better to handle the lvalue cases as materializing and
5668   // lifetime-extending a temporary object, but our materialized temporaries
5669   // representation only supports lifetime extension from a variable, not "out
5670   // of thin air".
5671   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5672   // is bound to the result of applying array-to-pointer decay to the compound
5673   // literal.
5674   // FIXME: GCC supports compound literals of reference type, which should
5675   // obviously have a value kind derived from the kind of reference involved.
5676   ExprValueKind VK =
5677       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5678           ? VK_RValue
5679           : VK_LValue;
5680
5681   return MaybeBindToTemporary(
5682       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5683                                         VK, LiteralExpr, isFileScope));
5684 }
5685
5686 ExprResult
5687 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5688                     SourceLocation RBraceLoc) {
5689   // Immediately handle non-overload placeholders.  Overloads can be
5690   // resolved contextually, but everything else here can't.
5691   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5692     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5693       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5694
5695       // Ignore failures; dropping the entire initializer list because
5696       // of one failure would be terrible for indexing/etc.
5697       if (result.isInvalid()) continue;
5698
5699       InitArgList[I] = result.get();
5700     }
5701   }
5702
5703   // Semantic analysis for initializers is done by ActOnDeclarator() and
5704   // CheckInitializer() - it requires knowledge of the object being intialized.
5705
5706   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5707                                                RBraceLoc);
5708   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5709   return E;
5710 }
5711
5712 /// Do an explicit extend of the given block pointer if we're in ARC.
5713 void Sema::maybeExtendBlockObject(ExprResult &E) {
5714   assert(E.get()->getType()->isBlockPointerType());
5715   assert(E.get()->isRValue());
5716
5717   // Only do this in an r-value context.
5718   if (!getLangOpts().ObjCAutoRefCount) return;
5719
5720   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5721                                CK_ARCExtendBlockObject, E.get(),
5722                                /*base path*/ nullptr, VK_RValue);
5723   Cleanup.setExprNeedsCleanups(true);
5724 }
5725
5726 /// Prepare a conversion of the given expression to an ObjC object
5727 /// pointer type.
5728 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5729   QualType type = E.get()->getType();
5730   if (type->isObjCObjectPointerType()) {
5731     return CK_BitCast;
5732   } else if (type->isBlockPointerType()) {
5733     maybeExtendBlockObject(E);
5734     return CK_BlockPointerToObjCPointerCast;
5735   } else {
5736     assert(type->isPointerType());
5737     return CK_CPointerToObjCPointerCast;
5738   }
5739 }
5740
5741 /// Prepares for a scalar cast, performing all the necessary stages
5742 /// except the final cast and returning the kind required.
5743 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5744   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5745   // Also, callers should have filtered out the invalid cases with
5746   // pointers.  Everything else should be possible.
5747
5748   QualType SrcTy = Src.get()->getType();
5749   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5750     return CK_NoOp;
5751
5752   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5753   case Type::STK_MemberPointer:
5754     llvm_unreachable("member pointer type in C");
5755
5756   case Type::STK_CPointer:
5757   case Type::STK_BlockPointer:
5758   case Type::STK_ObjCObjectPointer:
5759     switch (DestTy->getScalarTypeKind()) {
5760     case Type::STK_CPointer: {
5761       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5762       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5763       if (SrcAS != DestAS)
5764         return CK_AddressSpaceConversion;
5765       return CK_BitCast;
5766     }
5767     case Type::STK_BlockPointer:
5768       return (SrcKind == Type::STK_BlockPointer
5769                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5770     case Type::STK_ObjCObjectPointer:
5771       if (SrcKind == Type::STK_ObjCObjectPointer)
5772         return CK_BitCast;
5773       if (SrcKind == Type::STK_CPointer)
5774         return CK_CPointerToObjCPointerCast;
5775       maybeExtendBlockObject(Src);
5776       return CK_BlockPointerToObjCPointerCast;
5777     case Type::STK_Bool:
5778       return CK_PointerToBoolean;
5779     case Type::STK_Integral:
5780       return CK_PointerToIntegral;
5781     case Type::STK_Floating:
5782     case Type::STK_FloatingComplex:
5783     case Type::STK_IntegralComplex:
5784     case Type::STK_MemberPointer:
5785       llvm_unreachable("illegal cast from pointer");
5786     }
5787     llvm_unreachable("Should have returned before this");
5788
5789   case Type::STK_Bool: // casting from bool is like casting from an integer
5790   case Type::STK_Integral:
5791     switch (DestTy->getScalarTypeKind()) {
5792     case Type::STK_CPointer:
5793     case Type::STK_ObjCObjectPointer:
5794     case Type::STK_BlockPointer:
5795       if (Src.get()->isNullPointerConstant(Context,
5796                                            Expr::NPC_ValueDependentIsNull))
5797         return CK_NullToPointer;
5798       return CK_IntegralToPointer;
5799     case Type::STK_Bool:
5800       return CK_IntegralToBoolean;
5801     case Type::STK_Integral:
5802       return CK_IntegralCast;
5803     case Type::STK_Floating:
5804       return CK_IntegralToFloating;
5805     case Type::STK_IntegralComplex:
5806       Src = ImpCastExprToType(Src.get(),
5807                       DestTy->castAs<ComplexType>()->getElementType(),
5808                       CK_IntegralCast);
5809       return CK_IntegralRealToComplex;
5810     case Type::STK_FloatingComplex:
5811       Src = ImpCastExprToType(Src.get(),
5812                       DestTy->castAs<ComplexType>()->getElementType(),
5813                       CK_IntegralToFloating);
5814       return CK_FloatingRealToComplex;
5815     case Type::STK_MemberPointer:
5816       llvm_unreachable("member pointer type in C");
5817     }
5818     llvm_unreachable("Should have returned before this");
5819
5820   case Type::STK_Floating:
5821     switch (DestTy->getScalarTypeKind()) {
5822     case Type::STK_Floating:
5823       return CK_FloatingCast;
5824     case Type::STK_Bool:
5825       return CK_FloatingToBoolean;
5826     case Type::STK_Integral:
5827       return CK_FloatingToIntegral;
5828     case Type::STK_FloatingComplex:
5829       Src = ImpCastExprToType(Src.get(),
5830                               DestTy->castAs<ComplexType>()->getElementType(),
5831                               CK_FloatingCast);
5832       return CK_FloatingRealToComplex;
5833     case Type::STK_IntegralComplex:
5834       Src = ImpCastExprToType(Src.get(),
5835                               DestTy->castAs<ComplexType>()->getElementType(),
5836                               CK_FloatingToIntegral);
5837       return CK_IntegralRealToComplex;
5838     case Type::STK_CPointer:
5839     case Type::STK_ObjCObjectPointer:
5840     case Type::STK_BlockPointer:
5841       llvm_unreachable("valid float->pointer cast?");
5842     case Type::STK_MemberPointer:
5843       llvm_unreachable("member pointer type in C");
5844     }
5845     llvm_unreachable("Should have returned before this");
5846
5847   case Type::STK_FloatingComplex:
5848     switch (DestTy->getScalarTypeKind()) {
5849     case Type::STK_FloatingComplex:
5850       return CK_FloatingComplexCast;
5851     case Type::STK_IntegralComplex:
5852       return CK_FloatingComplexToIntegralComplex;
5853     case Type::STK_Floating: {
5854       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5855       if (Context.hasSameType(ET, DestTy))
5856         return CK_FloatingComplexToReal;
5857       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5858       return CK_FloatingCast;
5859     }
5860     case Type::STK_Bool:
5861       return CK_FloatingComplexToBoolean;
5862     case Type::STK_Integral:
5863       Src = ImpCastExprToType(Src.get(),
5864                               SrcTy->castAs<ComplexType>()->getElementType(),
5865                               CK_FloatingComplexToReal);
5866       return CK_FloatingToIntegral;
5867     case Type::STK_CPointer:
5868     case Type::STK_ObjCObjectPointer:
5869     case Type::STK_BlockPointer:
5870       llvm_unreachable("valid complex float->pointer cast?");
5871     case Type::STK_MemberPointer:
5872       llvm_unreachable("member pointer type in C");
5873     }
5874     llvm_unreachable("Should have returned before this");
5875
5876   case Type::STK_IntegralComplex:
5877     switch (DestTy->getScalarTypeKind()) {
5878     case Type::STK_FloatingComplex:
5879       return CK_IntegralComplexToFloatingComplex;
5880     case Type::STK_IntegralComplex:
5881       return CK_IntegralComplexCast;
5882     case Type::STK_Integral: {
5883       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5884       if (Context.hasSameType(ET, DestTy))
5885         return CK_IntegralComplexToReal;
5886       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5887       return CK_IntegralCast;
5888     }
5889     case Type::STK_Bool:
5890       return CK_IntegralComplexToBoolean;
5891     case Type::STK_Floating:
5892       Src = ImpCastExprToType(Src.get(),
5893                               SrcTy->castAs<ComplexType>()->getElementType(),
5894                               CK_IntegralComplexToReal);
5895       return CK_IntegralToFloating;
5896     case Type::STK_CPointer:
5897     case Type::STK_ObjCObjectPointer:
5898     case Type::STK_BlockPointer:
5899       llvm_unreachable("valid complex int->pointer cast?");
5900     case Type::STK_MemberPointer:
5901       llvm_unreachable("member pointer type in C");
5902     }
5903     llvm_unreachable("Should have returned before this");
5904   }
5905
5906   llvm_unreachable("Unhandled scalar cast");
5907 }
5908
5909 static bool breakDownVectorType(QualType type, uint64_t &len,
5910                                 QualType &eltType) {
5911   // Vectors are simple.
5912   if (const VectorType *vecType = type->getAs<VectorType>()) {
5913     len = vecType->getNumElements();
5914     eltType = vecType->getElementType();
5915     assert(eltType->isScalarType());
5916     return true;
5917   }
5918   
5919   // We allow lax conversion to and from non-vector types, but only if
5920   // they're real types (i.e. non-complex, non-pointer scalar types).
5921   if (!type->isRealType()) return false;
5922   
5923   len = 1;
5924   eltType = type;
5925   return true;
5926 }
5927
5928 /// Are the two types lax-compatible vector types?  That is, given
5929 /// that one of them is a vector, do they have equal storage sizes,
5930 /// where the storage size is the number of elements times the element
5931 /// size?
5932 ///
5933 /// This will also return false if either of the types is neither a
5934 /// vector nor a real type.
5935 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5936   assert(destTy->isVectorType() || srcTy->isVectorType());
5937   
5938   // Disallow lax conversions between scalars and ExtVectors (these
5939   // conversions are allowed for other vector types because common headers
5940   // depend on them).  Most scalar OP ExtVector cases are handled by the
5941   // splat path anyway, which does what we want (convert, not bitcast).
5942   // What this rules out for ExtVectors is crazy things like char4*float.
5943   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5944   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5945
5946   uint64_t srcLen, destLen;
5947   QualType srcEltTy, destEltTy;
5948   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5949   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5950   
5951   // ASTContext::getTypeSize will return the size rounded up to a
5952   // power of 2, so instead of using that, we need to use the raw
5953   // element size multiplied by the element count.
5954   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5955   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5956   
5957   return (srcLen * srcEltSize == destLen * destEltSize);
5958 }
5959
5960 /// Is this a legal conversion between two types, one of which is
5961 /// known to be a vector type?
5962 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5963   assert(destTy->isVectorType() || srcTy->isVectorType());
5964   
5965   if (!Context.getLangOpts().LaxVectorConversions)
5966     return false;
5967   return areLaxCompatibleVectorTypes(srcTy, destTy);
5968 }
5969
5970 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5971                            CastKind &Kind) {
5972   assert(VectorTy->isVectorType() && "Not a vector type!");
5973
5974   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5975     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5976       return Diag(R.getBegin(),
5977                   Ty->isVectorType() ?
5978                   diag::err_invalid_conversion_between_vectors :
5979                   diag::err_invalid_conversion_between_vector_and_integer)
5980         << VectorTy << Ty << R;
5981   } else
5982     return Diag(R.getBegin(),
5983                 diag::err_invalid_conversion_between_vector_and_scalar)
5984       << VectorTy << Ty << R;
5985
5986   Kind = CK_BitCast;
5987   return false;
5988 }
5989
5990 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5991   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5992
5993   if (DestElemTy == SplattedExpr->getType())
5994     return SplattedExpr;
5995
5996   assert(DestElemTy->isFloatingType() ||
5997          DestElemTy->isIntegralOrEnumerationType());
5998
5999   CastKind CK;
6000   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6001     // OpenCL requires that we convert `true` boolean expressions to -1, but
6002     // only when splatting vectors.
6003     if (DestElemTy->isFloatingType()) {
6004       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6005       // in two steps: boolean to signed integral, then to floating.
6006       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6007                                                  CK_BooleanToSignedIntegral);
6008       SplattedExpr = CastExprRes.get();
6009       CK = CK_IntegralToFloating;
6010     } else {
6011       CK = CK_BooleanToSignedIntegral;
6012     }
6013   } else {
6014     ExprResult CastExprRes = SplattedExpr;
6015     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6016     if (CastExprRes.isInvalid())
6017       return ExprError();
6018     SplattedExpr = CastExprRes.get();
6019   }
6020   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6021 }
6022
6023 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6024                                     Expr *CastExpr, CastKind &Kind) {
6025   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6026
6027   QualType SrcTy = CastExpr->getType();
6028
6029   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6030   // an ExtVectorType.
6031   // In OpenCL, casts between vectors of different types are not allowed.
6032   // (See OpenCL 6.2).
6033   if (SrcTy->isVectorType()) {
6034     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6035         || (getLangOpts().OpenCL &&
6036             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6037       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6038         << DestTy << SrcTy << R;
6039       return ExprError();
6040     }
6041     Kind = CK_BitCast;
6042     return CastExpr;
6043   }
6044
6045   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6046   // conversion will take place first from scalar to elt type, and then
6047   // splat from elt type to vector.
6048   if (SrcTy->isPointerType())
6049     return Diag(R.getBegin(),
6050                 diag::err_invalid_conversion_between_vector_and_scalar)
6051       << DestTy << SrcTy << R;
6052
6053   Kind = CK_VectorSplat;
6054   return prepareVectorSplat(DestTy, CastExpr);
6055 }
6056
6057 ExprResult
6058 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6059                     Declarator &D, ParsedType &Ty,
6060                     SourceLocation RParenLoc, Expr *CastExpr) {
6061   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6062          "ActOnCastExpr(): missing type or expr");
6063
6064   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6065   if (D.isInvalidType())
6066     return ExprError();
6067
6068   if (getLangOpts().CPlusPlus) {
6069     // Check that there are no default arguments (C++ only).
6070     CheckExtraCXXDefaultArguments(D);
6071   } else {
6072     // Make sure any TypoExprs have been dealt with.
6073     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6074     if (!Res.isUsable())
6075       return ExprError();
6076     CastExpr = Res.get();
6077   }
6078
6079   checkUnusedDeclAttributes(D);
6080
6081   QualType castType = castTInfo->getType();
6082   Ty = CreateParsedType(castType, castTInfo);
6083
6084   bool isVectorLiteral = false;
6085
6086   // Check for an altivec or OpenCL literal,
6087   // i.e. all the elements are integer constants.
6088   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6089   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6090   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6091        && castType->isVectorType() && (PE || PLE)) {
6092     if (PLE && PLE->getNumExprs() == 0) {
6093       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6094       return ExprError();
6095     }
6096     if (PE || PLE->getNumExprs() == 1) {
6097       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6098       if (!E->getType()->isVectorType())
6099         isVectorLiteral = true;
6100     }
6101     else
6102       isVectorLiteral = true;
6103   }
6104
6105   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6106   // then handle it as such.
6107   if (isVectorLiteral)
6108     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6109
6110   // If the Expr being casted is a ParenListExpr, handle it specially.
6111   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6112   // sequence of BinOp comma operators.
6113   if (isa<ParenListExpr>(CastExpr)) {
6114     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6115     if (Result.isInvalid()) return ExprError();
6116     CastExpr = Result.get();
6117   }
6118
6119   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6120       !getSourceManager().isInSystemMacro(LParenLoc))
6121     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6122   
6123   CheckTollFreeBridgeCast(castType, CastExpr);
6124   
6125   CheckObjCBridgeRelatedCast(castType, CastExpr);
6126
6127   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6128
6129   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6130 }
6131
6132 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6133                                     SourceLocation RParenLoc, Expr *E,
6134                                     TypeSourceInfo *TInfo) {
6135   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6136          "Expected paren or paren list expression");
6137
6138   Expr **exprs;
6139   unsigned numExprs;
6140   Expr *subExpr;
6141   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6142   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6143     LiteralLParenLoc = PE->getLParenLoc();
6144     LiteralRParenLoc = PE->getRParenLoc();
6145     exprs = PE->getExprs();
6146     numExprs = PE->getNumExprs();
6147   } else { // isa<ParenExpr> by assertion at function entrance
6148     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6149     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6150     subExpr = cast<ParenExpr>(E)->getSubExpr();
6151     exprs = &subExpr;
6152     numExprs = 1;
6153   }
6154
6155   QualType Ty = TInfo->getType();
6156   assert(Ty->isVectorType() && "Expected vector type");
6157
6158   SmallVector<Expr *, 8> initExprs;
6159   const VectorType *VTy = Ty->getAs<VectorType>();
6160   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6161   
6162   // '(...)' form of vector initialization in AltiVec: the number of
6163   // initializers must be one or must match the size of the vector.
6164   // If a single value is specified in the initializer then it will be
6165   // replicated to all the components of the vector
6166   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6167     // The number of initializers must be one or must match the size of the
6168     // vector. If a single value is specified in the initializer then it will
6169     // be replicated to all the components of the vector
6170     if (numExprs == 1) {
6171       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6172       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6173       if (Literal.isInvalid())
6174         return ExprError();
6175       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6176                                   PrepareScalarCast(Literal, ElemTy));
6177       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6178     }
6179     else if (numExprs < numElems) {
6180       Diag(E->getExprLoc(),
6181            diag::err_incorrect_number_of_vector_initializers);
6182       return ExprError();
6183     }
6184     else
6185       initExprs.append(exprs, exprs + numExprs);
6186   }
6187   else {
6188     // For OpenCL, when the number of initializers is a single value,
6189     // it will be replicated to all components of the vector.
6190     if (getLangOpts().OpenCL &&
6191         VTy->getVectorKind() == VectorType::GenericVector &&
6192         numExprs == 1) {
6193         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6194         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6195         if (Literal.isInvalid())
6196           return ExprError();
6197         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6198                                     PrepareScalarCast(Literal, ElemTy));
6199         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6200     }
6201     
6202     initExprs.append(exprs, exprs + numExprs);
6203   }
6204   // FIXME: This means that pretty-printing the final AST will produce curly
6205   // braces instead of the original commas.
6206   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6207                                                    initExprs, LiteralRParenLoc);
6208   initE->setType(Ty);
6209   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6210 }
6211
6212 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6213 /// the ParenListExpr into a sequence of comma binary operators.
6214 ExprResult
6215 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6216   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6217   if (!E)
6218     return OrigExpr;
6219
6220   ExprResult Result(E->getExpr(0));
6221
6222   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6223     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6224                         E->getExpr(i));
6225
6226   if (Result.isInvalid()) return ExprError();
6227
6228   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6229 }
6230
6231 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6232                                     SourceLocation R,
6233                                     MultiExprArg Val) {
6234   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6235   return expr;
6236 }
6237
6238 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6239 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6240 /// emitted.
6241 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6242                                       SourceLocation QuestionLoc) {
6243   Expr *NullExpr = LHSExpr;
6244   Expr *NonPointerExpr = RHSExpr;
6245   Expr::NullPointerConstantKind NullKind =
6246       NullExpr->isNullPointerConstant(Context,
6247                                       Expr::NPC_ValueDependentIsNotNull);
6248
6249   if (NullKind == Expr::NPCK_NotNull) {
6250     NullExpr = RHSExpr;
6251     NonPointerExpr = LHSExpr;
6252     NullKind =
6253         NullExpr->isNullPointerConstant(Context,
6254                                         Expr::NPC_ValueDependentIsNotNull);
6255   }
6256
6257   if (NullKind == Expr::NPCK_NotNull)
6258     return false;
6259
6260   if (NullKind == Expr::NPCK_ZeroExpression)
6261     return false;
6262
6263   if (NullKind == Expr::NPCK_ZeroLiteral) {
6264     // In this case, check to make sure that we got here from a "NULL"
6265     // string in the source code.
6266     NullExpr = NullExpr->IgnoreParenImpCasts();
6267     SourceLocation loc = NullExpr->getExprLoc();
6268     if (!findMacroSpelling(loc, "NULL"))
6269       return false;
6270   }
6271
6272   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6273   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6274       << NonPointerExpr->getType() << DiagType
6275       << NonPointerExpr->getSourceRange();
6276   return true;
6277 }
6278
6279 /// \brief Return false if the condition expression is valid, true otherwise.
6280 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6281   QualType CondTy = Cond->getType();
6282
6283   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6284   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6285     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6286       << CondTy << Cond->getSourceRange();
6287     return true;
6288   }
6289
6290   // C99 6.5.15p2
6291   if (CondTy->isScalarType()) return false;
6292
6293   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6294     << CondTy << Cond->getSourceRange();
6295   return true;
6296 }
6297
6298 /// \brief Handle when one or both operands are void type.
6299 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6300                                          ExprResult &RHS) {
6301     Expr *LHSExpr = LHS.get();
6302     Expr *RHSExpr = RHS.get();
6303
6304     if (!LHSExpr->getType()->isVoidType())
6305       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6306         << RHSExpr->getSourceRange();
6307     if (!RHSExpr->getType()->isVoidType())
6308       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6309         << LHSExpr->getSourceRange();
6310     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6311     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6312     return S.Context.VoidTy;
6313 }
6314
6315 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6316 /// true otherwise.
6317 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6318                                         QualType PointerTy) {
6319   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6320       !NullExpr.get()->isNullPointerConstant(S.Context,
6321                                             Expr::NPC_ValueDependentIsNull))
6322     return true;
6323
6324   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6325   return false;
6326 }
6327
6328 /// \brief Checks compatibility between two pointers and return the resulting
6329 /// type.
6330 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6331                                                      ExprResult &RHS,
6332                                                      SourceLocation Loc) {
6333   QualType LHSTy = LHS.get()->getType();
6334   QualType RHSTy = RHS.get()->getType();
6335
6336   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6337     // Two identical pointers types are always compatible.
6338     return LHSTy;
6339   }
6340
6341   QualType lhptee, rhptee;
6342
6343   // Get the pointee types.
6344   bool IsBlockPointer = false;
6345   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6346     lhptee = LHSBTy->getPointeeType();
6347     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6348     IsBlockPointer = true;
6349   } else {
6350     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6351     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6352   }
6353
6354   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6355   // differently qualified versions of compatible types, the result type is
6356   // a pointer to an appropriately qualified version of the composite
6357   // type.
6358
6359   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6360   // clause doesn't make sense for our extensions. E.g. address space 2 should
6361   // be incompatible with address space 3: they may live on different devices or
6362   // anything.
6363   Qualifiers lhQual = lhptee.getQualifiers();
6364   Qualifiers rhQual = rhptee.getQualifiers();
6365
6366   unsigned ResultAddrSpace = 0;
6367   unsigned LAddrSpace = lhQual.getAddressSpace();
6368   unsigned RAddrSpace = rhQual.getAddressSpace();
6369   if (S.getLangOpts().OpenCL) {
6370     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6371     // spaces is disallowed.
6372     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6373       ResultAddrSpace = LAddrSpace;
6374     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6375       ResultAddrSpace = RAddrSpace;
6376     else {
6377       S.Diag(Loc,
6378              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6379           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6380           << RHS.get()->getSourceRange();
6381       return QualType();
6382     }
6383   }
6384
6385   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6386   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6387   lhQual.removeCVRQualifiers();
6388   rhQual.removeCVRQualifiers();
6389
6390   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6391   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6392   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6393   // qual types are compatible iff
6394   //  * corresponded types are compatible
6395   //  * CVR qualifiers are equal
6396   //  * address spaces are equal
6397   // Thus for conditional operator we merge CVR and address space unqualified
6398   // pointees and if there is a composite type we return a pointer to it with
6399   // merged qualifiers.
6400   if (S.getLangOpts().OpenCL) {
6401     LHSCastKind = LAddrSpace == ResultAddrSpace
6402                       ? CK_BitCast
6403                       : CK_AddressSpaceConversion;
6404     RHSCastKind = RAddrSpace == ResultAddrSpace
6405                       ? CK_BitCast
6406                       : CK_AddressSpaceConversion;
6407     lhQual.removeAddressSpace();
6408     rhQual.removeAddressSpace();
6409   }
6410
6411   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6412   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6413
6414   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6415
6416   if (CompositeTy.isNull()) {
6417     // In this situation, we assume void* type. No especially good
6418     // reason, but this is what gcc does, and we do have to pick
6419     // to get a consistent AST.
6420     QualType incompatTy;
6421     incompatTy = S.Context.getPointerType(
6422         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6423     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6424     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6425     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6426     // for casts between types with incompatible address space qualifiers.
6427     // For the following code the compiler produces casts between global and
6428     // local address spaces of the corresponded innermost pointees:
6429     // local int *global *a;
6430     // global int *global *b;
6431     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6432     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6433         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6434         << RHS.get()->getSourceRange();
6435     return incompatTy;
6436   }
6437
6438   // The pointer types are compatible.
6439   // In case of OpenCL ResultTy should have the address space qualifier
6440   // which is a superset of address spaces of both the 2nd and the 3rd
6441   // operands of the conditional operator.
6442   QualType ResultTy = [&, ResultAddrSpace]() {
6443     if (S.getLangOpts().OpenCL) {
6444       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6445       CompositeQuals.setAddressSpace(ResultAddrSpace);
6446       return S.Context
6447           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6448           .withCVRQualifiers(MergedCVRQual);
6449     }
6450     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6451   }();
6452   if (IsBlockPointer)
6453     ResultTy = S.Context.getBlockPointerType(ResultTy);
6454   else
6455     ResultTy = S.Context.getPointerType(ResultTy);
6456
6457   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6458   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6459   return ResultTy;
6460 }
6461
6462 /// \brief Return the resulting type when the operands are both block pointers.
6463 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6464                                                           ExprResult &LHS,
6465                                                           ExprResult &RHS,
6466                                                           SourceLocation Loc) {
6467   QualType LHSTy = LHS.get()->getType();
6468   QualType RHSTy = RHS.get()->getType();
6469
6470   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6471     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6472       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6473       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6474       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6475       return destType;
6476     }
6477     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6478       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6479       << RHS.get()->getSourceRange();
6480     return QualType();
6481   }
6482
6483   // We have 2 block pointer types.
6484   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6485 }
6486
6487 /// \brief Return the resulting type when the operands are both pointers.
6488 static QualType
6489 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6490                                             ExprResult &RHS,
6491                                             SourceLocation Loc) {
6492   // get the pointer types
6493   QualType LHSTy = LHS.get()->getType();
6494   QualType RHSTy = RHS.get()->getType();
6495
6496   // get the "pointed to" types
6497   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6498   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6499
6500   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6501   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6502     // Figure out necessary qualifiers (C99 6.5.15p6)
6503     QualType destPointee
6504       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6505     QualType destType = S.Context.getPointerType(destPointee);
6506     // Add qualifiers if necessary.
6507     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6508     // Promote to void*.
6509     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6510     return destType;
6511   }
6512   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6513     QualType destPointee
6514       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6515     QualType destType = S.Context.getPointerType(destPointee);
6516     // Add qualifiers if necessary.
6517     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6518     // Promote to void*.
6519     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6520     return destType;
6521   }
6522
6523   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6524 }
6525
6526 /// \brief Return false if the first expression is not an integer and the second
6527 /// expression is not a pointer, true otherwise.
6528 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6529                                         Expr* PointerExpr, SourceLocation Loc,
6530                                         bool IsIntFirstExpr) {
6531   if (!PointerExpr->getType()->isPointerType() ||
6532       !Int.get()->getType()->isIntegerType())
6533     return false;
6534
6535   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6536   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6537
6538   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6539     << Expr1->getType() << Expr2->getType()
6540     << Expr1->getSourceRange() << Expr2->getSourceRange();
6541   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6542                             CK_IntegralToPointer);
6543   return true;
6544 }
6545
6546 /// \brief Simple conversion between integer and floating point types.
6547 ///
6548 /// Used when handling the OpenCL conditional operator where the
6549 /// condition is a vector while the other operands are scalar.
6550 ///
6551 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6552 /// types are either integer or floating type. Between the two
6553 /// operands, the type with the higher rank is defined as the "result
6554 /// type". The other operand needs to be promoted to the same type. No
6555 /// other type promotion is allowed. We cannot use
6556 /// UsualArithmeticConversions() for this purpose, since it always
6557 /// promotes promotable types.
6558 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6559                                             ExprResult &RHS,
6560                                             SourceLocation QuestionLoc) {
6561   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6562   if (LHS.isInvalid())
6563     return QualType();
6564   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6565   if (RHS.isInvalid())
6566     return QualType();
6567
6568   // For conversion purposes, we ignore any qualifiers.
6569   // For example, "const float" and "float" are equivalent.
6570   QualType LHSType =
6571     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6572   QualType RHSType =
6573     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6574
6575   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6576     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6577       << LHSType << LHS.get()->getSourceRange();
6578     return QualType();
6579   }
6580
6581   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6582     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6583       << RHSType << RHS.get()->getSourceRange();
6584     return QualType();
6585   }
6586
6587   // If both types are identical, no conversion is needed.
6588   if (LHSType == RHSType)
6589     return LHSType;
6590
6591   // Now handle "real" floating types (i.e. float, double, long double).
6592   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6593     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6594                                  /*IsCompAssign = */ false);
6595
6596   // Finally, we have two differing integer types.
6597   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6598   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6599 }
6600
6601 /// \brief Convert scalar operands to a vector that matches the
6602 ///        condition in length.
6603 ///
6604 /// Used when handling the OpenCL conditional operator where the
6605 /// condition is a vector while the other operands are scalar.
6606 ///
6607 /// We first compute the "result type" for the scalar operands
6608 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6609 /// into a vector of that type where the length matches the condition
6610 /// vector type. s6.11.6 requires that the element types of the result
6611 /// and the condition must have the same number of bits.
6612 static QualType
6613 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6614                               QualType CondTy, SourceLocation QuestionLoc) {
6615   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6616   if (ResTy.isNull()) return QualType();
6617
6618   const VectorType *CV = CondTy->getAs<VectorType>();
6619   assert(CV);
6620
6621   // Determine the vector result type
6622   unsigned NumElements = CV->getNumElements();
6623   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6624
6625   // Ensure that all types have the same number of bits
6626   if (S.Context.getTypeSize(CV->getElementType())
6627       != S.Context.getTypeSize(ResTy)) {
6628     // Since VectorTy is created internally, it does not pretty print
6629     // with an OpenCL name. Instead, we just print a description.
6630     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6631     SmallString<64> Str;
6632     llvm::raw_svector_ostream OS(Str);
6633     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6634     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6635       << CondTy << OS.str();
6636     return QualType();
6637   }
6638
6639   // Convert operands to the vector result type
6640   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6641   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6642
6643   return VectorTy;
6644 }
6645
6646 /// \brief Return false if this is a valid OpenCL condition vector
6647 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6648                                        SourceLocation QuestionLoc) {
6649   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6650   // integral type.
6651   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6652   assert(CondTy);
6653   QualType EleTy = CondTy->getElementType();
6654   if (EleTy->isIntegerType()) return false;
6655
6656   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6657     << Cond->getType() << Cond->getSourceRange();
6658   return true;
6659 }
6660
6661 /// \brief Return false if the vector condition type and the vector
6662 ///        result type are compatible.
6663 ///
6664 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6665 /// number of elements, and their element types have the same number
6666 /// of bits.
6667 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6668                               SourceLocation QuestionLoc) {
6669   const VectorType *CV = CondTy->getAs<VectorType>();
6670   const VectorType *RV = VecResTy->getAs<VectorType>();
6671   assert(CV && RV);
6672
6673   if (CV->getNumElements() != RV->getNumElements()) {
6674     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6675       << CondTy << VecResTy;
6676     return true;
6677   }
6678
6679   QualType CVE = CV->getElementType();
6680   QualType RVE = RV->getElementType();
6681
6682   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6683     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6684       << CondTy << VecResTy;
6685     return true;
6686   }
6687
6688   return false;
6689 }
6690
6691 /// \brief Return the resulting type for the conditional operator in
6692 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6693 ///        s6.3.i) when the condition is a vector type.
6694 static QualType
6695 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6696                              ExprResult &LHS, ExprResult &RHS,
6697                              SourceLocation QuestionLoc) {
6698   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6699   if (Cond.isInvalid())
6700     return QualType();
6701   QualType CondTy = Cond.get()->getType();
6702
6703   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6704     return QualType();
6705
6706   // If either operand is a vector then find the vector type of the
6707   // result as specified in OpenCL v1.1 s6.3.i.
6708   if (LHS.get()->getType()->isVectorType() ||
6709       RHS.get()->getType()->isVectorType()) {
6710     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6711                                               /*isCompAssign*/false,
6712                                               /*AllowBothBool*/true,
6713                                               /*AllowBoolConversions*/false);
6714     if (VecResTy.isNull()) return QualType();
6715     // The result type must match the condition type as specified in
6716     // OpenCL v1.1 s6.11.6.
6717     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6718       return QualType();
6719     return VecResTy;
6720   }
6721
6722   // Both operands are scalar.
6723   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6724 }
6725
6726 /// \brief Return true if the Expr is block type
6727 static bool checkBlockType(Sema &S, const Expr *E) {
6728   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6729     QualType Ty = CE->getCallee()->getType();
6730     if (Ty->isBlockPointerType()) {
6731       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6732       return true;
6733     }
6734   }
6735   return false;
6736 }
6737
6738 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6739 /// In that case, LHS = cond.
6740 /// C99 6.5.15
6741 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6742                                         ExprResult &RHS, ExprValueKind &VK,
6743                                         ExprObjectKind &OK,
6744                                         SourceLocation QuestionLoc) {
6745
6746   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6747   if (!LHSResult.isUsable()) return QualType();
6748   LHS = LHSResult;
6749
6750   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6751   if (!RHSResult.isUsable()) return QualType();
6752   RHS = RHSResult;
6753
6754   // C++ is sufficiently different to merit its own checker.
6755   if (getLangOpts().CPlusPlus)
6756     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6757
6758   VK = VK_RValue;
6759   OK = OK_Ordinary;
6760
6761   // The OpenCL operator with a vector condition is sufficiently
6762   // different to merit its own checker.
6763   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6764     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6765
6766   // First, check the condition.
6767   Cond = UsualUnaryConversions(Cond.get());
6768   if (Cond.isInvalid())
6769     return QualType();
6770   if (checkCondition(*this, Cond.get(), QuestionLoc))
6771     return QualType();
6772
6773   // Now check the two expressions.
6774   if (LHS.get()->getType()->isVectorType() ||
6775       RHS.get()->getType()->isVectorType())
6776     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6777                                /*AllowBothBool*/true,
6778                                /*AllowBoolConversions*/false);
6779
6780   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6781   if (LHS.isInvalid() || RHS.isInvalid())
6782     return QualType();
6783
6784   QualType LHSTy = LHS.get()->getType();
6785   QualType RHSTy = RHS.get()->getType();
6786
6787   // Diagnose attempts to convert between __float128 and long double where
6788   // such conversions currently can't be handled.
6789   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6790     Diag(QuestionLoc,
6791          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6792       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6793     return QualType();
6794   }
6795
6796   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6797   // selection operator (?:).
6798   if (getLangOpts().OpenCL &&
6799       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6800     return QualType();
6801   }
6802
6803   // If both operands have arithmetic type, do the usual arithmetic conversions
6804   // to find a common type: C99 6.5.15p3,5.
6805   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6806     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6807     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6808
6809     return ResTy;
6810   }
6811
6812   // If both operands are the same structure or union type, the result is that
6813   // type.
6814   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6815     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6816       if (LHSRT->getDecl() == RHSRT->getDecl())
6817         // "If both the operands have structure or union type, the result has
6818         // that type."  This implies that CV qualifiers are dropped.
6819         return LHSTy.getUnqualifiedType();
6820     // FIXME: Type of conditional expression must be complete in C mode.
6821   }
6822
6823   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6824   // The following || allows only one side to be void (a GCC-ism).
6825   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6826     return checkConditionalVoidType(*this, LHS, RHS);
6827   }
6828
6829   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6830   // the type of the other operand."
6831   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6832   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6833
6834   // All objective-c pointer type analysis is done here.
6835   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6836                                                         QuestionLoc);
6837   if (LHS.isInvalid() || RHS.isInvalid())
6838     return QualType();
6839   if (!compositeType.isNull())
6840     return compositeType;
6841
6842
6843   // Handle block pointer types.
6844   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6845     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6846                                                      QuestionLoc);
6847
6848   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6849   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6850     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6851                                                        QuestionLoc);
6852
6853   // GCC compatibility: soften pointer/integer mismatch.  Note that
6854   // null pointers have been filtered out by this point.
6855   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6856       /*isIntFirstExpr=*/true))
6857     return RHSTy;
6858   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6859       /*isIntFirstExpr=*/false))
6860     return LHSTy;
6861
6862   // Emit a better diagnostic if one of the expressions is a null pointer
6863   // constant and the other is not a pointer type. In this case, the user most
6864   // likely forgot to take the address of the other expression.
6865   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6866     return QualType();
6867
6868   // Otherwise, the operands are not compatible.
6869   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6870     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6871     << RHS.get()->getSourceRange();
6872   return QualType();
6873 }
6874
6875 /// FindCompositeObjCPointerType - Helper method to find composite type of
6876 /// two objective-c pointer types of the two input expressions.
6877 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6878                                             SourceLocation QuestionLoc) {
6879   QualType LHSTy = LHS.get()->getType();
6880   QualType RHSTy = RHS.get()->getType();
6881
6882   // Handle things like Class and struct objc_class*.  Here we case the result
6883   // to the pseudo-builtin, because that will be implicitly cast back to the
6884   // redefinition type if an attempt is made to access its fields.
6885   if (LHSTy->isObjCClassType() &&
6886       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6887     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6888     return LHSTy;
6889   }
6890   if (RHSTy->isObjCClassType() &&
6891       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6892     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6893     return RHSTy;
6894   }
6895   // And the same for struct objc_object* / id
6896   if (LHSTy->isObjCIdType() &&
6897       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6898     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6899     return LHSTy;
6900   }
6901   if (RHSTy->isObjCIdType() &&
6902       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6903     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6904     return RHSTy;
6905   }
6906   // And the same for struct objc_selector* / SEL
6907   if (Context.isObjCSelType(LHSTy) &&
6908       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6909     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6910     return LHSTy;
6911   }
6912   if (Context.isObjCSelType(RHSTy) &&
6913       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6914     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6915     return RHSTy;
6916   }
6917   // Check constraints for Objective-C object pointers types.
6918   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6919
6920     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6921       // Two identical object pointer types are always compatible.
6922       return LHSTy;
6923     }
6924     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6925     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6926     QualType compositeType = LHSTy;
6927
6928     // If both operands are interfaces and either operand can be
6929     // assigned to the other, use that type as the composite
6930     // type. This allows
6931     //   xxx ? (A*) a : (B*) b
6932     // where B is a subclass of A.
6933     //
6934     // Additionally, as for assignment, if either type is 'id'
6935     // allow silent coercion. Finally, if the types are
6936     // incompatible then make sure to use 'id' as the composite
6937     // type so the result is acceptable for sending messages to.
6938
6939     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6940     // It could return the composite type.
6941     if (!(compositeType =
6942           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6943       // Nothing more to do.
6944     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6945       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6946     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6947       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6948     } else if ((LHSTy->isObjCQualifiedIdType() ||
6949                 RHSTy->isObjCQualifiedIdType()) &&
6950                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6951       // Need to handle "id<xx>" explicitly.
6952       // GCC allows qualified id and any Objective-C type to devolve to
6953       // id. Currently localizing to here until clear this should be
6954       // part of ObjCQualifiedIdTypesAreCompatible.
6955       compositeType = Context.getObjCIdType();
6956     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6957       compositeType = Context.getObjCIdType();
6958     } else {
6959       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6960       << LHSTy << RHSTy
6961       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6962       QualType incompatTy = Context.getObjCIdType();
6963       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6964       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6965       return incompatTy;
6966     }
6967     // The object pointer types are compatible.
6968     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6969     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6970     return compositeType;
6971   }
6972   // Check Objective-C object pointer types and 'void *'
6973   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6974     if (getLangOpts().ObjCAutoRefCount) {
6975       // ARC forbids the implicit conversion of object pointers to 'void *',
6976       // so these types are not compatible.
6977       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6978           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6979       LHS = RHS = true;
6980       return QualType();
6981     }
6982     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6983     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6984     QualType destPointee
6985     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6986     QualType destType = Context.getPointerType(destPointee);
6987     // Add qualifiers if necessary.
6988     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6989     // Promote to void*.
6990     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6991     return destType;
6992   }
6993   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6994     if (getLangOpts().ObjCAutoRefCount) {
6995       // ARC forbids the implicit conversion of object pointers to 'void *',
6996       // so these types are not compatible.
6997       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6998           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6999       LHS = RHS = true;
7000       return QualType();
7001     }
7002     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7003     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7004     QualType destPointee
7005     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7006     QualType destType = Context.getPointerType(destPointee);
7007     // Add qualifiers if necessary.
7008     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7009     // Promote to void*.
7010     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7011     return destType;
7012   }
7013   return QualType();
7014 }
7015
7016 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7017 /// ParenRange in parentheses.
7018 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7019                                const PartialDiagnostic &Note,
7020                                SourceRange ParenRange) {
7021   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7022   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7023       EndLoc.isValid()) {
7024     Self.Diag(Loc, Note)
7025       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7026       << FixItHint::CreateInsertion(EndLoc, ")");
7027   } else {
7028     // We can't display the parentheses, so just show the bare note.
7029     Self.Diag(Loc, Note) << ParenRange;
7030   }
7031 }
7032
7033 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7034   return BinaryOperator::isAdditiveOp(Opc) ||
7035          BinaryOperator::isMultiplicativeOp(Opc) ||
7036          BinaryOperator::isShiftOp(Opc);
7037 }
7038
7039 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7040 /// expression, either using a built-in or overloaded operator,
7041 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7042 /// expression.
7043 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7044                                    Expr **RHSExprs) {
7045   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7046   E = E->IgnoreImpCasts();
7047   E = E->IgnoreConversionOperator();
7048   E = E->IgnoreImpCasts();
7049
7050   // Built-in binary operator.
7051   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7052     if (IsArithmeticOp(OP->getOpcode())) {
7053       *Opcode = OP->getOpcode();
7054       *RHSExprs = OP->getRHS();
7055       return true;
7056     }
7057   }
7058
7059   // Overloaded operator.
7060   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7061     if (Call->getNumArgs() != 2)
7062       return false;
7063
7064     // Make sure this is really a binary operator that is safe to pass into
7065     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7066     OverloadedOperatorKind OO = Call->getOperator();
7067     if (OO < OO_Plus || OO > OO_Arrow ||
7068         OO == OO_PlusPlus || OO == OO_MinusMinus)
7069       return false;
7070
7071     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7072     if (IsArithmeticOp(OpKind)) {
7073       *Opcode = OpKind;
7074       *RHSExprs = Call->getArg(1);
7075       return true;
7076     }
7077   }
7078
7079   return false;
7080 }
7081
7082 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7083 /// or is a logical expression such as (x==y) which has int type, but is
7084 /// commonly interpreted as boolean.
7085 static bool ExprLooksBoolean(Expr *E) {
7086   E = E->IgnoreParenImpCasts();
7087
7088   if (E->getType()->isBooleanType())
7089     return true;
7090   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7091     return OP->isComparisonOp() || OP->isLogicalOp();
7092   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7093     return OP->getOpcode() == UO_LNot;
7094   if (E->getType()->isPointerType())
7095     return true;
7096
7097   return false;
7098 }
7099
7100 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7101 /// and binary operator are mixed in a way that suggests the programmer assumed
7102 /// the conditional operator has higher precedence, for example:
7103 /// "int x = a + someBinaryCondition ? 1 : 2".
7104 static void DiagnoseConditionalPrecedence(Sema &Self,
7105                                           SourceLocation OpLoc,
7106                                           Expr *Condition,
7107                                           Expr *LHSExpr,
7108                                           Expr *RHSExpr) {
7109   BinaryOperatorKind CondOpcode;
7110   Expr *CondRHS;
7111
7112   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7113     return;
7114   if (!ExprLooksBoolean(CondRHS))
7115     return;
7116
7117   // The condition is an arithmetic binary expression, with a right-
7118   // hand side that looks boolean, so warn.
7119
7120   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7121       << Condition->getSourceRange()
7122       << BinaryOperator::getOpcodeStr(CondOpcode);
7123
7124   SuggestParentheses(Self, OpLoc,
7125     Self.PDiag(diag::note_precedence_silence)
7126       << BinaryOperator::getOpcodeStr(CondOpcode),
7127     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7128
7129   SuggestParentheses(Self, OpLoc,
7130     Self.PDiag(diag::note_precedence_conditional_first),
7131     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7132 }
7133
7134 /// Compute the nullability of a conditional expression.
7135 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7136                                               QualType LHSTy, QualType RHSTy,
7137                                               ASTContext &Ctx) {
7138   if (!ResTy->isAnyPointerType())
7139     return ResTy;
7140
7141   auto GetNullability = [&Ctx](QualType Ty) {
7142     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7143     if (Kind)
7144       return *Kind;
7145     return NullabilityKind::Unspecified;
7146   };
7147
7148   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7149   NullabilityKind MergedKind;
7150
7151   // Compute nullability of a binary conditional expression.
7152   if (IsBin) {
7153     if (LHSKind == NullabilityKind::NonNull)
7154       MergedKind = NullabilityKind::NonNull;
7155     else
7156       MergedKind = RHSKind;
7157   // Compute nullability of a normal conditional expression.
7158   } else {
7159     if (LHSKind == NullabilityKind::Nullable ||
7160         RHSKind == NullabilityKind::Nullable)
7161       MergedKind = NullabilityKind::Nullable;
7162     else if (LHSKind == NullabilityKind::NonNull)
7163       MergedKind = RHSKind;
7164     else if (RHSKind == NullabilityKind::NonNull)
7165       MergedKind = LHSKind;
7166     else
7167       MergedKind = NullabilityKind::Unspecified;
7168   }
7169
7170   // Return if ResTy already has the correct nullability.
7171   if (GetNullability(ResTy) == MergedKind)
7172     return ResTy;
7173
7174   // Strip all nullability from ResTy.
7175   while (ResTy->getNullability(Ctx))
7176     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7177
7178   // Create a new AttributedType with the new nullability kind.
7179   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7180   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7181 }
7182
7183 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7184 /// in the case of a the GNU conditional expr extension.
7185 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7186                                     SourceLocation ColonLoc,
7187                                     Expr *CondExpr, Expr *LHSExpr,
7188                                     Expr *RHSExpr) {
7189   if (!getLangOpts().CPlusPlus) {
7190     // C cannot handle TypoExpr nodes in the condition because it
7191     // doesn't handle dependent types properly, so make sure any TypoExprs have
7192     // been dealt with before checking the operands.
7193     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7194     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7195     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7196
7197     if (!CondResult.isUsable())
7198       return ExprError();
7199
7200     if (LHSExpr) {
7201       if (!LHSResult.isUsable())
7202         return ExprError();
7203     }
7204
7205     if (!RHSResult.isUsable())
7206       return ExprError();
7207
7208     CondExpr = CondResult.get();
7209     LHSExpr = LHSResult.get();
7210     RHSExpr = RHSResult.get();
7211   }
7212
7213   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7214   // was the condition.
7215   OpaqueValueExpr *opaqueValue = nullptr;
7216   Expr *commonExpr = nullptr;
7217   if (!LHSExpr) {
7218     commonExpr = CondExpr;
7219     // Lower out placeholder types first.  This is important so that we don't
7220     // try to capture a placeholder. This happens in few cases in C++; such
7221     // as Objective-C++'s dictionary subscripting syntax.
7222     if (commonExpr->hasPlaceholderType()) {
7223       ExprResult result = CheckPlaceholderExpr(commonExpr);
7224       if (!result.isUsable()) return ExprError();
7225       commonExpr = result.get();
7226     }
7227     // We usually want to apply unary conversions *before* saving, except
7228     // in the special case of a C++ l-value conditional.
7229     if (!(getLangOpts().CPlusPlus
7230           && !commonExpr->isTypeDependent()
7231           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7232           && commonExpr->isGLValue()
7233           && commonExpr->isOrdinaryOrBitFieldObject()
7234           && RHSExpr->isOrdinaryOrBitFieldObject()
7235           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7236       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7237       if (commonRes.isInvalid())
7238         return ExprError();
7239       commonExpr = commonRes.get();
7240     }
7241
7242     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7243                                                 commonExpr->getType(),
7244                                                 commonExpr->getValueKind(),
7245                                                 commonExpr->getObjectKind(),
7246                                                 commonExpr);
7247     LHSExpr = CondExpr = opaqueValue;
7248   }
7249
7250   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7251   ExprValueKind VK = VK_RValue;
7252   ExprObjectKind OK = OK_Ordinary;
7253   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7254   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
7255                                              VK, OK, QuestionLoc);
7256   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7257       RHS.isInvalid())
7258     return ExprError();
7259
7260   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7261                                 RHS.get());
7262
7263   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7264
7265   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7266                                          Context);
7267
7268   if (!commonExpr)
7269     return new (Context)
7270         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7271                             RHS.get(), result, VK, OK);
7272
7273   return new (Context) BinaryConditionalOperator(
7274       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7275       ColonLoc, result, VK, OK);
7276 }
7277
7278 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7279 // being closely modeled after the C99 spec:-). The odd characteristic of this
7280 // routine is it effectively iqnores the qualifiers on the top level pointee.
7281 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7282 // FIXME: add a couple examples in this comment.
7283 static Sema::AssignConvertType
7284 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7285   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7286   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7287
7288   // get the "pointed to" type (ignoring qualifiers at the top level)
7289   const Type *lhptee, *rhptee;
7290   Qualifiers lhq, rhq;
7291   std::tie(lhptee, lhq) =
7292       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7293   std::tie(rhptee, rhq) =
7294       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7295
7296   Sema::AssignConvertType ConvTy = Sema::Compatible;
7297
7298   // C99 6.5.16.1p1: This following citation is common to constraints
7299   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7300   // qualifiers of the type *pointed to* by the right;
7301
7302   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7303   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7304       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7305     // Ignore lifetime for further calculation.
7306     lhq.removeObjCLifetime();
7307     rhq.removeObjCLifetime();
7308   }
7309
7310   if (!lhq.compatiblyIncludes(rhq)) {
7311     // Treat address-space mismatches as fatal.  TODO: address subspaces
7312     if (!lhq.isAddressSpaceSupersetOf(rhq))
7313       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7314
7315     // It's okay to add or remove GC or lifetime qualifiers when converting to
7316     // and from void*.
7317     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7318                         .compatiblyIncludes(
7319                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7320              && (lhptee->isVoidType() || rhptee->isVoidType()))
7321       ; // keep old
7322
7323     // Treat lifetime mismatches as fatal.
7324     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7325       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7326     
7327     // For GCC/MS compatibility, other qualifier mismatches are treated
7328     // as still compatible in C.
7329     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7330   }
7331
7332   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7333   // incomplete type and the other is a pointer to a qualified or unqualified
7334   // version of void...
7335   if (lhptee->isVoidType()) {
7336     if (rhptee->isIncompleteOrObjectType())
7337       return ConvTy;
7338
7339     // As an extension, we allow cast to/from void* to function pointer.
7340     assert(rhptee->isFunctionType());
7341     return Sema::FunctionVoidPointer;
7342   }
7343
7344   if (rhptee->isVoidType()) {
7345     if (lhptee->isIncompleteOrObjectType())
7346       return ConvTy;
7347
7348     // As an extension, we allow cast to/from void* to function pointer.
7349     assert(lhptee->isFunctionType());
7350     return Sema::FunctionVoidPointer;
7351   }
7352
7353   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7354   // unqualified versions of compatible types, ...
7355   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7356   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7357     // Check if the pointee types are compatible ignoring the sign.
7358     // We explicitly check for char so that we catch "char" vs
7359     // "unsigned char" on systems where "char" is unsigned.
7360     if (lhptee->isCharType())
7361       ltrans = S.Context.UnsignedCharTy;
7362     else if (lhptee->hasSignedIntegerRepresentation())
7363       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7364
7365     if (rhptee->isCharType())
7366       rtrans = S.Context.UnsignedCharTy;
7367     else if (rhptee->hasSignedIntegerRepresentation())
7368       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7369
7370     if (ltrans == rtrans) {
7371       // Types are compatible ignoring the sign. Qualifier incompatibility
7372       // takes priority over sign incompatibility because the sign
7373       // warning can be disabled.
7374       if (ConvTy != Sema::Compatible)
7375         return ConvTy;
7376
7377       return Sema::IncompatiblePointerSign;
7378     }
7379
7380     // If we are a multi-level pointer, it's possible that our issue is simply
7381     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7382     // the eventual target type is the same and the pointers have the same
7383     // level of indirection, this must be the issue.
7384     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7385       do {
7386         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7387         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7388       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7389
7390       if (lhptee == rhptee)
7391         return Sema::IncompatibleNestedPointerQualifiers;
7392     }
7393
7394     // General pointer incompatibility takes priority over qualifiers.
7395     return Sema::IncompatiblePointer;
7396   }
7397   if (!S.getLangOpts().CPlusPlus &&
7398       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7399     return Sema::IncompatiblePointer;
7400   return ConvTy;
7401 }
7402
7403 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7404 /// block pointer types are compatible or whether a block and normal pointer
7405 /// are compatible. It is more restrict than comparing two function pointer
7406 // types.
7407 static Sema::AssignConvertType
7408 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7409                                     QualType RHSType) {
7410   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7411   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7412
7413   QualType lhptee, rhptee;
7414
7415   // get the "pointed to" type (ignoring qualifiers at the top level)
7416   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7417   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7418
7419   // In C++, the types have to match exactly.
7420   if (S.getLangOpts().CPlusPlus)
7421     return Sema::IncompatibleBlockPointer;
7422
7423   Sema::AssignConvertType ConvTy = Sema::Compatible;
7424
7425   // For blocks we enforce that qualifiers are identical.
7426   Qualifiers LQuals = lhptee.getLocalQualifiers();
7427   Qualifiers RQuals = rhptee.getLocalQualifiers();
7428   if (S.getLangOpts().OpenCL) {
7429     LQuals.removeAddressSpace();
7430     RQuals.removeAddressSpace();
7431   }
7432   if (LQuals != RQuals)
7433     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7434
7435   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7436   // assignment.
7437   // The current behavior is similar to C++ lambdas. A block might be
7438   // assigned to a variable iff its return type and parameters are compatible
7439   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7440   // an assignment. Presumably it should behave in way that a function pointer
7441   // assignment does in C, so for each parameter and return type:
7442   //  * CVR and address space of LHS should be a superset of CVR and address
7443   //  space of RHS.
7444   //  * unqualified types should be compatible.
7445   if (S.getLangOpts().OpenCL) {
7446     if (!S.Context.typesAreBlockPointerCompatible(
7447             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7448             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7449       return Sema::IncompatibleBlockPointer;
7450   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7451     return Sema::IncompatibleBlockPointer;
7452
7453   return ConvTy;
7454 }
7455
7456 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7457 /// for assignment compatibility.
7458 static Sema::AssignConvertType
7459 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7460                                    QualType RHSType) {
7461   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7462   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7463
7464   if (LHSType->isObjCBuiltinType()) {
7465     // Class is not compatible with ObjC object pointers.
7466     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7467         !RHSType->isObjCQualifiedClassType())
7468       return Sema::IncompatiblePointer;
7469     return Sema::Compatible;
7470   }
7471   if (RHSType->isObjCBuiltinType()) {
7472     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7473         !LHSType->isObjCQualifiedClassType())
7474       return Sema::IncompatiblePointer;
7475     return Sema::Compatible;
7476   }
7477   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7478   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7479
7480   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7481       // make an exception for id<P>
7482       !LHSType->isObjCQualifiedIdType())
7483     return Sema::CompatiblePointerDiscardsQualifiers;
7484
7485   if (S.Context.typesAreCompatible(LHSType, RHSType))
7486     return Sema::Compatible;
7487   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7488     return Sema::IncompatibleObjCQualifiedId;
7489   return Sema::IncompatiblePointer;
7490 }
7491
7492 Sema::AssignConvertType
7493 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7494                                  QualType LHSType, QualType RHSType) {
7495   // Fake up an opaque expression.  We don't actually care about what
7496   // cast operations are required, so if CheckAssignmentConstraints
7497   // adds casts to this they'll be wasted, but fortunately that doesn't
7498   // usually happen on valid code.
7499   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7500   ExprResult RHSPtr = &RHSExpr;
7501   CastKind K = CK_Invalid;
7502
7503   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7504 }
7505
7506 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7507 /// has code to accommodate several GCC extensions when type checking
7508 /// pointers. Here are some objectionable examples that GCC considers warnings:
7509 ///
7510 ///  int a, *pint;
7511 ///  short *pshort;
7512 ///  struct foo *pfoo;
7513 ///
7514 ///  pint = pshort; // warning: assignment from incompatible pointer type
7515 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7516 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7517 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7518 ///
7519 /// As a result, the code for dealing with pointers is more complex than the
7520 /// C99 spec dictates.
7521 ///
7522 /// Sets 'Kind' for any result kind except Incompatible.
7523 Sema::AssignConvertType
7524 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7525                                  CastKind &Kind, bool ConvertRHS) {
7526   QualType RHSType = RHS.get()->getType();
7527   QualType OrigLHSType = LHSType;
7528
7529   // Get canonical types.  We're not formatting these types, just comparing
7530   // them.
7531   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7532   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7533
7534   // Common case: no conversion required.
7535   if (LHSType == RHSType) {
7536     Kind = CK_NoOp;
7537     return Compatible;
7538   }
7539
7540   // If we have an atomic type, try a non-atomic assignment, then just add an
7541   // atomic qualification step.
7542   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7543     Sema::AssignConvertType result =
7544       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7545     if (result != Compatible)
7546       return result;
7547     if (Kind != CK_NoOp && ConvertRHS)
7548       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7549     Kind = CK_NonAtomicToAtomic;
7550     return Compatible;
7551   }
7552
7553   // If the left-hand side is a reference type, then we are in a
7554   // (rare!) case where we've allowed the use of references in C,
7555   // e.g., as a parameter type in a built-in function. In this case,
7556   // just make sure that the type referenced is compatible with the
7557   // right-hand side type. The caller is responsible for adjusting
7558   // LHSType so that the resulting expression does not have reference
7559   // type.
7560   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7561     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7562       Kind = CK_LValueBitCast;
7563       return Compatible;
7564     }
7565     return Incompatible;
7566   }
7567
7568   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7569   // to the same ExtVector type.
7570   if (LHSType->isExtVectorType()) {
7571     if (RHSType->isExtVectorType())
7572       return Incompatible;
7573     if (RHSType->isArithmeticType()) {
7574       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7575       if (ConvertRHS)
7576         RHS = prepareVectorSplat(LHSType, RHS.get());
7577       Kind = CK_VectorSplat;
7578       return Compatible;
7579     }
7580   }
7581
7582   // Conversions to or from vector type.
7583   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7584     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7585       // Allow assignments of an AltiVec vector type to an equivalent GCC
7586       // vector type and vice versa
7587       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7588         Kind = CK_BitCast;
7589         return Compatible;
7590       }
7591
7592       // If we are allowing lax vector conversions, and LHS and RHS are both
7593       // vectors, the total size only needs to be the same. This is a bitcast;
7594       // no bits are changed but the result type is different.
7595       if (isLaxVectorConversion(RHSType, LHSType)) {
7596         Kind = CK_BitCast;
7597         return IncompatibleVectors;
7598       }
7599     }
7600
7601     // When the RHS comes from another lax conversion (e.g. binops between
7602     // scalars and vectors) the result is canonicalized as a vector. When the
7603     // LHS is also a vector, the lax is allowed by the condition above. Handle
7604     // the case where LHS is a scalar.
7605     if (LHSType->isScalarType()) {
7606       const VectorType *VecType = RHSType->getAs<VectorType>();
7607       if (VecType && VecType->getNumElements() == 1 &&
7608           isLaxVectorConversion(RHSType, LHSType)) {
7609         ExprResult *VecExpr = &RHS;
7610         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7611         Kind = CK_BitCast;
7612         return Compatible;
7613       }
7614     }
7615
7616     return Incompatible;
7617   }
7618
7619   // Diagnose attempts to convert between __float128 and long double where
7620   // such conversions currently can't be handled.
7621   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7622     return Incompatible;
7623
7624   // Arithmetic conversions.
7625   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7626       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7627     if (ConvertRHS)
7628       Kind = PrepareScalarCast(RHS, LHSType);
7629     return Compatible;
7630   }
7631
7632   // Conversions to normal pointers.
7633   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7634     // U* -> T*
7635     if (isa<PointerType>(RHSType)) {
7636       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7637       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7638       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7639       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7640     }
7641
7642     // int -> T*
7643     if (RHSType->isIntegerType()) {
7644       Kind = CK_IntegralToPointer; // FIXME: null?
7645       return IntToPointer;
7646     }
7647
7648     // C pointers are not compatible with ObjC object pointers,
7649     // with two exceptions:
7650     if (isa<ObjCObjectPointerType>(RHSType)) {
7651       //  - conversions to void*
7652       if (LHSPointer->getPointeeType()->isVoidType()) {
7653         Kind = CK_BitCast;
7654         return Compatible;
7655       }
7656
7657       //  - conversions from 'Class' to the redefinition type
7658       if (RHSType->isObjCClassType() &&
7659           Context.hasSameType(LHSType, 
7660                               Context.getObjCClassRedefinitionType())) {
7661         Kind = CK_BitCast;
7662         return Compatible;
7663       }
7664
7665       Kind = CK_BitCast;
7666       return IncompatiblePointer;
7667     }
7668
7669     // U^ -> void*
7670     if (RHSType->getAs<BlockPointerType>()) {
7671       if (LHSPointer->getPointeeType()->isVoidType()) {
7672         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7673         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7674                                   ->getPointeeType()
7675                                   .getAddressSpace();
7676         Kind =
7677             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7678         return Compatible;
7679       }
7680     }
7681
7682     return Incompatible;
7683   }
7684
7685   // Conversions to block pointers.
7686   if (isa<BlockPointerType>(LHSType)) {
7687     // U^ -> T^
7688     if (RHSType->isBlockPointerType()) {
7689       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7690                                 ->getPointeeType()
7691                                 .getAddressSpace();
7692       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7693                                 ->getPointeeType()
7694                                 .getAddressSpace();
7695       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7696       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7697     }
7698
7699     // int or null -> T^
7700     if (RHSType->isIntegerType()) {
7701       Kind = CK_IntegralToPointer; // FIXME: null
7702       return IntToBlockPointer;
7703     }
7704
7705     // id -> T^
7706     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7707       Kind = CK_AnyPointerToBlockPointerCast;
7708       return Compatible;
7709     }
7710
7711     // void* -> T^
7712     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7713       if (RHSPT->getPointeeType()->isVoidType()) {
7714         Kind = CK_AnyPointerToBlockPointerCast;
7715         return Compatible;
7716       }
7717
7718     return Incompatible;
7719   }
7720
7721   // Conversions to Objective-C pointers.
7722   if (isa<ObjCObjectPointerType>(LHSType)) {
7723     // A* -> B*
7724     if (RHSType->isObjCObjectPointerType()) {
7725       Kind = CK_BitCast;
7726       Sema::AssignConvertType result = 
7727         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7728       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7729           result == Compatible && 
7730           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7731         result = IncompatibleObjCWeakRef;
7732       return result;
7733     }
7734
7735     // int or null -> A*
7736     if (RHSType->isIntegerType()) {
7737       Kind = CK_IntegralToPointer; // FIXME: null
7738       return IntToPointer;
7739     }
7740
7741     // In general, C pointers are not compatible with ObjC object pointers,
7742     // with two exceptions:
7743     if (isa<PointerType>(RHSType)) {
7744       Kind = CK_CPointerToObjCPointerCast;
7745
7746       //  - conversions from 'void*'
7747       if (RHSType->isVoidPointerType()) {
7748         return Compatible;
7749       }
7750
7751       //  - conversions to 'Class' from its redefinition type
7752       if (LHSType->isObjCClassType() &&
7753           Context.hasSameType(RHSType, 
7754                               Context.getObjCClassRedefinitionType())) {
7755         return Compatible;
7756       }
7757
7758       return IncompatiblePointer;
7759     }
7760
7761     // Only under strict condition T^ is compatible with an Objective-C pointer.
7762     if (RHSType->isBlockPointerType() && 
7763         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7764       if (ConvertRHS)
7765         maybeExtendBlockObject(RHS);
7766       Kind = CK_BlockPointerToObjCPointerCast;
7767       return Compatible;
7768     }
7769
7770     return Incompatible;
7771   }
7772
7773   // Conversions from pointers that are not covered by the above.
7774   if (isa<PointerType>(RHSType)) {
7775     // T* -> _Bool
7776     if (LHSType == Context.BoolTy) {
7777       Kind = CK_PointerToBoolean;
7778       return Compatible;
7779     }
7780
7781     // T* -> int
7782     if (LHSType->isIntegerType()) {
7783       Kind = CK_PointerToIntegral;
7784       return PointerToInt;
7785     }
7786
7787     return Incompatible;
7788   }
7789
7790   // Conversions from Objective-C pointers that are not covered by the above.
7791   if (isa<ObjCObjectPointerType>(RHSType)) {
7792     // T* -> _Bool
7793     if (LHSType == Context.BoolTy) {
7794       Kind = CK_PointerToBoolean;
7795       return Compatible;
7796     }
7797
7798     // T* -> int
7799     if (LHSType->isIntegerType()) {
7800       Kind = CK_PointerToIntegral;
7801       return PointerToInt;
7802     }
7803
7804     return Incompatible;
7805   }
7806
7807   // struct A -> struct B
7808   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7809     if (Context.typesAreCompatible(LHSType, RHSType)) {
7810       Kind = CK_NoOp;
7811       return Compatible;
7812     }
7813   }
7814
7815   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7816     Kind = CK_IntToOCLSampler;
7817     return Compatible;
7818   }
7819
7820   return Incompatible;
7821 }
7822
7823 /// \brief Constructs a transparent union from an expression that is
7824 /// used to initialize the transparent union.
7825 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7826                                       ExprResult &EResult, QualType UnionType,
7827                                       FieldDecl *Field) {
7828   // Build an initializer list that designates the appropriate member
7829   // of the transparent union.
7830   Expr *E = EResult.get();
7831   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7832                                                    E, SourceLocation());
7833   Initializer->setType(UnionType);
7834   Initializer->setInitializedFieldInUnion(Field);
7835
7836   // Build a compound literal constructing a value of the transparent
7837   // union type from this initializer list.
7838   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7839   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7840                                         VK_RValue, Initializer, false);
7841 }
7842
7843 Sema::AssignConvertType
7844 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7845                                                ExprResult &RHS) {
7846   QualType RHSType = RHS.get()->getType();
7847
7848   // If the ArgType is a Union type, we want to handle a potential
7849   // transparent_union GCC extension.
7850   const RecordType *UT = ArgType->getAsUnionType();
7851   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7852     return Incompatible;
7853
7854   // The field to initialize within the transparent union.
7855   RecordDecl *UD = UT->getDecl();
7856   FieldDecl *InitField = nullptr;
7857   // It's compatible if the expression matches any of the fields.
7858   for (auto *it : UD->fields()) {
7859     if (it->getType()->isPointerType()) {
7860       // If the transparent union contains a pointer type, we allow:
7861       // 1) void pointer
7862       // 2) null pointer constant
7863       if (RHSType->isPointerType())
7864         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7865           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7866           InitField = it;
7867           break;
7868         }
7869
7870       if (RHS.get()->isNullPointerConstant(Context,
7871                                            Expr::NPC_ValueDependentIsNull)) {
7872         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7873                                 CK_NullToPointer);
7874         InitField = it;
7875         break;
7876       }
7877     }
7878
7879     CastKind Kind = CK_Invalid;
7880     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7881           == Compatible) {
7882       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7883       InitField = it;
7884       break;
7885     }
7886   }
7887
7888   if (!InitField)
7889     return Incompatible;
7890
7891   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7892   return Compatible;
7893 }
7894
7895 Sema::AssignConvertType
7896 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7897                                        bool Diagnose,
7898                                        bool DiagnoseCFAudited,
7899                                        bool ConvertRHS) {
7900   // We need to be able to tell the caller whether we diagnosed a problem, if
7901   // they ask us to issue diagnostics.
7902   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7903
7904   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7905   // we can't avoid *all* modifications at the moment, so we need some somewhere
7906   // to put the updated value.
7907   ExprResult LocalRHS = CallerRHS;
7908   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7909
7910   if (getLangOpts().CPlusPlus) {
7911     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7912       // C++ 5.17p3: If the left operand is not of class type, the
7913       // expression is implicitly converted (C++ 4) to the
7914       // cv-unqualified type of the left operand.
7915       QualType RHSType = RHS.get()->getType();
7916       if (Diagnose) {
7917         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7918                                         AA_Assigning);
7919       } else {
7920         ImplicitConversionSequence ICS =
7921             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7922                                   /*SuppressUserConversions=*/false,
7923                                   /*AllowExplicit=*/false,
7924                                   /*InOverloadResolution=*/false,
7925                                   /*CStyle=*/false,
7926                                   /*AllowObjCWritebackConversion=*/false);
7927         if (ICS.isFailure())
7928           return Incompatible;
7929         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7930                                         ICS, AA_Assigning);
7931       }
7932       if (RHS.isInvalid())
7933         return Incompatible;
7934       Sema::AssignConvertType result = Compatible;
7935       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7936           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7937         result = IncompatibleObjCWeakRef;
7938       return result;
7939     }
7940
7941     // FIXME: Currently, we fall through and treat C++ classes like C
7942     // structures.
7943     // FIXME: We also fall through for atomics; not sure what should
7944     // happen there, though.
7945   } else if (RHS.get()->getType() == Context.OverloadTy) {
7946     // As a set of extensions to C, we support overloading on functions. These
7947     // functions need to be resolved here.
7948     DeclAccessPair DAP;
7949     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7950             RHS.get(), LHSType, /*Complain=*/false, DAP))
7951       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7952     else
7953       return Incompatible;
7954   }
7955
7956   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7957   // a null pointer constant.
7958   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7959        LHSType->isBlockPointerType()) &&
7960       RHS.get()->isNullPointerConstant(Context,
7961                                        Expr::NPC_ValueDependentIsNull)) {
7962     if (Diagnose || ConvertRHS) {
7963       CastKind Kind;
7964       CXXCastPath Path;
7965       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7966                              /*IgnoreBaseAccess=*/false, Diagnose);
7967       if (ConvertRHS)
7968         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7969     }
7970     return Compatible;
7971   }
7972
7973   // This check seems unnatural, however it is necessary to ensure the proper
7974   // conversion of functions/arrays. If the conversion were done for all
7975   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7976   // expressions that suppress this implicit conversion (&, sizeof).
7977   //
7978   // Suppress this for references: C++ 8.5.3p5.
7979   if (!LHSType->isReferenceType()) {
7980     // FIXME: We potentially allocate here even if ConvertRHS is false.
7981     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7982     if (RHS.isInvalid())
7983       return Incompatible;
7984   }
7985
7986   Expr *PRE = RHS.get()->IgnoreParenCasts();
7987   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7988     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7989     if (PDecl && !PDecl->hasDefinition()) {
7990       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7991       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7992     }
7993   }
7994   
7995   CastKind Kind = CK_Invalid;
7996   Sema::AssignConvertType result =
7997     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7998
7999   // C99 6.5.16.1p2: The value of the right operand is converted to the
8000   // type of the assignment expression.
8001   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8002   // so that we can use references in built-in functions even in C.
8003   // The getNonReferenceType() call makes sure that the resulting expression
8004   // does not have reference type.
8005   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8006     QualType Ty = LHSType.getNonLValueExprType(Context);
8007     Expr *E = RHS.get();
8008
8009     // Check for various Objective-C errors. If we are not reporting
8010     // diagnostics and just checking for errors, e.g., during overload
8011     // resolution, return Incompatible to indicate the failure.
8012     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8013         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8014                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8015       if (!Diagnose)
8016         return Incompatible;
8017     }
8018     if (getLangOpts().ObjC1 &&
8019         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8020                                            E->getType(), E, Diagnose) ||
8021          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8022       if (!Diagnose)
8023         return Incompatible;
8024       // Replace the expression with a corrected version and continue so we
8025       // can find further errors.
8026       RHS = E;
8027       return Compatible;
8028     }
8029     
8030     if (ConvertRHS)
8031       RHS = ImpCastExprToType(E, Ty, Kind);
8032   }
8033   return result;
8034 }
8035
8036 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8037                                ExprResult &RHS) {
8038   Diag(Loc, diag::err_typecheck_invalid_operands)
8039     << LHS.get()->getType() << RHS.get()->getType()
8040     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8041   return QualType();
8042 }
8043
8044 // Diagnose cases where a scalar was implicitly converted to a vector and
8045 // diagnose the underlying types. Otherwise, diagnose the error
8046 // as invalid vector logical operands for non-C++ cases.
8047 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8048                                             ExprResult &RHS) {
8049   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8050   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8051
8052   bool LHSNatVec = LHSType->isVectorType();
8053   bool RHSNatVec = RHSType->isVectorType();
8054
8055   if (!(LHSNatVec && RHSNatVec)) {
8056     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8057     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8058     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8059         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8060         << Vector->getSourceRange();
8061     return QualType();
8062   }
8063
8064   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8065       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8066       << RHS.get()->getSourceRange();
8067
8068   return QualType();
8069 }
8070
8071 /// Try to convert a value of non-vector type to a vector type by converting
8072 /// the type to the element type of the vector and then performing a splat.
8073 /// If the language is OpenCL, we only use conversions that promote scalar
8074 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8075 /// for float->int.
8076 ///
8077 /// OpenCL V2.0 6.2.6.p2:
8078 /// An error shall occur if any scalar operand type has greater rank
8079 /// than the type of the vector element.
8080 ///
8081 /// \param scalar - if non-null, actually perform the conversions
8082 /// \return true if the operation fails (but without diagnosing the failure)
8083 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8084                                      QualType scalarTy,
8085                                      QualType vectorEltTy,
8086                                      QualType vectorTy,
8087                                      unsigned &DiagID) {
8088   // The conversion to apply to the scalar before splatting it,
8089   // if necessary.
8090   CastKind scalarCast = CK_Invalid;
8091   
8092   if (vectorEltTy->isIntegralType(S.Context)) {
8093     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8094         (scalarTy->isIntegerType() &&
8095          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8096       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8097       return true;
8098     }
8099     if (!scalarTy->isIntegralType(S.Context))
8100       return true;
8101     scalarCast = CK_IntegralCast;
8102   } else if (vectorEltTy->isRealFloatingType()) {
8103     if (scalarTy->isRealFloatingType()) {
8104       if (S.getLangOpts().OpenCL &&
8105           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8106         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8107         return true;
8108       }
8109       scalarCast = CK_FloatingCast;
8110     }
8111     else if (scalarTy->isIntegralType(S.Context))
8112       scalarCast = CK_IntegralToFloating;
8113     else
8114       return true;
8115   } else {
8116     return true;
8117   }
8118
8119   // Adjust scalar if desired.
8120   if (scalar) {
8121     if (scalarCast != CK_Invalid)
8122       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8123     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8124   }
8125   return false;
8126 }
8127
8128 /// Test if a (constant) integer Int can be casted to another integer type
8129 /// IntTy without losing precision.
8130 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8131                                       QualType OtherIntTy) {
8132   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8133
8134   // Reject cases where the value of the Int is unknown as that would
8135   // possibly cause truncation, but accept cases where the scalar can be
8136   // demoted without loss of precision.
8137   llvm::APSInt Result;
8138   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8139   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8140   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8141   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8142
8143   if (CstInt) {
8144     // If the scalar is constant and is of a higher order and has more active
8145     // bits that the vector element type, reject it.
8146     unsigned NumBits = IntSigned
8147                            ? (Result.isNegative() ? Result.getMinSignedBits()
8148                                                   : Result.getActiveBits())
8149                            : Result.getActiveBits();
8150     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8151       return true;
8152
8153     // If the signedness of the scalar type and the vector element type
8154     // differs and the number of bits is greater than that of the vector
8155     // element reject it.
8156     return (IntSigned != OtherIntSigned &&
8157             NumBits > S.Context.getIntWidth(OtherIntTy));
8158   }
8159
8160   // Reject cases where the value of the scalar is not constant and it's
8161   // order is greater than that of the vector element type.
8162   return (Order < 0);
8163 }
8164
8165 /// Test if a (constant) integer Int can be casted to floating point type
8166 /// FloatTy without losing precision.
8167 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8168                                      QualType FloatTy) {
8169   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8170
8171   // Determine if the integer constant can be expressed as a floating point
8172   // number of the appropiate type.
8173   llvm::APSInt Result;
8174   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8175   uint64_t Bits = 0;
8176   if (CstInt) {
8177     // Reject constants that would be truncated if they were converted to
8178     // the floating point type. Test by simple to/from conversion.
8179     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8180     //        could be avoided if there was a convertFromAPInt method
8181     //        which could signal back if implicit truncation occurred.
8182     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8183     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8184                            llvm::APFloat::rmTowardZero);
8185     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8186                              !IntTy->hasSignedIntegerRepresentation());
8187     bool Ignored = false;
8188     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8189                            &Ignored);
8190     if (Result != ConvertBack)
8191       return true;
8192   } else {
8193     // Reject types that cannot be fully encoded into the mantissa of
8194     // the float.
8195     Bits = S.Context.getTypeSize(IntTy);
8196     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8197         S.Context.getFloatTypeSemantics(FloatTy));
8198     if (Bits > FloatPrec)
8199       return true;
8200   }
8201
8202   return false;
8203 }
8204
8205 /// Attempt to convert and splat Scalar into a vector whose types matches
8206 /// Vector following GCC conversion rules. The rule is that implicit
8207 /// conversion can occur when Scalar can be casted to match Vector's element
8208 /// type without causing truncation of Scalar.
8209 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8210                                         ExprResult *Vector) {
8211   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8212   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8213   const VectorType *VT = VectorTy->getAs<VectorType>();
8214
8215   assert(!isa<ExtVectorType>(VT) &&
8216          "ExtVectorTypes should not be handled here!");
8217
8218   QualType VectorEltTy = VT->getElementType();
8219
8220   // Reject cases where the vector element type or the scalar element type are
8221   // not integral or floating point types.
8222   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8223     return true;
8224
8225   // The conversion to apply to the scalar before splatting it,
8226   // if necessary.
8227   CastKind ScalarCast = CK_NoOp;
8228
8229   // Accept cases where the vector elements are integers and the scalar is
8230   // an integer.
8231   // FIXME: Notionally if the scalar was a floating point value with a precise
8232   //        integral representation, we could cast it to an appropriate integer
8233   //        type and then perform the rest of the checks here. GCC will perform
8234   //        this conversion in some cases as determined by the input language.
8235   //        We should accept it on a language independent basis.
8236   if (VectorEltTy->isIntegralType(S.Context) &&
8237       ScalarTy->isIntegralType(S.Context) &&
8238       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8239
8240     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8241       return true;
8242
8243     ScalarCast = CK_IntegralCast;
8244   } else if (VectorEltTy->isRealFloatingType()) {
8245     if (ScalarTy->isRealFloatingType()) {
8246
8247       // Reject cases where the scalar type is not a constant and has a higher
8248       // Order than the vector element type.
8249       llvm::APFloat Result(0.0);
8250       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8251       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8252       if (!CstScalar && Order < 0)
8253         return true;
8254
8255       // If the scalar cannot be safely casted to the vector element type,
8256       // reject it.
8257       if (CstScalar) {
8258         bool Truncated = false;
8259         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8260                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8261         if (Truncated)
8262           return true;
8263       }
8264
8265       ScalarCast = CK_FloatingCast;
8266     } else if (ScalarTy->isIntegralType(S.Context)) {
8267       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8268         return true;
8269
8270       ScalarCast = CK_IntegralToFloating;
8271     } else
8272       return true;
8273   }
8274
8275   // Adjust scalar if desired.
8276   if (Scalar) {
8277     if (ScalarCast != CK_NoOp)
8278       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8279     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8280   }
8281   return false;
8282 }
8283
8284 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8285                                    SourceLocation Loc, bool IsCompAssign,
8286                                    bool AllowBothBool,
8287                                    bool AllowBoolConversions) {
8288   if (!IsCompAssign) {
8289     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8290     if (LHS.isInvalid())
8291       return QualType();
8292   }
8293   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8294   if (RHS.isInvalid())
8295     return QualType();
8296
8297   // For conversion purposes, we ignore any qualifiers.
8298   // For example, "const float" and "float" are equivalent.
8299   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8300   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8301
8302   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8303   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8304   assert(LHSVecType || RHSVecType);
8305
8306   // AltiVec-style "vector bool op vector bool" combinations are allowed
8307   // for some operators but not others.
8308   if (!AllowBothBool &&
8309       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8310       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8311     return InvalidOperands(Loc, LHS, RHS);
8312
8313   // If the vector types are identical, return.
8314   if (Context.hasSameType(LHSType, RHSType))
8315     return LHSType;
8316
8317   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8318   if (LHSVecType && RHSVecType &&
8319       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8320     if (isa<ExtVectorType>(LHSVecType)) {
8321       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8322       return LHSType;
8323     }
8324
8325     if (!IsCompAssign)
8326       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8327     return RHSType;
8328   }
8329
8330   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8331   // can be mixed, with the result being the non-bool type.  The non-bool
8332   // operand must have integer element type.
8333   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8334       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8335       (Context.getTypeSize(LHSVecType->getElementType()) ==
8336        Context.getTypeSize(RHSVecType->getElementType()))) {
8337     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8338         LHSVecType->getElementType()->isIntegerType() &&
8339         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8340       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8341       return LHSType;
8342     }
8343     if (!IsCompAssign &&
8344         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8345         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8346         RHSVecType->getElementType()->isIntegerType()) {
8347       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8348       return RHSType;
8349     }
8350   }
8351
8352   // If there's a vector type and a scalar, try to convert the scalar to
8353   // the vector element type and splat.
8354   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8355   if (!RHSVecType) {
8356     if (isa<ExtVectorType>(LHSVecType)) {
8357       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8358                                     LHSVecType->getElementType(), LHSType,
8359                                     DiagID))
8360         return LHSType;
8361     } else {
8362       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8363         return LHSType;
8364     }
8365   }
8366   if (!LHSVecType) {
8367     if (isa<ExtVectorType>(RHSVecType)) {
8368       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8369                                     LHSType, RHSVecType->getElementType(),
8370                                     RHSType, DiagID))
8371         return RHSType;
8372     } else {
8373       if (LHS.get()->getValueKind() == VK_LValue ||
8374           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8375         return RHSType;
8376     }
8377   }
8378
8379   // FIXME: The code below also handles conversion between vectors and
8380   // non-scalars, we should break this down into fine grained specific checks
8381   // and emit proper diagnostics.
8382   QualType VecType = LHSVecType ? LHSType : RHSType;
8383   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8384   QualType OtherType = LHSVecType ? RHSType : LHSType;
8385   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8386   if (isLaxVectorConversion(OtherType, VecType)) {
8387     // If we're allowing lax vector conversions, only the total (data) size
8388     // needs to be the same. For non compound assignment, if one of the types is
8389     // scalar, the result is always the vector type.
8390     if (!IsCompAssign) {
8391       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8392       return VecType;
8393     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8394     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8395     // type. Note that this is already done by non-compound assignments in
8396     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8397     // <1 x T> -> T. The result is also a vector type.
8398     } else if (OtherType->isExtVectorType() ||
8399                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8400       ExprResult *RHSExpr = &RHS;
8401       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8402       return VecType;
8403     }
8404   }
8405
8406   // Okay, the expression is invalid.
8407
8408   // If there's a non-vector, non-real operand, diagnose that.
8409   if ((!RHSVecType && !RHSType->isRealType()) ||
8410       (!LHSVecType && !LHSType->isRealType())) {
8411     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8412       << LHSType << RHSType
8413       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8414     return QualType();
8415   }
8416
8417   // OpenCL V1.1 6.2.6.p1:
8418   // If the operands are of more than one vector type, then an error shall
8419   // occur. Implicit conversions between vector types are not permitted, per
8420   // section 6.2.1.
8421   if (getLangOpts().OpenCL &&
8422       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8423       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8424     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8425                                                            << RHSType;
8426     return QualType();
8427   }
8428
8429
8430   // If there is a vector type that is not a ExtVector and a scalar, we reach
8431   // this point if scalar could not be converted to the vector's element type
8432   // without truncation.
8433   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8434       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8435     QualType Scalar = LHSVecType ? RHSType : LHSType;
8436     QualType Vector = LHSVecType ? LHSType : RHSType;
8437     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8438     Diag(Loc,
8439          diag::err_typecheck_vector_not_convertable_implict_truncation)
8440         << ScalarOrVector << Scalar << Vector;
8441
8442     return QualType();
8443   }
8444
8445   // Otherwise, use the generic diagnostic.
8446   Diag(Loc, DiagID)
8447     << LHSType << RHSType
8448     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8449   return QualType();
8450 }
8451
8452 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8453 // expression.  These are mainly cases where the null pointer is used as an
8454 // integer instead of a pointer.
8455 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8456                                 SourceLocation Loc, bool IsCompare) {
8457   // The canonical way to check for a GNU null is with isNullPointerConstant,
8458   // but we use a bit of a hack here for speed; this is a relatively
8459   // hot path, and isNullPointerConstant is slow.
8460   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8461   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8462
8463   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8464
8465   // Avoid analyzing cases where the result will either be invalid (and
8466   // diagnosed as such) or entirely valid and not something to warn about.
8467   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8468       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8469     return;
8470
8471   // Comparison operations would not make sense with a null pointer no matter
8472   // what the other expression is.
8473   if (!IsCompare) {
8474     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8475         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8476         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8477     return;
8478   }
8479
8480   // The rest of the operations only make sense with a null pointer
8481   // if the other expression is a pointer.
8482   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8483       NonNullType->canDecayToPointerType())
8484     return;
8485
8486   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8487       << LHSNull /* LHS is NULL */ << NonNullType
8488       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8489 }
8490
8491 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8492                                                ExprResult &RHS,
8493                                                SourceLocation Loc, bool IsDiv) {
8494   // Check for division/remainder by zero.
8495   llvm::APSInt RHSValue;
8496   if (!RHS.get()->isValueDependent() &&
8497       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8498     S.DiagRuntimeBehavior(Loc, RHS.get(),
8499                           S.PDiag(diag::warn_remainder_division_by_zero)
8500                             << IsDiv << RHS.get()->getSourceRange());
8501 }
8502
8503 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8504                                            SourceLocation Loc,
8505                                            bool IsCompAssign, bool IsDiv) {
8506   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8507
8508   if (LHS.get()->getType()->isVectorType() ||
8509       RHS.get()->getType()->isVectorType())
8510     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8511                                /*AllowBothBool*/getLangOpts().AltiVec,
8512                                /*AllowBoolConversions*/false);
8513
8514   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8515   if (LHS.isInvalid() || RHS.isInvalid())
8516     return QualType();
8517
8518
8519   if (compType.isNull() || !compType->isArithmeticType())
8520     return InvalidOperands(Loc, LHS, RHS);
8521   if (IsDiv)
8522     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8523   return compType;
8524 }
8525
8526 QualType Sema::CheckRemainderOperands(
8527   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8528   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8529
8530   if (LHS.get()->getType()->isVectorType() ||
8531       RHS.get()->getType()->isVectorType()) {
8532     if (LHS.get()->getType()->hasIntegerRepresentation() && 
8533         RHS.get()->getType()->hasIntegerRepresentation())
8534       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8535                                  /*AllowBothBool*/getLangOpts().AltiVec,
8536                                  /*AllowBoolConversions*/false);
8537     return InvalidOperands(Loc, LHS, RHS);
8538   }
8539
8540   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8541   if (LHS.isInvalid() || RHS.isInvalid())
8542     return QualType();
8543
8544   if (compType.isNull() || !compType->isIntegerType())
8545     return InvalidOperands(Loc, LHS, RHS);
8546   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8547   return compType;
8548 }
8549
8550 /// \brief Diagnose invalid arithmetic on two void pointers.
8551 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8552                                                 Expr *LHSExpr, Expr *RHSExpr) {
8553   S.Diag(Loc, S.getLangOpts().CPlusPlus
8554                 ? diag::err_typecheck_pointer_arith_void_type
8555                 : diag::ext_gnu_void_ptr)
8556     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8557                             << RHSExpr->getSourceRange();
8558 }
8559
8560 /// \brief Diagnose invalid arithmetic on a void pointer.
8561 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8562                                             Expr *Pointer) {
8563   S.Diag(Loc, S.getLangOpts().CPlusPlus
8564                 ? diag::err_typecheck_pointer_arith_void_type
8565                 : diag::ext_gnu_void_ptr)
8566     << 0 /* one pointer */ << Pointer->getSourceRange();
8567 }
8568
8569 /// \brief Diagnose invalid arithmetic on two function pointers.
8570 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8571                                                     Expr *LHS, Expr *RHS) {
8572   assert(LHS->getType()->isAnyPointerType());
8573   assert(RHS->getType()->isAnyPointerType());
8574   S.Diag(Loc, S.getLangOpts().CPlusPlus
8575                 ? diag::err_typecheck_pointer_arith_function_type
8576                 : diag::ext_gnu_ptr_func_arith)
8577     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8578     // We only show the second type if it differs from the first.
8579     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8580                                                    RHS->getType())
8581     << RHS->getType()->getPointeeType()
8582     << LHS->getSourceRange() << RHS->getSourceRange();
8583 }
8584
8585 /// \brief Diagnose invalid arithmetic on a function pointer.
8586 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8587                                                 Expr *Pointer) {
8588   assert(Pointer->getType()->isAnyPointerType());
8589   S.Diag(Loc, S.getLangOpts().CPlusPlus
8590                 ? diag::err_typecheck_pointer_arith_function_type
8591                 : diag::ext_gnu_ptr_func_arith)
8592     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8593     << 0 /* one pointer, so only one type */
8594     << Pointer->getSourceRange();
8595 }
8596
8597 /// \brief Emit error if Operand is incomplete pointer type
8598 ///
8599 /// \returns True if pointer has incomplete type
8600 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8601                                                  Expr *Operand) {
8602   QualType ResType = Operand->getType();
8603   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8604     ResType = ResAtomicType->getValueType();
8605
8606   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8607   QualType PointeeTy = ResType->getPointeeType();
8608   return S.RequireCompleteType(Loc, PointeeTy,
8609                                diag::err_typecheck_arithmetic_incomplete_type,
8610                                PointeeTy, Operand->getSourceRange());
8611 }
8612
8613 /// \brief Check the validity of an arithmetic pointer operand.
8614 ///
8615 /// If the operand has pointer type, this code will check for pointer types
8616 /// which are invalid in arithmetic operations. These will be diagnosed
8617 /// appropriately, including whether or not the use is supported as an
8618 /// extension.
8619 ///
8620 /// \returns True when the operand is valid to use (even if as an extension).
8621 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8622                                             Expr *Operand) {
8623   QualType ResType = Operand->getType();
8624   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8625     ResType = ResAtomicType->getValueType();
8626
8627   if (!ResType->isAnyPointerType()) return true;
8628
8629   QualType PointeeTy = ResType->getPointeeType();
8630   if (PointeeTy->isVoidType()) {
8631     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8632     return !S.getLangOpts().CPlusPlus;
8633   }
8634   if (PointeeTy->isFunctionType()) {
8635     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8636     return !S.getLangOpts().CPlusPlus;
8637   }
8638
8639   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8640
8641   return true;
8642 }
8643
8644 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8645 /// operands.
8646 ///
8647 /// This routine will diagnose any invalid arithmetic on pointer operands much
8648 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8649 /// for emitting a single diagnostic even for operations where both LHS and RHS
8650 /// are (potentially problematic) pointers.
8651 ///
8652 /// \returns True when the operand is valid to use (even if as an extension).
8653 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8654                                                 Expr *LHSExpr, Expr *RHSExpr) {
8655   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8656   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8657   if (!isLHSPointer && !isRHSPointer) return true;
8658
8659   QualType LHSPointeeTy, RHSPointeeTy;
8660   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8661   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8662
8663   // if both are pointers check if operation is valid wrt address spaces
8664   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8665     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8666     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8667     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8668       S.Diag(Loc,
8669              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8670           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8671           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8672       return false;
8673     }
8674   }
8675
8676   // Check for arithmetic on pointers to incomplete types.
8677   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8678   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8679   if (isLHSVoidPtr || isRHSVoidPtr) {
8680     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8681     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8682     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8683
8684     return !S.getLangOpts().CPlusPlus;
8685   }
8686
8687   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8688   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8689   if (isLHSFuncPtr || isRHSFuncPtr) {
8690     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8691     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8692                                                                 RHSExpr);
8693     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8694
8695     return !S.getLangOpts().CPlusPlus;
8696   }
8697
8698   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8699     return false;
8700   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8701     return false;
8702
8703   return true;
8704 }
8705
8706 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8707 /// literal.
8708 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8709                                   Expr *LHSExpr, Expr *RHSExpr) {
8710   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8711   Expr* IndexExpr = RHSExpr;
8712   if (!StrExpr) {
8713     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8714     IndexExpr = LHSExpr;
8715   }
8716
8717   bool IsStringPlusInt = StrExpr &&
8718       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8719   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8720     return;
8721
8722   llvm::APSInt index;
8723   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8724     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8725     if (index.isNonNegative() &&
8726         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8727                               index.isUnsigned()))
8728       return;
8729   }
8730
8731   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8732   Self.Diag(OpLoc, diag::warn_string_plus_int)
8733       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8734
8735   // Only print a fixit for "str" + int, not for int + "str".
8736   if (IndexExpr == RHSExpr) {
8737     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8738     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8739         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8740         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8741         << FixItHint::CreateInsertion(EndLoc, "]");
8742   } else
8743     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8744 }
8745
8746 /// \brief Emit a warning when adding a char literal to a string.
8747 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8748                                    Expr *LHSExpr, Expr *RHSExpr) {
8749   const Expr *StringRefExpr = LHSExpr;
8750   const CharacterLiteral *CharExpr =
8751       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8752
8753   if (!CharExpr) {
8754     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8755     StringRefExpr = RHSExpr;
8756   }
8757
8758   if (!CharExpr || !StringRefExpr)
8759     return;
8760
8761   const QualType StringType = StringRefExpr->getType();
8762
8763   // Return if not a PointerType.
8764   if (!StringType->isAnyPointerType())
8765     return;
8766
8767   // Return if not a CharacterType.
8768   if (!StringType->getPointeeType()->isAnyCharacterType())
8769     return;
8770
8771   ASTContext &Ctx = Self.getASTContext();
8772   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8773
8774   const QualType CharType = CharExpr->getType();
8775   if (!CharType->isAnyCharacterType() &&
8776       CharType->isIntegerType() &&
8777       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8778     Self.Diag(OpLoc, diag::warn_string_plus_char)
8779         << DiagRange << Ctx.CharTy;
8780   } else {
8781     Self.Diag(OpLoc, diag::warn_string_plus_char)
8782         << DiagRange << CharExpr->getType();
8783   }
8784
8785   // Only print a fixit for str + char, not for char + str.
8786   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8787     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8788     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8789         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8790         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8791         << FixItHint::CreateInsertion(EndLoc, "]");
8792   } else {
8793     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8794   }
8795 }
8796
8797 /// \brief Emit error when two pointers are incompatible.
8798 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8799                                            Expr *LHSExpr, Expr *RHSExpr) {
8800   assert(LHSExpr->getType()->isAnyPointerType());
8801   assert(RHSExpr->getType()->isAnyPointerType());
8802   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8803     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8804     << RHSExpr->getSourceRange();
8805 }
8806
8807 // C99 6.5.6
8808 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8809                                      SourceLocation Loc, BinaryOperatorKind Opc,
8810                                      QualType* CompLHSTy) {
8811   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8812
8813   if (LHS.get()->getType()->isVectorType() ||
8814       RHS.get()->getType()->isVectorType()) {
8815     QualType compType = CheckVectorOperands(
8816         LHS, RHS, Loc, CompLHSTy,
8817         /*AllowBothBool*/getLangOpts().AltiVec,
8818         /*AllowBoolConversions*/getLangOpts().ZVector);
8819     if (CompLHSTy) *CompLHSTy = compType;
8820     return compType;
8821   }
8822
8823   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8824   if (LHS.isInvalid() || RHS.isInvalid())
8825     return QualType();
8826
8827   // Diagnose "string literal" '+' int and string '+' "char literal".
8828   if (Opc == BO_Add) {
8829     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8830     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8831   }
8832
8833   // handle the common case first (both operands are arithmetic).
8834   if (!compType.isNull() && compType->isArithmeticType()) {
8835     if (CompLHSTy) *CompLHSTy = compType;
8836     return compType;
8837   }
8838
8839   // Type-checking.  Ultimately the pointer's going to be in PExp;
8840   // note that we bias towards the LHS being the pointer.
8841   Expr *PExp = LHS.get(), *IExp = RHS.get();
8842
8843   bool isObjCPointer;
8844   if (PExp->getType()->isPointerType()) {
8845     isObjCPointer = false;
8846   } else if (PExp->getType()->isObjCObjectPointerType()) {
8847     isObjCPointer = true;
8848   } else {
8849     std::swap(PExp, IExp);
8850     if (PExp->getType()->isPointerType()) {
8851       isObjCPointer = false;
8852     } else if (PExp->getType()->isObjCObjectPointerType()) {
8853       isObjCPointer = true;
8854     } else {
8855       return InvalidOperands(Loc, LHS, RHS);
8856     }
8857   }
8858   assert(PExp->getType()->isAnyPointerType());
8859
8860   if (!IExp->getType()->isIntegerType())
8861     return InvalidOperands(Loc, LHS, RHS);
8862
8863   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8864     return QualType();
8865
8866   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8867     return QualType();
8868
8869   // Check array bounds for pointer arithemtic
8870   CheckArrayAccess(PExp, IExp);
8871
8872   if (CompLHSTy) {
8873     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8874     if (LHSTy.isNull()) {
8875       LHSTy = LHS.get()->getType();
8876       if (LHSTy->isPromotableIntegerType())
8877         LHSTy = Context.getPromotedIntegerType(LHSTy);
8878     }
8879     *CompLHSTy = LHSTy;
8880   }
8881
8882   return PExp->getType();
8883 }
8884
8885 // C99 6.5.6
8886 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8887                                         SourceLocation Loc,
8888                                         QualType* CompLHSTy) {
8889   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8890
8891   if (LHS.get()->getType()->isVectorType() ||
8892       RHS.get()->getType()->isVectorType()) {
8893     QualType compType = CheckVectorOperands(
8894         LHS, RHS, Loc, CompLHSTy,
8895         /*AllowBothBool*/getLangOpts().AltiVec,
8896         /*AllowBoolConversions*/getLangOpts().ZVector);
8897     if (CompLHSTy) *CompLHSTy = compType;
8898     return compType;
8899   }
8900
8901   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8902   if (LHS.isInvalid() || RHS.isInvalid())
8903     return QualType();
8904
8905   // Enforce type constraints: C99 6.5.6p3.
8906
8907   // Handle the common case first (both operands are arithmetic).
8908   if (!compType.isNull() && compType->isArithmeticType()) {
8909     if (CompLHSTy) *CompLHSTy = compType;
8910     return compType;
8911   }
8912
8913   // Either ptr - int   or   ptr - ptr.
8914   if (LHS.get()->getType()->isAnyPointerType()) {
8915     QualType lpointee = LHS.get()->getType()->getPointeeType();
8916
8917     // Diagnose bad cases where we step over interface counts.
8918     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8919         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8920       return QualType();
8921
8922     // The result type of a pointer-int computation is the pointer type.
8923     if (RHS.get()->getType()->isIntegerType()) {
8924       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8925         return QualType();
8926
8927       // Check array bounds for pointer arithemtic
8928       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8929                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8930
8931       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8932       return LHS.get()->getType();
8933     }
8934
8935     // Handle pointer-pointer subtractions.
8936     if (const PointerType *RHSPTy
8937           = RHS.get()->getType()->getAs<PointerType>()) {
8938       QualType rpointee = RHSPTy->getPointeeType();
8939
8940       if (getLangOpts().CPlusPlus) {
8941         // Pointee types must be the same: C++ [expr.add]
8942         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8943           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8944         }
8945       } else {
8946         // Pointee types must be compatible C99 6.5.6p3
8947         if (!Context.typesAreCompatible(
8948                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8949                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8950           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8951           return QualType();
8952         }
8953       }
8954
8955       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8956                                                LHS.get(), RHS.get()))
8957         return QualType();
8958
8959       // The pointee type may have zero size.  As an extension, a structure or
8960       // union may have zero size or an array may have zero length.  In this
8961       // case subtraction does not make sense.
8962       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8963         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8964         if (ElementSize.isZero()) {
8965           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8966             << rpointee.getUnqualifiedType()
8967             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8968         }
8969       }
8970
8971       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8972       return Context.getPointerDiffType();
8973     }
8974   }
8975
8976   return InvalidOperands(Loc, LHS, RHS);
8977 }
8978
8979 static bool isScopedEnumerationType(QualType T) {
8980   if (const EnumType *ET = T->getAs<EnumType>())
8981     return ET->getDecl()->isScoped();
8982   return false;
8983 }
8984
8985 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8986                                    SourceLocation Loc, BinaryOperatorKind Opc,
8987                                    QualType LHSType) {
8988   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8989   // so skip remaining warnings as we don't want to modify values within Sema.
8990   if (S.getLangOpts().OpenCL)
8991     return;
8992
8993   llvm::APSInt Right;
8994   // Check right/shifter operand
8995   if (RHS.get()->isValueDependent() ||
8996       !RHS.get()->EvaluateAsInt(Right, S.Context))
8997     return;
8998
8999   if (Right.isNegative()) {
9000     S.DiagRuntimeBehavior(Loc, RHS.get(),
9001                           S.PDiag(diag::warn_shift_negative)
9002                             << RHS.get()->getSourceRange());
9003     return;
9004   }
9005   llvm::APInt LeftBits(Right.getBitWidth(),
9006                        S.Context.getTypeSize(LHS.get()->getType()));
9007   if (Right.uge(LeftBits)) {
9008     S.DiagRuntimeBehavior(Loc, RHS.get(),
9009                           S.PDiag(diag::warn_shift_gt_typewidth)
9010                             << RHS.get()->getSourceRange());
9011     return;
9012   }
9013   if (Opc != BO_Shl)
9014     return;
9015
9016   // When left shifting an ICE which is signed, we can check for overflow which
9017   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9018   // integers have defined behavior modulo one more than the maximum value
9019   // representable in the result type, so never warn for those.
9020   llvm::APSInt Left;
9021   if (LHS.get()->isValueDependent() ||
9022       LHSType->hasUnsignedIntegerRepresentation() ||
9023       !LHS.get()->EvaluateAsInt(Left, S.Context))
9024     return;
9025
9026   // If LHS does not have a signed type and non-negative value
9027   // then, the behavior is undefined. Warn about it.
9028   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9029     S.DiagRuntimeBehavior(Loc, LHS.get(),
9030                           S.PDiag(diag::warn_shift_lhs_negative)
9031                             << LHS.get()->getSourceRange());
9032     return;
9033   }
9034
9035   llvm::APInt ResultBits =
9036       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9037   if (LeftBits.uge(ResultBits))
9038     return;
9039   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9040   Result = Result.shl(Right);
9041
9042   // Print the bit representation of the signed integer as an unsigned
9043   // hexadecimal number.
9044   SmallString<40> HexResult;
9045   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9046
9047   // If we are only missing a sign bit, this is less likely to result in actual
9048   // bugs -- if the result is cast back to an unsigned type, it will have the
9049   // expected value. Thus we place this behind a different warning that can be
9050   // turned off separately if needed.
9051   if (LeftBits == ResultBits - 1) {
9052     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9053         << HexResult << LHSType
9054         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9055     return;
9056   }
9057
9058   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9059     << HexResult.str() << Result.getMinSignedBits() << LHSType
9060     << Left.getBitWidth() << LHS.get()->getSourceRange()
9061     << RHS.get()->getSourceRange();
9062 }
9063
9064 /// \brief Return the resulting type when a vector is shifted
9065 ///        by a scalar or vector shift amount.
9066 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9067                                  SourceLocation Loc, bool IsCompAssign) {
9068   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9069   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9070       !LHS.get()->getType()->isVectorType()) {
9071     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9072       << RHS.get()->getType() << LHS.get()->getType()
9073       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9074     return QualType();
9075   }
9076
9077   if (!IsCompAssign) {
9078     LHS = S.UsualUnaryConversions(LHS.get());
9079     if (LHS.isInvalid()) return QualType();
9080   }
9081
9082   RHS = S.UsualUnaryConversions(RHS.get());
9083   if (RHS.isInvalid()) return QualType();
9084
9085   QualType LHSType = LHS.get()->getType();
9086   // Note that LHS might be a scalar because the routine calls not only in
9087   // OpenCL case.
9088   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9089   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9090
9091   // Note that RHS might not be a vector.
9092   QualType RHSType = RHS.get()->getType();
9093   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9094   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9095
9096   // The operands need to be integers.
9097   if (!LHSEleType->isIntegerType()) {
9098     S.Diag(Loc, diag::err_typecheck_expect_int)
9099       << LHS.get()->getType() << LHS.get()->getSourceRange();
9100     return QualType();
9101   }
9102
9103   if (!RHSEleType->isIntegerType()) {
9104     S.Diag(Loc, diag::err_typecheck_expect_int)
9105       << RHS.get()->getType() << RHS.get()->getSourceRange();
9106     return QualType();
9107   }
9108
9109   if (!LHSVecTy) {
9110     assert(RHSVecTy);
9111     if (IsCompAssign)
9112       return RHSType;
9113     if (LHSEleType != RHSEleType) {
9114       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9115       LHSEleType = RHSEleType;
9116     }
9117     QualType VecTy =
9118         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9119     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9120     LHSType = VecTy;
9121   } else if (RHSVecTy) {
9122     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9123     // are applied component-wise. So if RHS is a vector, then ensure
9124     // that the number of elements is the same as LHS...
9125     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9126       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9127         << LHS.get()->getType() << RHS.get()->getType()
9128         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9129       return QualType();
9130     }
9131     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9132       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9133       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9134       if (LHSBT != RHSBT &&
9135           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9136         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9137             << LHS.get()->getType() << RHS.get()->getType()
9138             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9139       }
9140     }
9141   } else {
9142     // ...else expand RHS to match the number of elements in LHS.
9143     QualType VecTy =
9144       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9145     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9146   }
9147
9148   return LHSType;
9149 }
9150
9151 // C99 6.5.7
9152 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9153                                   SourceLocation Loc, BinaryOperatorKind Opc,
9154                                   bool IsCompAssign) {
9155   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9156
9157   // Vector shifts promote their scalar inputs to vector type.
9158   if (LHS.get()->getType()->isVectorType() ||
9159       RHS.get()->getType()->isVectorType()) {
9160     if (LangOpts.ZVector) {
9161       // The shift operators for the z vector extensions work basically
9162       // like general shifts, except that neither the LHS nor the RHS is
9163       // allowed to be a "vector bool".
9164       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9165         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9166           return InvalidOperands(Loc, LHS, RHS);
9167       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9168         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9169           return InvalidOperands(Loc, LHS, RHS);
9170     }
9171     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9172   }
9173
9174   // Shifts don't perform usual arithmetic conversions, they just do integer
9175   // promotions on each operand. C99 6.5.7p3
9176
9177   // For the LHS, do usual unary conversions, but then reset them away
9178   // if this is a compound assignment.
9179   ExprResult OldLHS = LHS;
9180   LHS = UsualUnaryConversions(LHS.get());
9181   if (LHS.isInvalid())
9182     return QualType();
9183   QualType LHSType = LHS.get()->getType();
9184   if (IsCompAssign) LHS = OldLHS;
9185
9186   // The RHS is simpler.
9187   RHS = UsualUnaryConversions(RHS.get());
9188   if (RHS.isInvalid())
9189     return QualType();
9190   QualType RHSType = RHS.get()->getType();
9191
9192   // C99 6.5.7p2: Each of the operands shall have integer type.
9193   if (!LHSType->hasIntegerRepresentation() ||
9194       !RHSType->hasIntegerRepresentation())
9195     return InvalidOperands(Loc, LHS, RHS);
9196
9197   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9198   // hasIntegerRepresentation() above instead of this.
9199   if (isScopedEnumerationType(LHSType) ||
9200       isScopedEnumerationType(RHSType)) {
9201     return InvalidOperands(Loc, LHS, RHS);
9202   }
9203   // Sanity-check shift operands
9204   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9205
9206   // "The type of the result is that of the promoted left operand."
9207   return LHSType;
9208 }
9209
9210 static bool IsWithinTemplateSpecialization(Decl *D) {
9211   if (DeclContext *DC = D->getDeclContext()) {
9212     if (isa<ClassTemplateSpecializationDecl>(DC))
9213       return true;
9214     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
9215       return FD->isFunctionTemplateSpecialization();
9216   }
9217   return false;
9218 }
9219
9220 /// If two different enums are compared, raise a warning.
9221 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9222                                 Expr *RHS) {
9223   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9224   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9225
9226   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9227   if (!LHSEnumType)
9228     return;
9229   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9230   if (!RHSEnumType)
9231     return;
9232
9233   // Ignore anonymous enums.
9234   if (!LHSEnumType->getDecl()->getIdentifier())
9235     return;
9236   if (!RHSEnumType->getDecl()->getIdentifier())
9237     return;
9238
9239   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9240     return;
9241
9242   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9243       << LHSStrippedType << RHSStrippedType
9244       << LHS->getSourceRange() << RHS->getSourceRange();
9245 }
9246
9247 /// \brief Diagnose bad pointer comparisons.
9248 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9249                                               ExprResult &LHS, ExprResult &RHS,
9250                                               bool IsError) {
9251   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9252                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9253     << LHS.get()->getType() << RHS.get()->getType()
9254     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9255 }
9256
9257 /// \brief Returns false if the pointers are converted to a composite type,
9258 /// true otherwise.
9259 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9260                                            ExprResult &LHS, ExprResult &RHS) {
9261   // C++ [expr.rel]p2:
9262   //   [...] Pointer conversions (4.10) and qualification
9263   //   conversions (4.4) are performed on pointer operands (or on
9264   //   a pointer operand and a null pointer constant) to bring
9265   //   them to their composite pointer type. [...]
9266   //
9267   // C++ [expr.eq]p1 uses the same notion for (in)equality
9268   // comparisons of pointers.
9269
9270   QualType LHSType = LHS.get()->getType();
9271   QualType RHSType = RHS.get()->getType();
9272   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9273          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9274
9275   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9276   if (T.isNull()) {
9277     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9278         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9279       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9280     else
9281       S.InvalidOperands(Loc, LHS, RHS);
9282     return true;
9283   }
9284
9285   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9286   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9287   return false;
9288 }
9289
9290 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9291                                                     ExprResult &LHS,
9292                                                     ExprResult &RHS,
9293                                                     bool IsError) {
9294   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9295                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9296     << LHS.get()->getType() << RHS.get()->getType()
9297     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9298 }
9299
9300 static bool isObjCObjectLiteral(ExprResult &E) {
9301   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9302   case Stmt::ObjCArrayLiteralClass:
9303   case Stmt::ObjCDictionaryLiteralClass:
9304   case Stmt::ObjCStringLiteralClass:
9305   case Stmt::ObjCBoxedExprClass:
9306     return true;
9307   default:
9308     // Note that ObjCBoolLiteral is NOT an object literal!
9309     return false;
9310   }
9311 }
9312
9313 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9314   const ObjCObjectPointerType *Type =
9315     LHS->getType()->getAs<ObjCObjectPointerType>();
9316
9317   // If this is not actually an Objective-C object, bail out.
9318   if (!Type)
9319     return false;
9320
9321   // Get the LHS object's interface type.
9322   QualType InterfaceType = Type->getPointeeType();
9323
9324   // If the RHS isn't an Objective-C object, bail out.
9325   if (!RHS->getType()->isObjCObjectPointerType())
9326     return false;
9327
9328   // Try to find the -isEqual: method.
9329   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9330   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9331                                                       InterfaceType,
9332                                                       /*instance=*/true);
9333   if (!Method) {
9334     if (Type->isObjCIdType()) {
9335       // For 'id', just check the global pool.
9336       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9337                                                   /*receiverId=*/true);
9338     } else {
9339       // Check protocols.
9340       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9341                                              /*instance=*/true);
9342     }
9343   }
9344
9345   if (!Method)
9346     return false;
9347
9348   QualType T = Method->parameters()[0]->getType();
9349   if (!T->isObjCObjectPointerType())
9350     return false;
9351
9352   QualType R = Method->getReturnType();
9353   if (!R->isScalarType())
9354     return false;
9355
9356   return true;
9357 }
9358
9359 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9360   FromE = FromE->IgnoreParenImpCasts();
9361   switch (FromE->getStmtClass()) {
9362     default:
9363       break;
9364     case Stmt::ObjCStringLiteralClass:
9365       // "string literal"
9366       return LK_String;
9367     case Stmt::ObjCArrayLiteralClass:
9368       // "array literal"
9369       return LK_Array;
9370     case Stmt::ObjCDictionaryLiteralClass:
9371       // "dictionary literal"
9372       return LK_Dictionary;
9373     case Stmt::BlockExprClass:
9374       return LK_Block;
9375     case Stmt::ObjCBoxedExprClass: {
9376       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9377       switch (Inner->getStmtClass()) {
9378         case Stmt::IntegerLiteralClass:
9379         case Stmt::FloatingLiteralClass:
9380         case Stmt::CharacterLiteralClass:
9381         case Stmt::ObjCBoolLiteralExprClass:
9382         case Stmt::CXXBoolLiteralExprClass:
9383           // "numeric literal"
9384           return LK_Numeric;
9385         case Stmt::ImplicitCastExprClass: {
9386           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9387           // Boolean literals can be represented by implicit casts.
9388           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9389             return LK_Numeric;
9390           break;
9391         }
9392         default:
9393           break;
9394       }
9395       return LK_Boxed;
9396     }
9397   }
9398   return LK_None;
9399 }
9400
9401 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9402                                           ExprResult &LHS, ExprResult &RHS,
9403                                           BinaryOperator::Opcode Opc){
9404   Expr *Literal;
9405   Expr *Other;
9406   if (isObjCObjectLiteral(LHS)) {
9407     Literal = LHS.get();
9408     Other = RHS.get();
9409   } else {
9410     Literal = RHS.get();
9411     Other = LHS.get();
9412   }
9413
9414   // Don't warn on comparisons against nil.
9415   Other = Other->IgnoreParenCasts();
9416   if (Other->isNullPointerConstant(S.getASTContext(),
9417                                    Expr::NPC_ValueDependentIsNotNull))
9418     return;
9419
9420   // This should be kept in sync with warn_objc_literal_comparison.
9421   // LK_String should always be after the other literals, since it has its own
9422   // warning flag.
9423   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9424   assert(LiteralKind != Sema::LK_Block);
9425   if (LiteralKind == Sema::LK_None) {
9426     llvm_unreachable("Unknown Objective-C object literal kind");
9427   }
9428
9429   if (LiteralKind == Sema::LK_String)
9430     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9431       << Literal->getSourceRange();
9432   else
9433     S.Diag(Loc, diag::warn_objc_literal_comparison)
9434       << LiteralKind << Literal->getSourceRange();
9435
9436   if (BinaryOperator::isEqualityOp(Opc) &&
9437       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9438     SourceLocation Start = LHS.get()->getLocStart();
9439     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9440     CharSourceRange OpRange =
9441       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9442
9443     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9444       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9445       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9446       << FixItHint::CreateInsertion(End, "]");
9447   }
9448 }
9449
9450 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9451 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9452                                            ExprResult &RHS, SourceLocation Loc,
9453                                            BinaryOperatorKind Opc) {
9454   // Check that left hand side is !something.
9455   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9456   if (!UO || UO->getOpcode() != UO_LNot) return;
9457
9458   // Only check if the right hand side is non-bool arithmetic type.
9459   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9460
9461   // Make sure that the something in !something is not bool.
9462   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9463   if (SubExpr->isKnownToHaveBooleanValue()) return;
9464
9465   // Emit warning.
9466   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9467   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9468       << Loc << IsBitwiseOp;
9469
9470   // First note suggest !(x < y)
9471   SourceLocation FirstOpen = SubExpr->getLocStart();
9472   SourceLocation FirstClose = RHS.get()->getLocEnd();
9473   FirstClose = S.getLocForEndOfToken(FirstClose);
9474   if (FirstClose.isInvalid())
9475     FirstOpen = SourceLocation();
9476   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9477       << IsBitwiseOp
9478       << FixItHint::CreateInsertion(FirstOpen, "(")
9479       << FixItHint::CreateInsertion(FirstClose, ")");
9480
9481   // Second note suggests (!x) < y
9482   SourceLocation SecondOpen = LHS.get()->getLocStart();
9483   SourceLocation SecondClose = LHS.get()->getLocEnd();
9484   SecondClose = S.getLocForEndOfToken(SecondClose);
9485   if (SecondClose.isInvalid())
9486     SecondOpen = SourceLocation();
9487   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9488       << FixItHint::CreateInsertion(SecondOpen, "(")
9489       << FixItHint::CreateInsertion(SecondClose, ")");
9490 }
9491
9492 // Get the decl for a simple expression: a reference to a variable,
9493 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9494 static ValueDecl *getCompareDecl(Expr *E) {
9495   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9496     return DR->getDecl();
9497   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9498     if (Ivar->isFreeIvar())
9499       return Ivar->getDecl();
9500   }
9501   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9502     if (Mem->isImplicitAccess())
9503       return Mem->getMemberDecl();
9504   }
9505   return nullptr;
9506 }
9507
9508 // C99 6.5.8, C++ [expr.rel]
9509 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9510                                     SourceLocation Loc, BinaryOperatorKind Opc,
9511                                     bool IsRelational) {
9512   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9513
9514   // Handle vector comparisons separately.
9515   if (LHS.get()->getType()->isVectorType() ||
9516       RHS.get()->getType()->isVectorType())
9517     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9518
9519   QualType LHSType = LHS.get()->getType();
9520   QualType RHSType = RHS.get()->getType();
9521
9522   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9523   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9524
9525   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9526   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9527
9528   if (!LHSType->hasFloatingRepresentation() &&
9529       !(LHSType->isBlockPointerType() && IsRelational) &&
9530       !LHS.get()->getLocStart().isMacroID() &&
9531       !RHS.get()->getLocStart().isMacroID() &&
9532       !inTemplateInstantiation()) {
9533     // For non-floating point types, check for self-comparisons of the form
9534     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9535     // often indicate logic errors in the program.
9536     //
9537     // NOTE: Don't warn about comparison expressions resulting from macro
9538     // expansion. Also don't warn about comparisons which are only self
9539     // comparisons within a template specialization. The warnings should catch
9540     // obvious cases in the definition of the template anyways. The idea is to
9541     // warn when the typed comparison operator will always evaluate to the same
9542     // result.
9543     ValueDecl *DL = getCompareDecl(LHSStripped);
9544     ValueDecl *DR = getCompareDecl(RHSStripped);
9545     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9546       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9547                           << 0 // self-
9548                           << (Opc == BO_EQ
9549                               || Opc == BO_LE
9550                               || Opc == BO_GE));
9551     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9552                !DL->getType()->isReferenceType() &&
9553                !DR->getType()->isReferenceType()) {
9554         // what is it always going to eval to?
9555         char always_evals_to;
9556         switch(Opc) {
9557         case BO_EQ: // e.g. array1 == array2
9558           always_evals_to = 0; // false
9559           break;
9560         case BO_NE: // e.g. array1 != array2
9561           always_evals_to = 1; // true
9562           break;
9563         default:
9564           // best we can say is 'a constant'
9565           always_evals_to = 2; // e.g. array1 <= array2
9566           break;
9567         }
9568         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9569                             << 1 // array
9570                             << always_evals_to);
9571     }
9572
9573     if (isa<CastExpr>(LHSStripped))
9574       LHSStripped = LHSStripped->IgnoreParenCasts();
9575     if (isa<CastExpr>(RHSStripped))
9576       RHSStripped = RHSStripped->IgnoreParenCasts();
9577
9578     // Warn about comparisons against a string constant (unless the other
9579     // operand is null), the user probably wants strcmp.
9580     Expr *literalString = nullptr;
9581     Expr *literalStringStripped = nullptr;
9582     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9583         !RHSStripped->isNullPointerConstant(Context,
9584                                             Expr::NPC_ValueDependentIsNull)) {
9585       literalString = LHS.get();
9586       literalStringStripped = LHSStripped;
9587     } else if ((isa<StringLiteral>(RHSStripped) ||
9588                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9589                !LHSStripped->isNullPointerConstant(Context,
9590                                             Expr::NPC_ValueDependentIsNull)) {
9591       literalString = RHS.get();
9592       literalStringStripped = RHSStripped;
9593     }
9594
9595     if (literalString) {
9596       DiagRuntimeBehavior(Loc, nullptr,
9597         PDiag(diag::warn_stringcompare)
9598           << isa<ObjCEncodeExpr>(literalStringStripped)
9599           << literalString->getSourceRange());
9600     }
9601   }
9602
9603   // C99 6.5.8p3 / C99 6.5.9p4
9604   UsualArithmeticConversions(LHS, RHS);
9605   if (LHS.isInvalid() || RHS.isInvalid())
9606     return QualType();
9607
9608   LHSType = LHS.get()->getType();
9609   RHSType = RHS.get()->getType();
9610
9611   // The result of comparisons is 'bool' in C++, 'int' in C.
9612   QualType ResultTy = Context.getLogicalOperationType();
9613
9614   if (IsRelational) {
9615     if (LHSType->isRealType() && RHSType->isRealType())
9616       return ResultTy;
9617   } else {
9618     // Check for comparisons of floating point operands using != and ==.
9619     if (LHSType->hasFloatingRepresentation())
9620       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9621
9622     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9623       return ResultTy;
9624   }
9625
9626   const Expr::NullPointerConstantKind LHSNullKind =
9627       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9628   const Expr::NullPointerConstantKind RHSNullKind =
9629       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9630   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9631   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9632
9633   if (!IsRelational && LHSIsNull != RHSIsNull) {
9634     bool IsEquality = Opc == BO_EQ;
9635     if (RHSIsNull)
9636       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9637                                    RHS.get()->getSourceRange());
9638     else
9639       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9640                                    LHS.get()->getSourceRange());
9641   }
9642
9643   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9644       (RHSType->isIntegerType() && !RHSIsNull)) {
9645     // Skip normal pointer conversion checks in this case; we have better
9646     // diagnostics for this below.
9647   } else if (getLangOpts().CPlusPlus) {
9648     // Equality comparison of a function pointer to a void pointer is invalid,
9649     // but we allow it as an extension.
9650     // FIXME: If we really want to allow this, should it be part of composite
9651     // pointer type computation so it works in conditionals too?
9652     if (!IsRelational &&
9653         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9654          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9655       // This is a gcc extension compatibility comparison.
9656       // In a SFINAE context, we treat this as a hard error to maintain
9657       // conformance with the C++ standard.
9658       diagnoseFunctionPointerToVoidComparison(
9659           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9660       
9661       if (isSFINAEContext())
9662         return QualType();
9663       
9664       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9665       return ResultTy;
9666     }
9667
9668     // C++ [expr.eq]p2:
9669     //   If at least one operand is a pointer [...] bring them to their
9670     //   composite pointer type.
9671     // C++ [expr.rel]p2:
9672     //   If both operands are pointers, [...] bring them to their composite
9673     //   pointer type.
9674     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9675             (IsRelational ? 2 : 1) &&
9676         (!LangOpts.ObjCAutoRefCount ||
9677          !(LHSType->isObjCObjectPointerType() ||
9678            RHSType->isObjCObjectPointerType()))) {
9679       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9680         return QualType();
9681       else
9682         return ResultTy;
9683     }
9684   } else if (LHSType->isPointerType() &&
9685              RHSType->isPointerType()) { // C99 6.5.8p2
9686     // All of the following pointer-related warnings are GCC extensions, except
9687     // when handling null pointer constants.
9688     QualType LCanPointeeTy =
9689       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9690     QualType RCanPointeeTy =
9691       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9692
9693     // C99 6.5.9p2 and C99 6.5.8p2
9694     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9695                                    RCanPointeeTy.getUnqualifiedType())) {
9696       // Valid unless a relational comparison of function pointers
9697       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9698         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9699           << LHSType << RHSType << LHS.get()->getSourceRange()
9700           << RHS.get()->getSourceRange();
9701       }
9702     } else if (!IsRelational &&
9703                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9704       // Valid unless comparison between non-null pointer and function pointer
9705       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9706           && !LHSIsNull && !RHSIsNull)
9707         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9708                                                 /*isError*/false);
9709     } else {
9710       // Invalid
9711       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9712     }
9713     if (LCanPointeeTy != RCanPointeeTy) {
9714       // Treat NULL constant as a special case in OpenCL.
9715       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9716         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9717         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9718           Diag(Loc,
9719                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9720               << LHSType << RHSType << 0 /* comparison */
9721               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9722         }
9723       }
9724       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9725       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9726       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9727                                                : CK_BitCast;
9728       if (LHSIsNull && !RHSIsNull)
9729         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9730       else
9731         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9732     }
9733     return ResultTy;
9734   }
9735
9736   if (getLangOpts().CPlusPlus) {
9737     // C++ [expr.eq]p4:
9738     //   Two operands of type std::nullptr_t or one operand of type
9739     //   std::nullptr_t and the other a null pointer constant compare equal.
9740     if (!IsRelational && LHSIsNull && RHSIsNull) {
9741       if (LHSType->isNullPtrType()) {
9742         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9743         return ResultTy;
9744       }
9745       if (RHSType->isNullPtrType()) {
9746         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9747         return ResultTy;
9748       }
9749     }
9750
9751     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9752     // These aren't covered by the composite pointer type rules.
9753     if (!IsRelational && RHSType->isNullPtrType() &&
9754         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9755       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9756       return ResultTy;
9757     }
9758     if (!IsRelational && LHSType->isNullPtrType() &&
9759         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9760       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9761       return ResultTy;
9762     }
9763
9764     if (IsRelational &&
9765         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9766          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9767       // HACK: Relational comparison of nullptr_t against a pointer type is
9768       // invalid per DR583, but we allow it within std::less<> and friends,
9769       // since otherwise common uses of it break.
9770       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9771       // friends to have std::nullptr_t overload candidates.
9772       DeclContext *DC = CurContext;
9773       if (isa<FunctionDecl>(DC))
9774         DC = DC->getParent();
9775       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9776         if (CTSD->isInStdNamespace() &&
9777             llvm::StringSwitch<bool>(CTSD->getName())
9778                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9779                 .Default(false)) {
9780           if (RHSType->isNullPtrType())
9781             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9782           else
9783             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9784           return ResultTy;
9785         }
9786       }
9787     }
9788
9789     // C++ [expr.eq]p2:
9790     //   If at least one operand is a pointer to member, [...] bring them to
9791     //   their composite pointer type.
9792     if (!IsRelational &&
9793         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9794       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9795         return QualType();
9796       else
9797         return ResultTy;
9798     }
9799
9800     // Handle scoped enumeration types specifically, since they don't promote
9801     // to integers.
9802     if (LHS.get()->getType()->isEnumeralType() &&
9803         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9804                                        RHS.get()->getType()))
9805       return ResultTy;
9806   }
9807
9808   // Handle block pointer types.
9809   if (!IsRelational && LHSType->isBlockPointerType() &&
9810       RHSType->isBlockPointerType()) {
9811     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9812     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9813
9814     if (!LHSIsNull && !RHSIsNull &&
9815         !Context.typesAreCompatible(lpointee, rpointee)) {
9816       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9817         << LHSType << RHSType << LHS.get()->getSourceRange()
9818         << RHS.get()->getSourceRange();
9819     }
9820     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9821     return ResultTy;
9822   }
9823
9824   // Allow block pointers to be compared with null pointer constants.
9825   if (!IsRelational
9826       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9827           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9828     if (!LHSIsNull && !RHSIsNull) {
9829       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9830              ->getPointeeType()->isVoidType())
9831             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9832                 ->getPointeeType()->isVoidType())))
9833         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9834           << LHSType << RHSType << LHS.get()->getSourceRange()
9835           << RHS.get()->getSourceRange();
9836     }
9837     if (LHSIsNull && !RHSIsNull)
9838       LHS = ImpCastExprToType(LHS.get(), RHSType,
9839                               RHSType->isPointerType() ? CK_BitCast
9840                                 : CK_AnyPointerToBlockPointerCast);
9841     else
9842       RHS = ImpCastExprToType(RHS.get(), LHSType,
9843                               LHSType->isPointerType() ? CK_BitCast
9844                                 : CK_AnyPointerToBlockPointerCast);
9845     return ResultTy;
9846   }
9847
9848   if (LHSType->isObjCObjectPointerType() ||
9849       RHSType->isObjCObjectPointerType()) {
9850     const PointerType *LPT = LHSType->getAs<PointerType>();
9851     const PointerType *RPT = RHSType->getAs<PointerType>();
9852     if (LPT || RPT) {
9853       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9854       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9855
9856       if (!LPtrToVoid && !RPtrToVoid &&
9857           !Context.typesAreCompatible(LHSType, RHSType)) {
9858         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9859                                           /*isError*/false);
9860       }
9861       if (LHSIsNull && !RHSIsNull) {
9862         Expr *E = LHS.get();
9863         if (getLangOpts().ObjCAutoRefCount)
9864           CheckObjCConversion(SourceRange(), RHSType, E,
9865                               CCK_ImplicitConversion);
9866         LHS = ImpCastExprToType(E, RHSType,
9867                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9868       }
9869       else {
9870         Expr *E = RHS.get();
9871         if (getLangOpts().ObjCAutoRefCount)
9872           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9873                               /*Diagnose=*/true,
9874                               /*DiagnoseCFAudited=*/false, Opc);
9875         RHS = ImpCastExprToType(E, LHSType,
9876                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9877       }
9878       return ResultTy;
9879     }
9880     if (LHSType->isObjCObjectPointerType() &&
9881         RHSType->isObjCObjectPointerType()) {
9882       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9883         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9884                                           /*isError*/false);
9885       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9886         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9887
9888       if (LHSIsNull && !RHSIsNull)
9889         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9890       else
9891         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9892       return ResultTy;
9893     }
9894   }
9895   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9896       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9897     unsigned DiagID = 0;
9898     bool isError = false;
9899     if (LangOpts.DebuggerSupport) {
9900       // Under a debugger, allow the comparison of pointers to integers,
9901       // since users tend to want to compare addresses.
9902     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9903                (RHSIsNull && RHSType->isIntegerType())) {
9904       if (IsRelational) {
9905         isError = getLangOpts().CPlusPlus;
9906         DiagID =
9907           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9908                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9909       }
9910     } else if (getLangOpts().CPlusPlus) {
9911       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9912       isError = true;
9913     } else if (IsRelational)
9914       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9915     else
9916       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9917
9918     if (DiagID) {
9919       Diag(Loc, DiagID)
9920         << LHSType << RHSType << LHS.get()->getSourceRange()
9921         << RHS.get()->getSourceRange();
9922       if (isError)
9923         return QualType();
9924     }
9925     
9926     if (LHSType->isIntegerType())
9927       LHS = ImpCastExprToType(LHS.get(), RHSType,
9928                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9929     else
9930       RHS = ImpCastExprToType(RHS.get(), LHSType,
9931                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9932     return ResultTy;
9933   }
9934   
9935   // Handle block pointers.
9936   if (!IsRelational && RHSIsNull
9937       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9938     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9939     return ResultTy;
9940   }
9941   if (!IsRelational && LHSIsNull
9942       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9943     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9944     return ResultTy;
9945   }
9946
9947   if (getLangOpts().OpenCLVersion >= 200) {
9948     if (LHSIsNull && RHSType->isQueueT()) {
9949       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9950       return ResultTy;
9951     }
9952
9953     if (LHSType->isQueueT() && RHSIsNull) {
9954       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9955       return ResultTy;
9956     }
9957   }
9958
9959   return InvalidOperands(Loc, LHS, RHS);
9960 }
9961
9962 // Return a signed ext_vector_type that is of identical size and number of
9963 // elements. For floating point vectors, return an integer type of identical
9964 // size and number of elements. In the non ext_vector_type case, search from
9965 // the largest type to the smallest type to avoid cases where long long == long,
9966 // where long gets picked over long long.
9967 QualType Sema::GetSignedVectorType(QualType V) {
9968   const VectorType *VTy = V->getAs<VectorType>();
9969   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9970
9971   if (isa<ExtVectorType>(VTy)) {
9972     if (TypeSize == Context.getTypeSize(Context.CharTy))
9973       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9974     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9975       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9976     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9977       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9978     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9979       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9980     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9981            "Unhandled vector element size in vector compare");
9982     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9983   }
9984
9985   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9986     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9987                                  VectorType::GenericVector);
9988   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9989     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9990                                  VectorType::GenericVector);
9991   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9992     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9993                                  VectorType::GenericVector);
9994   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9995     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9996                                  VectorType::GenericVector);
9997   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9998          "Unhandled vector element size in vector compare");
9999   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10000                                VectorType::GenericVector);
10001 }
10002
10003 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10004 /// operates on extended vector types.  Instead of producing an IntTy result,
10005 /// like a scalar comparison, a vector comparison produces a vector of integer
10006 /// types.
10007 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10008                                           SourceLocation Loc,
10009                                           bool IsRelational) {
10010   // Check to make sure we're operating on vectors of the same type and width,
10011   // Allowing one side to be a scalar of element type.
10012   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10013                               /*AllowBothBool*/true,
10014                               /*AllowBoolConversions*/getLangOpts().ZVector);
10015   if (vType.isNull())
10016     return vType;
10017
10018   QualType LHSType = LHS.get()->getType();
10019
10020   // If AltiVec, the comparison results in a numeric type, i.e.
10021   // bool for C++, int for C
10022   if (getLangOpts().AltiVec &&
10023       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10024     return Context.getLogicalOperationType();
10025
10026   // For non-floating point types, check for self-comparisons of the form
10027   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10028   // often indicate logic errors in the program.
10029   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
10030     if (DeclRefExpr* DRL
10031           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
10032       if (DeclRefExpr* DRR
10033             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
10034         if (DRL->getDecl() == DRR->getDecl())
10035           DiagRuntimeBehavior(Loc, nullptr,
10036                               PDiag(diag::warn_comparison_always)
10037                                 << 0 // self-
10038                                 << 2 // "a constant"
10039                               );
10040   }
10041
10042   // Check for comparisons of floating point operands using != and ==.
10043   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
10044     assert (RHS.get()->getType()->hasFloatingRepresentation());
10045     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10046   }
10047
10048   // Return a signed type for the vector.
10049   return GetSignedVectorType(vType);
10050 }
10051
10052 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10053                                           SourceLocation Loc) {
10054   // Ensure that either both operands are of the same vector type, or
10055   // one operand is of a vector type and the other is of its element type.
10056   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10057                                        /*AllowBothBool*/true,
10058                                        /*AllowBoolConversions*/false);
10059   if (vType.isNull())
10060     return InvalidOperands(Loc, LHS, RHS);
10061   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10062       vType->hasFloatingRepresentation())
10063     return InvalidOperands(Loc, LHS, RHS);
10064   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10065   //        usage of the logical operators && and || with vectors in C. This
10066   //        check could be notionally dropped.
10067   if (!getLangOpts().CPlusPlus &&
10068       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10069     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10070
10071   return GetSignedVectorType(LHS.get()->getType());
10072 }
10073
10074 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10075                                            SourceLocation Loc,
10076                                            BinaryOperatorKind Opc) {
10077   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10078
10079   bool IsCompAssign =
10080       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10081
10082   if (LHS.get()->getType()->isVectorType() ||
10083       RHS.get()->getType()->isVectorType()) {
10084     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10085         RHS.get()->getType()->hasIntegerRepresentation())
10086       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10087                         /*AllowBothBool*/true,
10088                         /*AllowBoolConversions*/getLangOpts().ZVector);
10089     return InvalidOperands(Loc, LHS, RHS);
10090   }
10091
10092   if (Opc == BO_And)
10093     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10094
10095   ExprResult LHSResult = LHS, RHSResult = RHS;
10096   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10097                                                  IsCompAssign);
10098   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10099     return QualType();
10100   LHS = LHSResult.get();
10101   RHS = RHSResult.get();
10102
10103   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10104     return compType;
10105   return InvalidOperands(Loc, LHS, RHS);
10106 }
10107
10108 // C99 6.5.[13,14]
10109 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10110                                            SourceLocation Loc,
10111                                            BinaryOperatorKind Opc) {
10112   // Check vector operands differently.
10113   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10114     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10115   
10116   // Diagnose cases where the user write a logical and/or but probably meant a
10117   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10118   // is a constant.
10119   if (LHS.get()->getType()->isIntegerType() &&
10120       !LHS.get()->getType()->isBooleanType() &&
10121       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10122       // Don't warn in macros or template instantiations.
10123       !Loc.isMacroID() && !inTemplateInstantiation()) {
10124     // If the RHS can be constant folded, and if it constant folds to something
10125     // that isn't 0 or 1 (which indicate a potential logical operation that
10126     // happened to fold to true/false) then warn.
10127     // Parens on the RHS are ignored.
10128     llvm::APSInt Result;
10129     if (RHS.get()->EvaluateAsInt(Result, Context))
10130       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10131            !RHS.get()->getExprLoc().isMacroID()) ||
10132           (Result != 0 && Result != 1)) {
10133         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10134           << RHS.get()->getSourceRange()
10135           << (Opc == BO_LAnd ? "&&" : "||");
10136         // Suggest replacing the logical operator with the bitwise version
10137         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10138             << (Opc == BO_LAnd ? "&" : "|")
10139             << FixItHint::CreateReplacement(SourceRange(
10140                                                  Loc, getLocForEndOfToken(Loc)),
10141                                             Opc == BO_LAnd ? "&" : "|");
10142         if (Opc == BO_LAnd)
10143           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10144           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10145               << FixItHint::CreateRemoval(
10146                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10147                               RHS.get()->getLocEnd()));
10148       }
10149   }
10150
10151   if (!Context.getLangOpts().CPlusPlus) {
10152     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10153     // not operate on the built-in scalar and vector float types.
10154     if (Context.getLangOpts().OpenCL &&
10155         Context.getLangOpts().OpenCLVersion < 120) {
10156       if (LHS.get()->getType()->isFloatingType() ||
10157           RHS.get()->getType()->isFloatingType())
10158         return InvalidOperands(Loc, LHS, RHS);
10159     }
10160
10161     LHS = UsualUnaryConversions(LHS.get());
10162     if (LHS.isInvalid())
10163       return QualType();
10164
10165     RHS = UsualUnaryConversions(RHS.get());
10166     if (RHS.isInvalid())
10167       return QualType();
10168
10169     if (!LHS.get()->getType()->isScalarType() ||
10170         !RHS.get()->getType()->isScalarType())
10171       return InvalidOperands(Loc, LHS, RHS);
10172
10173     return Context.IntTy;
10174   }
10175
10176   // The following is safe because we only use this method for
10177   // non-overloadable operands.
10178
10179   // C++ [expr.log.and]p1
10180   // C++ [expr.log.or]p1
10181   // The operands are both contextually converted to type bool.
10182   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10183   if (LHSRes.isInvalid())
10184     return InvalidOperands(Loc, LHS, RHS);
10185   LHS = LHSRes;
10186
10187   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10188   if (RHSRes.isInvalid())
10189     return InvalidOperands(Loc, LHS, RHS);
10190   RHS = RHSRes;
10191
10192   // C++ [expr.log.and]p2
10193   // C++ [expr.log.or]p2
10194   // The result is a bool.
10195   return Context.BoolTy;
10196 }
10197
10198 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10199   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10200   if (!ME) return false;
10201   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10202   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10203       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10204   if (!Base) return false;
10205   return Base->getMethodDecl() != nullptr;
10206 }
10207
10208 /// Is the given expression (which must be 'const') a reference to a
10209 /// variable which was originally non-const, but which has become
10210 /// 'const' due to being captured within a block?
10211 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10212 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10213   assert(E->isLValue() && E->getType().isConstQualified());
10214   E = E->IgnoreParens();
10215
10216   // Must be a reference to a declaration from an enclosing scope.
10217   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10218   if (!DRE) return NCCK_None;
10219   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10220
10221   // The declaration must be a variable which is not declared 'const'.
10222   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10223   if (!var) return NCCK_None;
10224   if (var->getType().isConstQualified()) return NCCK_None;
10225   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10226
10227   // Decide whether the first capture was for a block or a lambda.
10228   DeclContext *DC = S.CurContext, *Prev = nullptr;
10229   // Decide whether the first capture was for a block or a lambda.
10230   while (DC) {
10231     // For init-capture, it is possible that the variable belongs to the
10232     // template pattern of the current context.
10233     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10234       if (var->isInitCapture() &&
10235           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10236         break;
10237     if (DC == var->getDeclContext())
10238       break;
10239     Prev = DC;
10240     DC = DC->getParent();
10241   }
10242   // Unless we have an init-capture, we've gone one step too far.
10243   if (!var->isInitCapture())
10244     DC = Prev;
10245   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10246 }
10247
10248 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10249   Ty = Ty.getNonReferenceType();
10250   if (IsDereference && Ty->isPointerType())
10251     Ty = Ty->getPointeeType();
10252   return !Ty.isConstQualified();
10253 }
10254
10255 /// Emit the "read-only variable not assignable" error and print notes to give
10256 /// more information about why the variable is not assignable, such as pointing
10257 /// to the declaration of a const variable, showing that a method is const, or
10258 /// that the function is returning a const reference.
10259 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10260                                     SourceLocation Loc) {
10261   // Update err_typecheck_assign_const and note_typecheck_assign_const
10262   // when this enum is changed.
10263   enum {
10264     ConstFunction,
10265     ConstVariable,
10266     ConstMember,
10267     ConstMethod,
10268     ConstUnknown,  // Keep as last element
10269   };
10270
10271   SourceRange ExprRange = E->getSourceRange();
10272
10273   // Only emit one error on the first const found.  All other consts will emit
10274   // a note to the error.
10275   bool DiagnosticEmitted = false;
10276
10277   // Track if the current expression is the result of a dereference, and if the
10278   // next checked expression is the result of a dereference.
10279   bool IsDereference = false;
10280   bool NextIsDereference = false;
10281
10282   // Loop to process MemberExpr chains.
10283   while (true) {
10284     IsDereference = NextIsDereference;
10285
10286     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10287     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10288       NextIsDereference = ME->isArrow();
10289       const ValueDecl *VD = ME->getMemberDecl();
10290       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10291         // Mutable fields can be modified even if the class is const.
10292         if (Field->isMutable()) {
10293           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10294           break;
10295         }
10296
10297         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10298           if (!DiagnosticEmitted) {
10299             S.Diag(Loc, diag::err_typecheck_assign_const)
10300                 << ExprRange << ConstMember << false /*static*/ << Field
10301                 << Field->getType();
10302             DiagnosticEmitted = true;
10303           }
10304           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10305               << ConstMember << false /*static*/ << Field << Field->getType()
10306               << Field->getSourceRange();
10307         }
10308         E = ME->getBase();
10309         continue;
10310       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10311         if (VDecl->getType().isConstQualified()) {
10312           if (!DiagnosticEmitted) {
10313             S.Diag(Loc, diag::err_typecheck_assign_const)
10314                 << ExprRange << ConstMember << true /*static*/ << VDecl
10315                 << VDecl->getType();
10316             DiagnosticEmitted = true;
10317           }
10318           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10319               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10320               << VDecl->getSourceRange();
10321         }
10322         // Static fields do not inherit constness from parents.
10323         break;
10324       }
10325       break;
10326     } // End MemberExpr
10327     break;
10328   }
10329
10330   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10331     // Function calls
10332     const FunctionDecl *FD = CE->getDirectCallee();
10333     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10334       if (!DiagnosticEmitted) {
10335         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10336                                                       << ConstFunction << FD;
10337         DiagnosticEmitted = true;
10338       }
10339       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10340              diag::note_typecheck_assign_const)
10341           << ConstFunction << FD << FD->getReturnType()
10342           << FD->getReturnTypeSourceRange();
10343     }
10344   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10345     // Point to variable declaration.
10346     if (const ValueDecl *VD = DRE->getDecl()) {
10347       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10348         if (!DiagnosticEmitted) {
10349           S.Diag(Loc, diag::err_typecheck_assign_const)
10350               << ExprRange << ConstVariable << VD << VD->getType();
10351           DiagnosticEmitted = true;
10352         }
10353         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10354             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10355       }
10356     }
10357   } else if (isa<CXXThisExpr>(E)) {
10358     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10359       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10360         if (MD->isConst()) {
10361           if (!DiagnosticEmitted) {
10362             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10363                                                           << ConstMethod << MD;
10364             DiagnosticEmitted = true;
10365           }
10366           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10367               << ConstMethod << MD << MD->getSourceRange();
10368         }
10369       }
10370     }
10371   }
10372
10373   if (DiagnosticEmitted)
10374     return;
10375
10376   // Can't determine a more specific message, so display the generic error.
10377   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10378 }
10379
10380 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10381 /// emit an error and return true.  If so, return false.
10382 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10383   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10384
10385   S.CheckShadowingDeclModification(E, Loc);
10386
10387   SourceLocation OrigLoc = Loc;
10388   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10389                                                               &Loc);
10390   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10391     IsLV = Expr::MLV_InvalidMessageExpression;
10392   if (IsLV == Expr::MLV_Valid)
10393     return false;
10394
10395   unsigned DiagID = 0;
10396   bool NeedType = false;
10397   switch (IsLV) { // C99 6.5.16p2
10398   case Expr::MLV_ConstQualified:
10399     // Use a specialized diagnostic when we're assigning to an object
10400     // from an enclosing function or block.
10401     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10402       if (NCCK == NCCK_Block)
10403         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10404       else
10405         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10406       break;
10407     }
10408
10409     // In ARC, use some specialized diagnostics for occasions where we
10410     // infer 'const'.  These are always pseudo-strong variables.
10411     if (S.getLangOpts().ObjCAutoRefCount) {
10412       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10413       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10414         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10415
10416         // Use the normal diagnostic if it's pseudo-__strong but the
10417         // user actually wrote 'const'.
10418         if (var->isARCPseudoStrong() &&
10419             (!var->getTypeSourceInfo() ||
10420              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10421           // There are two pseudo-strong cases:
10422           //  - self
10423           ObjCMethodDecl *method = S.getCurMethodDecl();
10424           if (method && var == method->getSelfDecl())
10425             DiagID = method->isClassMethod()
10426               ? diag::err_typecheck_arc_assign_self_class_method
10427               : diag::err_typecheck_arc_assign_self;
10428
10429           //  - fast enumeration variables
10430           else
10431             DiagID = diag::err_typecheck_arr_assign_enumeration;
10432
10433           SourceRange Assign;
10434           if (Loc != OrigLoc)
10435             Assign = SourceRange(OrigLoc, OrigLoc);
10436           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10437           // We need to preserve the AST regardless, so migration tool
10438           // can do its job.
10439           return false;
10440         }
10441       }
10442     }
10443
10444     // If none of the special cases above are triggered, then this is a
10445     // simple const assignment.
10446     if (DiagID == 0) {
10447       DiagnoseConstAssignment(S, E, Loc);
10448       return true;
10449     }
10450
10451     break;
10452   case Expr::MLV_ConstAddrSpace:
10453     DiagnoseConstAssignment(S, E, Loc);
10454     return true;
10455   case Expr::MLV_ArrayType:
10456   case Expr::MLV_ArrayTemporary:
10457     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10458     NeedType = true;
10459     break;
10460   case Expr::MLV_NotObjectType:
10461     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10462     NeedType = true;
10463     break;
10464   case Expr::MLV_LValueCast:
10465     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10466     break;
10467   case Expr::MLV_Valid:
10468     llvm_unreachable("did not take early return for MLV_Valid");
10469   case Expr::MLV_InvalidExpression:
10470   case Expr::MLV_MemberFunction:
10471   case Expr::MLV_ClassTemporary:
10472     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10473     break;
10474   case Expr::MLV_IncompleteType:
10475   case Expr::MLV_IncompleteVoidType:
10476     return S.RequireCompleteType(Loc, E->getType(),
10477              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10478   case Expr::MLV_DuplicateVectorComponents:
10479     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10480     break;
10481   case Expr::MLV_NoSetterProperty:
10482     llvm_unreachable("readonly properties should be processed differently");
10483   case Expr::MLV_InvalidMessageExpression:
10484     DiagID = diag::err_readonly_message_assignment;
10485     break;
10486   case Expr::MLV_SubObjCPropertySetting:
10487     DiagID = diag::err_no_subobject_property_setting;
10488     break;
10489   }
10490
10491   SourceRange Assign;
10492   if (Loc != OrigLoc)
10493     Assign = SourceRange(OrigLoc, OrigLoc);
10494   if (NeedType)
10495     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10496   else
10497     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10498   return true;
10499 }
10500
10501 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10502                                          SourceLocation Loc,
10503                                          Sema &Sema) {
10504   // C / C++ fields
10505   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10506   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10507   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10508     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10509       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10510   }
10511
10512   // Objective-C instance variables
10513   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10514   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10515   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10516     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10517     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10518     if (RL && RR && RL->getDecl() == RR->getDecl())
10519       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10520   }
10521 }
10522
10523 // C99 6.5.16.1
10524 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10525                                        SourceLocation Loc,
10526                                        QualType CompoundType) {
10527   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10528
10529   // Verify that LHS is a modifiable lvalue, and emit error if not.
10530   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10531     return QualType();
10532
10533   QualType LHSType = LHSExpr->getType();
10534   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10535                                              CompoundType;
10536   // OpenCL v1.2 s6.1.1.1 p2:
10537   // The half data type can only be used to declare a pointer to a buffer that
10538   // contains half values
10539   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10540     LHSType->isHalfType()) {
10541     Diag(Loc, diag::err_opencl_half_load_store) << 1
10542         << LHSType.getUnqualifiedType();
10543     return QualType();
10544   }
10545     
10546   AssignConvertType ConvTy;
10547   if (CompoundType.isNull()) {
10548     Expr *RHSCheck = RHS.get();
10549
10550     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10551
10552     QualType LHSTy(LHSType);
10553     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10554     if (RHS.isInvalid())
10555       return QualType();
10556     // Special case of NSObject attributes on c-style pointer types.
10557     if (ConvTy == IncompatiblePointer &&
10558         ((Context.isObjCNSObjectType(LHSType) &&
10559           RHSType->isObjCObjectPointerType()) ||
10560          (Context.isObjCNSObjectType(RHSType) &&
10561           LHSType->isObjCObjectPointerType())))
10562       ConvTy = Compatible;
10563
10564     if (ConvTy == Compatible &&
10565         LHSType->isObjCObjectType())
10566         Diag(Loc, diag::err_objc_object_assignment)
10567           << LHSType;
10568
10569     // If the RHS is a unary plus or minus, check to see if they = and + are
10570     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10571     // instead of "x += 4".
10572     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10573       RHSCheck = ICE->getSubExpr();
10574     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10575       if ((UO->getOpcode() == UO_Plus ||
10576            UO->getOpcode() == UO_Minus) &&
10577           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10578           // Only if the two operators are exactly adjacent.
10579           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10580           // And there is a space or other character before the subexpr of the
10581           // unary +/-.  We don't want to warn on "x=-1".
10582           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10583           UO->getSubExpr()->getLocStart().isFileID()) {
10584         Diag(Loc, diag::warn_not_compound_assign)
10585           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10586           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10587       }
10588     }
10589
10590     if (ConvTy == Compatible) {
10591       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10592         // Warn about retain cycles where a block captures the LHS, but
10593         // not if the LHS is a simple variable into which the block is
10594         // being stored...unless that variable can be captured by reference!
10595         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10596         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10597         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10598           checkRetainCycles(LHSExpr, RHS.get());
10599       }
10600
10601       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10602           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10603         // It is safe to assign a weak reference into a strong variable.
10604         // Although this code can still have problems:
10605         //   id x = self.weakProp;
10606         //   id y = self.weakProp;
10607         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10608         // paths through the function. This should be revisited if
10609         // -Wrepeated-use-of-weak is made flow-sensitive.
10610         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10611         // variable, which will be valid for the current autorelease scope.
10612         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10613                              RHS.get()->getLocStart()))
10614           getCurFunction()->markSafeWeakUse(RHS.get());
10615
10616       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10617         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10618       }
10619     }
10620   } else {
10621     // Compound assignment "x += y"
10622     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10623   }
10624
10625   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10626                                RHS.get(), AA_Assigning))
10627     return QualType();
10628
10629   CheckForNullPointerDereference(*this, LHSExpr);
10630
10631   // C99 6.5.16p3: The type of an assignment expression is the type of the
10632   // left operand unless the left operand has qualified type, in which case
10633   // it is the unqualified version of the type of the left operand.
10634   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10635   // is converted to the type of the assignment expression (above).
10636   // C++ 5.17p1: the type of the assignment expression is that of its left
10637   // operand.
10638   return (getLangOpts().CPlusPlus
10639           ? LHSType : LHSType.getUnqualifiedType());
10640 }
10641
10642 // Only ignore explicit casts to void.
10643 static bool IgnoreCommaOperand(const Expr *E) {
10644   E = E->IgnoreParens();
10645
10646   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10647     if (CE->getCastKind() == CK_ToVoid) {
10648       return true;
10649     }
10650   }
10651
10652   return false;
10653 }
10654
10655 // Look for instances where it is likely the comma operator is confused with
10656 // another operator.  There is a whitelist of acceptable expressions for the
10657 // left hand side of the comma operator, otherwise emit a warning.
10658 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10659   // No warnings in macros
10660   if (Loc.isMacroID())
10661     return;
10662
10663   // Don't warn in template instantiations.
10664   if (inTemplateInstantiation())
10665     return;
10666
10667   // Scope isn't fine-grained enough to whitelist the specific cases, so
10668   // instead, skip more than needed, then call back into here with the
10669   // CommaVisitor in SemaStmt.cpp.
10670   // The whitelisted locations are the initialization and increment portions
10671   // of a for loop.  The additional checks are on the condition of
10672   // if statements, do/while loops, and for loops.
10673   const unsigned ForIncrementFlags =
10674       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10675   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10676   const unsigned ScopeFlags = getCurScope()->getFlags();
10677   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10678       (ScopeFlags & ForInitFlags) == ForInitFlags)
10679     return;
10680
10681   // If there are multiple comma operators used together, get the RHS of the
10682   // of the comma operator as the LHS.
10683   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10684     if (BO->getOpcode() != BO_Comma)
10685       break;
10686     LHS = BO->getRHS();
10687   }
10688
10689   // Only allow some expressions on LHS to not warn.
10690   if (IgnoreCommaOperand(LHS))
10691     return;
10692
10693   Diag(Loc, diag::warn_comma_operator);
10694   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10695       << LHS->getSourceRange()
10696       << FixItHint::CreateInsertion(LHS->getLocStart(),
10697                                     LangOpts.CPlusPlus ? "static_cast<void>("
10698                                                        : "(void)(")
10699       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10700                                     ")");
10701 }
10702
10703 // C99 6.5.17
10704 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10705                                    SourceLocation Loc) {
10706   LHS = S.CheckPlaceholderExpr(LHS.get());
10707   RHS = S.CheckPlaceholderExpr(RHS.get());
10708   if (LHS.isInvalid() || RHS.isInvalid())
10709     return QualType();
10710
10711   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10712   // operands, but not unary promotions.
10713   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10714
10715   // So we treat the LHS as a ignored value, and in C++ we allow the
10716   // containing site to determine what should be done with the RHS.
10717   LHS = S.IgnoredValueConversions(LHS.get());
10718   if (LHS.isInvalid())
10719     return QualType();
10720
10721   S.DiagnoseUnusedExprResult(LHS.get());
10722
10723   if (!S.getLangOpts().CPlusPlus) {
10724     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10725     if (RHS.isInvalid())
10726       return QualType();
10727     if (!RHS.get()->getType()->isVoidType())
10728       S.RequireCompleteType(Loc, RHS.get()->getType(),
10729                             diag::err_incomplete_type);
10730   }
10731
10732   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10733     S.DiagnoseCommaOperator(LHS.get(), Loc);
10734
10735   return RHS.get()->getType();
10736 }
10737
10738 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10739 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10740 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10741                                                ExprValueKind &VK,
10742                                                ExprObjectKind &OK,
10743                                                SourceLocation OpLoc,
10744                                                bool IsInc, bool IsPrefix) {
10745   if (Op->isTypeDependent())
10746     return S.Context.DependentTy;
10747
10748   QualType ResType = Op->getType();
10749   // Atomic types can be used for increment / decrement where the non-atomic
10750   // versions can, so ignore the _Atomic() specifier for the purpose of
10751   // checking.
10752   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10753     ResType = ResAtomicType->getValueType();
10754
10755   assert(!ResType.isNull() && "no type for increment/decrement expression");
10756
10757   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10758     // Decrement of bool is not allowed.
10759     if (!IsInc) {
10760       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10761       return QualType();
10762     }
10763     // Increment of bool sets it to true, but is deprecated.
10764     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10765                                               : diag::warn_increment_bool)
10766       << Op->getSourceRange();
10767   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10768     // Error on enum increments and decrements in C++ mode
10769     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10770     return QualType();
10771   } else if (ResType->isRealType()) {
10772     // OK!
10773   } else if (ResType->isPointerType()) {
10774     // C99 6.5.2.4p2, 6.5.6p2
10775     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10776       return QualType();
10777   } else if (ResType->isObjCObjectPointerType()) {
10778     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10779     // Otherwise, we just need a complete type.
10780     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10781         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10782       return QualType();    
10783   } else if (ResType->isAnyComplexType()) {
10784     // C99 does not support ++/-- on complex types, we allow as an extension.
10785     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10786       << ResType << Op->getSourceRange();
10787   } else if (ResType->isPlaceholderType()) {
10788     ExprResult PR = S.CheckPlaceholderExpr(Op);
10789     if (PR.isInvalid()) return QualType();
10790     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10791                                           IsInc, IsPrefix);
10792   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10793     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10794   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10795              (ResType->getAs<VectorType>()->getVectorKind() !=
10796               VectorType::AltiVecBool)) {
10797     // The z vector extensions allow ++ and -- for non-bool vectors.
10798   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10799             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10800     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10801   } else {
10802     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10803       << ResType << int(IsInc) << Op->getSourceRange();
10804     return QualType();
10805   }
10806   // At this point, we know we have a real, complex or pointer type.
10807   // Now make sure the operand is a modifiable lvalue.
10808   if (CheckForModifiableLvalue(Op, OpLoc, S))
10809     return QualType();
10810   // In C++, a prefix increment is the same type as the operand. Otherwise
10811   // (in C or with postfix), the increment is the unqualified type of the
10812   // operand.
10813   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10814     VK = VK_LValue;
10815     OK = Op->getObjectKind();
10816     return ResType;
10817   } else {
10818     VK = VK_RValue;
10819     return ResType.getUnqualifiedType();
10820   }
10821 }
10822   
10823
10824 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10825 /// This routine allows us to typecheck complex/recursive expressions
10826 /// where the declaration is needed for type checking. We only need to
10827 /// handle cases when the expression references a function designator
10828 /// or is an lvalue. Here are some examples:
10829 ///  - &(x) => x
10830 ///  - &*****f => f for f a function designator.
10831 ///  - &s.xx => s
10832 ///  - &s.zz[1].yy -> s, if zz is an array
10833 ///  - *(x + 1) -> x, if x is an array
10834 ///  - &"123"[2] -> 0
10835 ///  - & __real__ x -> x
10836 static ValueDecl *getPrimaryDecl(Expr *E) {
10837   switch (E->getStmtClass()) {
10838   case Stmt::DeclRefExprClass:
10839     return cast<DeclRefExpr>(E)->getDecl();
10840   case Stmt::MemberExprClass:
10841     // If this is an arrow operator, the address is an offset from
10842     // the base's value, so the object the base refers to is
10843     // irrelevant.
10844     if (cast<MemberExpr>(E)->isArrow())
10845       return nullptr;
10846     // Otherwise, the expression refers to a part of the base
10847     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10848   case Stmt::ArraySubscriptExprClass: {
10849     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10850     // promotion of register arrays earlier.
10851     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10852     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10853       if (ICE->getSubExpr()->getType()->isArrayType())
10854         return getPrimaryDecl(ICE->getSubExpr());
10855     }
10856     return nullptr;
10857   }
10858   case Stmt::UnaryOperatorClass: {
10859     UnaryOperator *UO = cast<UnaryOperator>(E);
10860
10861     switch(UO->getOpcode()) {
10862     case UO_Real:
10863     case UO_Imag:
10864     case UO_Extension:
10865       return getPrimaryDecl(UO->getSubExpr());
10866     default:
10867       return nullptr;
10868     }
10869   }
10870   case Stmt::ParenExprClass:
10871     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10872   case Stmt::ImplicitCastExprClass:
10873     // If the result of an implicit cast is an l-value, we care about
10874     // the sub-expression; otherwise, the result here doesn't matter.
10875     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10876   default:
10877     return nullptr;
10878   }
10879 }
10880
10881 namespace {
10882   enum {
10883     AO_Bit_Field = 0,
10884     AO_Vector_Element = 1,
10885     AO_Property_Expansion = 2,
10886     AO_Register_Variable = 3,
10887     AO_No_Error = 4
10888   };
10889 }
10890 /// \brief Diagnose invalid operand for address of operations.
10891 ///
10892 /// \param Type The type of operand which cannot have its address taken.
10893 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10894                                          Expr *E, unsigned Type) {
10895   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10896 }
10897
10898 /// CheckAddressOfOperand - The operand of & must be either a function
10899 /// designator or an lvalue designating an object. If it is an lvalue, the
10900 /// object cannot be declared with storage class register or be a bit field.
10901 /// Note: The usual conversions are *not* applied to the operand of the &
10902 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10903 /// In C++, the operand might be an overloaded function name, in which case
10904 /// we allow the '&' but retain the overloaded-function type.
10905 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10906   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10907     if (PTy->getKind() == BuiltinType::Overload) {
10908       Expr *E = OrigOp.get()->IgnoreParens();
10909       if (!isa<OverloadExpr>(E)) {
10910         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10911         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10912           << OrigOp.get()->getSourceRange();
10913         return QualType();
10914       }
10915
10916       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10917       if (isa<UnresolvedMemberExpr>(Ovl))
10918         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10919           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10920             << OrigOp.get()->getSourceRange();
10921           return QualType();
10922         }
10923
10924       return Context.OverloadTy;
10925     }
10926
10927     if (PTy->getKind() == BuiltinType::UnknownAny)
10928       return Context.UnknownAnyTy;
10929
10930     if (PTy->getKind() == BuiltinType::BoundMember) {
10931       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10932         << OrigOp.get()->getSourceRange();
10933       return QualType();
10934     }
10935
10936     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10937     if (OrigOp.isInvalid()) return QualType();
10938   }
10939
10940   if (OrigOp.get()->isTypeDependent())
10941     return Context.DependentTy;
10942
10943   assert(!OrigOp.get()->getType()->isPlaceholderType());
10944
10945   // Make sure to ignore parentheses in subsequent checks
10946   Expr *op = OrigOp.get()->IgnoreParens();
10947
10948   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10949   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10950     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10951     return QualType();
10952   }
10953
10954   if (getLangOpts().C99) {
10955     // Implement C99-only parts of addressof rules.
10956     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10957       if (uOp->getOpcode() == UO_Deref)
10958         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10959         // (assuming the deref expression is valid).
10960         return uOp->getSubExpr()->getType();
10961     }
10962     // Technically, there should be a check for array subscript
10963     // expressions here, but the result of one is always an lvalue anyway.
10964   }
10965   ValueDecl *dcl = getPrimaryDecl(op);
10966
10967   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10968     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10969                                            op->getLocStart()))
10970       return QualType();
10971
10972   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10973   unsigned AddressOfError = AO_No_Error;
10974
10975   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10976     bool sfinae = (bool)isSFINAEContext();
10977     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10978                                   : diag::ext_typecheck_addrof_temporary)
10979       << op->getType() << op->getSourceRange();
10980     if (sfinae)
10981       return QualType();
10982     // Materialize the temporary as an lvalue so that we can take its address.
10983     OrigOp = op =
10984         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10985   } else if (isa<ObjCSelectorExpr>(op)) {
10986     return Context.getPointerType(op->getType());
10987   } else if (lval == Expr::LV_MemberFunction) {
10988     // If it's an instance method, make a member pointer.
10989     // The expression must have exactly the form &A::foo.
10990
10991     // If the underlying expression isn't a decl ref, give up.
10992     if (!isa<DeclRefExpr>(op)) {
10993       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10994         << OrigOp.get()->getSourceRange();
10995       return QualType();
10996     }
10997     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10998     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10999
11000     // The id-expression was parenthesized.
11001     if (OrigOp.get() != DRE) {
11002       Diag(OpLoc, diag::err_parens_pointer_member_function)
11003         << OrigOp.get()->getSourceRange();
11004
11005     // The method was named without a qualifier.
11006     } else if (!DRE->getQualifier()) {
11007       if (MD->getParent()->getName().empty())
11008         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11009           << op->getSourceRange();
11010       else {
11011         SmallString<32> Str;
11012         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11013         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11014           << op->getSourceRange()
11015           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11016       }
11017     }
11018
11019     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11020     if (isa<CXXDestructorDecl>(MD))
11021       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11022
11023     QualType MPTy = Context.getMemberPointerType(
11024         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11025     // Under the MS ABI, lock down the inheritance model now.
11026     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11027       (void)isCompleteType(OpLoc, MPTy);
11028     return MPTy;
11029   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11030     // C99 6.5.3.2p1
11031     // The operand must be either an l-value or a function designator
11032     if (!op->getType()->isFunctionType()) {
11033       // Use a special diagnostic for loads from property references.
11034       if (isa<PseudoObjectExpr>(op)) {
11035         AddressOfError = AO_Property_Expansion;
11036       } else {
11037         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11038           << op->getType() << op->getSourceRange();
11039         return QualType();
11040       }
11041     }
11042   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11043     // The operand cannot be a bit-field
11044     AddressOfError = AO_Bit_Field;
11045   } else if (op->getObjectKind() == OK_VectorComponent) {
11046     // The operand cannot be an element of a vector
11047     AddressOfError = AO_Vector_Element;
11048   } else if (dcl) { // C99 6.5.3.2p1
11049     // We have an lvalue with a decl. Make sure the decl is not declared
11050     // with the register storage-class specifier.
11051     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11052       // in C++ it is not error to take address of a register
11053       // variable (c++03 7.1.1P3)
11054       if (vd->getStorageClass() == SC_Register &&
11055           !getLangOpts().CPlusPlus) {
11056         AddressOfError = AO_Register_Variable;
11057       }
11058     } else if (isa<MSPropertyDecl>(dcl)) {
11059       AddressOfError = AO_Property_Expansion;
11060     } else if (isa<FunctionTemplateDecl>(dcl)) {
11061       return Context.OverloadTy;
11062     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11063       // Okay: we can take the address of a field.
11064       // Could be a pointer to member, though, if there is an explicit
11065       // scope qualifier for the class.
11066       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11067         DeclContext *Ctx = dcl->getDeclContext();
11068         if (Ctx && Ctx->isRecord()) {
11069           if (dcl->getType()->isReferenceType()) {
11070             Diag(OpLoc,
11071                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11072               << dcl->getDeclName() << dcl->getType();
11073             return QualType();
11074           }
11075
11076           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11077             Ctx = Ctx->getParent();
11078
11079           QualType MPTy = Context.getMemberPointerType(
11080               op->getType(),
11081               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11082           // Under the MS ABI, lock down the inheritance model now.
11083           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11084             (void)isCompleteType(OpLoc, MPTy);
11085           return MPTy;
11086         }
11087       }
11088     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11089                !isa<BindingDecl>(dcl))
11090       llvm_unreachable("Unknown/unexpected decl type");
11091   }
11092
11093   if (AddressOfError != AO_No_Error) {
11094     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11095     return QualType();
11096   }
11097
11098   if (lval == Expr::LV_IncompleteVoidType) {
11099     // Taking the address of a void variable is technically illegal, but we
11100     // allow it in cases which are otherwise valid.
11101     // Example: "extern void x; void* y = &x;".
11102     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11103   }
11104
11105   // If the operand has type "type", the result has type "pointer to type".
11106   if (op->getType()->isObjCObjectType())
11107     return Context.getObjCObjectPointerType(op->getType());
11108
11109   CheckAddressOfPackedMember(op);
11110
11111   return Context.getPointerType(op->getType());
11112 }
11113
11114 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11115   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11116   if (!DRE)
11117     return;
11118   const Decl *D = DRE->getDecl();
11119   if (!D)
11120     return;
11121   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11122   if (!Param)
11123     return;
11124   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11125     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11126       return;
11127   if (FunctionScopeInfo *FD = S.getCurFunction())
11128     if (!FD->ModifiedNonNullParams.count(Param))
11129       FD->ModifiedNonNullParams.insert(Param);
11130 }
11131
11132 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11133 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11134                                         SourceLocation OpLoc) {
11135   if (Op->isTypeDependent())
11136     return S.Context.DependentTy;
11137
11138   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11139   if (ConvResult.isInvalid())
11140     return QualType();
11141   Op = ConvResult.get();
11142   QualType OpTy = Op->getType();
11143   QualType Result;
11144
11145   if (isa<CXXReinterpretCastExpr>(Op)) {
11146     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11147     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11148                                      Op->getSourceRange());
11149   }
11150
11151   if (const PointerType *PT = OpTy->getAs<PointerType>())
11152   {
11153     Result = PT->getPointeeType();
11154   }
11155   else if (const ObjCObjectPointerType *OPT =
11156              OpTy->getAs<ObjCObjectPointerType>())
11157     Result = OPT->getPointeeType();
11158   else {
11159     ExprResult PR = S.CheckPlaceholderExpr(Op);
11160     if (PR.isInvalid()) return QualType();
11161     if (PR.get() != Op)
11162       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11163   }
11164
11165   if (Result.isNull()) {
11166     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11167       << OpTy << Op->getSourceRange();
11168     return QualType();
11169   }
11170
11171   // Note that per both C89 and C99, indirection is always legal, even if Result
11172   // is an incomplete type or void.  It would be possible to warn about
11173   // dereferencing a void pointer, but it's completely well-defined, and such a
11174   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11175   // for pointers to 'void' but is fine for any other pointer type:
11176   //
11177   // C++ [expr.unary.op]p1:
11178   //   [...] the expression to which [the unary * operator] is applied shall
11179   //   be a pointer to an object type, or a pointer to a function type
11180   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11181     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11182       << OpTy << Op->getSourceRange();
11183
11184   // Dereferences are usually l-values...
11185   VK = VK_LValue;
11186
11187   // ...except that certain expressions are never l-values in C.
11188   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11189     VK = VK_RValue;
11190   
11191   return Result;
11192 }
11193
11194 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11195   BinaryOperatorKind Opc;
11196   switch (Kind) {
11197   default: llvm_unreachable("Unknown binop!");
11198   case tok::periodstar:           Opc = BO_PtrMemD; break;
11199   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11200   case tok::star:                 Opc = BO_Mul; break;
11201   case tok::slash:                Opc = BO_Div; break;
11202   case tok::percent:              Opc = BO_Rem; break;
11203   case tok::plus:                 Opc = BO_Add; break;
11204   case tok::minus:                Opc = BO_Sub; break;
11205   case tok::lessless:             Opc = BO_Shl; break;
11206   case tok::greatergreater:       Opc = BO_Shr; break;
11207   case tok::lessequal:            Opc = BO_LE; break;
11208   case tok::less:                 Opc = BO_LT; break;
11209   case tok::greaterequal:         Opc = BO_GE; break;
11210   case tok::greater:              Opc = BO_GT; break;
11211   case tok::exclaimequal:         Opc = BO_NE; break;
11212   case tok::equalequal:           Opc = BO_EQ; break;
11213   case tok::amp:                  Opc = BO_And; break;
11214   case tok::caret:                Opc = BO_Xor; break;
11215   case tok::pipe:                 Opc = BO_Or; break;
11216   case tok::ampamp:               Opc = BO_LAnd; break;
11217   case tok::pipepipe:             Opc = BO_LOr; break;
11218   case tok::equal:                Opc = BO_Assign; break;
11219   case tok::starequal:            Opc = BO_MulAssign; break;
11220   case tok::slashequal:           Opc = BO_DivAssign; break;
11221   case tok::percentequal:         Opc = BO_RemAssign; break;
11222   case tok::plusequal:            Opc = BO_AddAssign; break;
11223   case tok::minusequal:           Opc = BO_SubAssign; break;
11224   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11225   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11226   case tok::ampequal:             Opc = BO_AndAssign; break;
11227   case tok::caretequal:           Opc = BO_XorAssign; break;
11228   case tok::pipeequal:            Opc = BO_OrAssign; break;
11229   case tok::comma:                Opc = BO_Comma; break;
11230   }
11231   return Opc;
11232 }
11233
11234 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11235   tok::TokenKind Kind) {
11236   UnaryOperatorKind Opc;
11237   switch (Kind) {
11238   default: llvm_unreachable("Unknown unary op!");
11239   case tok::plusplus:     Opc = UO_PreInc; break;
11240   case tok::minusminus:   Opc = UO_PreDec; break;
11241   case tok::amp:          Opc = UO_AddrOf; break;
11242   case tok::star:         Opc = UO_Deref; break;
11243   case tok::plus:         Opc = UO_Plus; break;
11244   case tok::minus:        Opc = UO_Minus; break;
11245   case tok::tilde:        Opc = UO_Not; break;
11246   case tok::exclaim:      Opc = UO_LNot; break;
11247   case tok::kw___real:    Opc = UO_Real; break;
11248   case tok::kw___imag:    Opc = UO_Imag; break;
11249   case tok::kw___extension__: Opc = UO_Extension; break;
11250   }
11251   return Opc;
11252 }
11253
11254 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11255 /// This warning is only emitted for builtin assignment operations. It is also
11256 /// suppressed in the event of macro expansions.
11257 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11258                                    SourceLocation OpLoc) {
11259   if (S.inTemplateInstantiation())
11260     return;
11261   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11262     return;
11263   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11264   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11265   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11266   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11267   if (!LHSDeclRef || !RHSDeclRef ||
11268       LHSDeclRef->getLocation().isMacroID() ||
11269       RHSDeclRef->getLocation().isMacroID())
11270     return;
11271   const ValueDecl *LHSDecl =
11272     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11273   const ValueDecl *RHSDecl =
11274     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11275   if (LHSDecl != RHSDecl)
11276     return;
11277   if (LHSDecl->getType().isVolatileQualified())
11278     return;
11279   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11280     if (RefTy->getPointeeType().isVolatileQualified())
11281       return;
11282
11283   S.Diag(OpLoc, diag::warn_self_assignment)
11284       << LHSDeclRef->getType()
11285       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11286 }
11287
11288 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11289 /// is usually indicative of introspection within the Objective-C pointer.
11290 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11291                                           SourceLocation OpLoc) {
11292   if (!S.getLangOpts().ObjC1)
11293     return;
11294
11295   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11296   const Expr *LHS = L.get();
11297   const Expr *RHS = R.get();
11298
11299   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11300     ObjCPointerExpr = LHS;
11301     OtherExpr = RHS;
11302   }
11303   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11304     ObjCPointerExpr = RHS;
11305     OtherExpr = LHS;
11306   }
11307
11308   // This warning is deliberately made very specific to reduce false
11309   // positives with logic that uses '&' for hashing.  This logic mainly
11310   // looks for code trying to introspect into tagged pointers, which
11311   // code should generally never do.
11312   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11313     unsigned Diag = diag::warn_objc_pointer_masking;
11314     // Determine if we are introspecting the result of performSelectorXXX.
11315     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11316     // Special case messages to -performSelector and friends, which
11317     // can return non-pointer values boxed in a pointer value.
11318     // Some clients may wish to silence warnings in this subcase.
11319     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11320       Selector S = ME->getSelector();
11321       StringRef SelArg0 = S.getNameForSlot(0);
11322       if (SelArg0.startswith("performSelector"))
11323         Diag = diag::warn_objc_pointer_masking_performSelector;
11324     }
11325     
11326     S.Diag(OpLoc, Diag)
11327       << ObjCPointerExpr->getSourceRange();
11328   }
11329 }
11330
11331 static NamedDecl *getDeclFromExpr(Expr *E) {
11332   if (!E)
11333     return nullptr;
11334   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11335     return DRE->getDecl();
11336   if (auto *ME = dyn_cast<MemberExpr>(E))
11337     return ME->getMemberDecl();
11338   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11339     return IRE->getDecl();
11340   return nullptr;
11341 }
11342
11343 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11344 /// operator @p Opc at location @c TokLoc. This routine only supports
11345 /// built-in operations; ActOnBinOp handles overloaded operators.
11346 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11347                                     BinaryOperatorKind Opc,
11348                                     Expr *LHSExpr, Expr *RHSExpr) {
11349   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11350     // The syntax only allows initializer lists on the RHS of assignment,
11351     // so we don't need to worry about accepting invalid code for
11352     // non-assignment operators.
11353     // C++11 5.17p9:
11354     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11355     //   of x = {} is x = T().
11356     InitializationKind Kind =
11357         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11358     InitializedEntity Entity =
11359         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11360     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11361     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11362     if (Init.isInvalid())
11363       return Init;
11364     RHSExpr = Init.get();
11365   }
11366
11367   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11368   QualType ResultTy;     // Result type of the binary operator.
11369   // The following two variables are used for compound assignment operators
11370   QualType CompLHSTy;    // Type of LHS after promotions for computation
11371   QualType CompResultTy; // Type of computation result
11372   ExprValueKind VK = VK_RValue;
11373   ExprObjectKind OK = OK_Ordinary;
11374
11375   if (!getLangOpts().CPlusPlus) {
11376     // C cannot handle TypoExpr nodes on either side of a binop because it
11377     // doesn't handle dependent types properly, so make sure any TypoExprs have
11378     // been dealt with before checking the operands.
11379     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11380     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11381       if (Opc != BO_Assign)
11382         return ExprResult(E);
11383       // Avoid correcting the RHS to the same Expr as the LHS.
11384       Decl *D = getDeclFromExpr(E);
11385       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11386     });
11387     if (!LHS.isUsable() || !RHS.isUsable())
11388       return ExprError();
11389   }
11390
11391   if (getLangOpts().OpenCL) {
11392     QualType LHSTy = LHSExpr->getType();
11393     QualType RHSTy = RHSExpr->getType();
11394     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11395     // the ATOMIC_VAR_INIT macro.
11396     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11397       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11398       if (BO_Assign == Opc)
11399         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11400       else
11401         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11402       return ExprError();
11403     }
11404
11405     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11406     // only with a builtin functions and therefore should be disallowed here.
11407     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11408         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11409         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11410         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11411       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11412       return ExprError();
11413     }
11414   }
11415
11416   switch (Opc) {
11417   case BO_Assign:
11418     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11419     if (getLangOpts().CPlusPlus &&
11420         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11421       VK = LHS.get()->getValueKind();
11422       OK = LHS.get()->getObjectKind();
11423     }
11424     if (!ResultTy.isNull()) {
11425       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11426       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11427     }
11428     RecordModifiableNonNullParam(*this, LHS.get());
11429     break;
11430   case BO_PtrMemD:
11431   case BO_PtrMemI:
11432     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11433                                             Opc == BO_PtrMemI);
11434     break;
11435   case BO_Mul:
11436   case BO_Div:
11437     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11438                                            Opc == BO_Div);
11439     break;
11440   case BO_Rem:
11441     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11442     break;
11443   case BO_Add:
11444     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11445     break;
11446   case BO_Sub:
11447     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11448     break;
11449   case BO_Shl:
11450   case BO_Shr:
11451     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11452     break;
11453   case BO_LE:
11454   case BO_LT:
11455   case BO_GE:
11456   case BO_GT:
11457     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11458     break;
11459   case BO_EQ:
11460   case BO_NE:
11461     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11462     break;
11463   case BO_And:
11464     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11465     LLVM_FALLTHROUGH;
11466   case BO_Xor:
11467   case BO_Or:
11468     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11469     break;
11470   case BO_LAnd:
11471   case BO_LOr:
11472     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11473     break;
11474   case BO_MulAssign:
11475   case BO_DivAssign:
11476     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11477                                                Opc == BO_DivAssign);
11478     CompLHSTy = CompResultTy;
11479     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11480       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11481     break;
11482   case BO_RemAssign:
11483     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11484     CompLHSTy = CompResultTy;
11485     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11486       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11487     break;
11488   case BO_AddAssign:
11489     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11490     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11491       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11492     break;
11493   case BO_SubAssign:
11494     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11495     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11496       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11497     break;
11498   case BO_ShlAssign:
11499   case BO_ShrAssign:
11500     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11501     CompLHSTy = CompResultTy;
11502     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11503       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11504     break;
11505   case BO_AndAssign:
11506   case BO_OrAssign: // fallthrough
11507     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11508     LLVM_FALLTHROUGH;
11509   case BO_XorAssign:
11510     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11511     CompLHSTy = CompResultTy;
11512     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11513       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11514     break;
11515   case BO_Comma:
11516     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11517     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11518       VK = RHS.get()->getValueKind();
11519       OK = RHS.get()->getObjectKind();
11520     }
11521     break;
11522   }
11523   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11524     return ExprError();
11525
11526   // Check for array bounds violations for both sides of the BinaryOperator
11527   CheckArrayAccess(LHS.get());
11528   CheckArrayAccess(RHS.get());
11529
11530   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11531     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11532                                                  &Context.Idents.get("object_setClass"),
11533                                                  SourceLocation(), LookupOrdinaryName);
11534     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11535       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11536       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11537       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11538       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11539       FixItHint::CreateInsertion(RHSLocEnd, ")");
11540     }
11541     else
11542       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11543   }
11544   else if (const ObjCIvarRefExpr *OIRE =
11545            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11546     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11547   
11548   if (CompResultTy.isNull())
11549     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11550                                         OK, OpLoc, FPFeatures);
11551   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11552       OK_ObjCProperty) {
11553     VK = VK_LValue;
11554     OK = LHS.get()->getObjectKind();
11555   }
11556   return new (Context) CompoundAssignOperator(
11557       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11558       OpLoc, FPFeatures);
11559 }
11560
11561 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11562 /// operators are mixed in a way that suggests that the programmer forgot that
11563 /// comparison operators have higher precedence. The most typical example of
11564 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11565 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11566                                       SourceLocation OpLoc, Expr *LHSExpr,
11567                                       Expr *RHSExpr) {
11568   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11569   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11570
11571   // Check that one of the sides is a comparison operator and the other isn't.
11572   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11573   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11574   if (isLeftComp == isRightComp)
11575     return;
11576
11577   // Bitwise operations are sometimes used as eager logical ops.
11578   // Don't diagnose this.
11579   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11580   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11581   if (isLeftBitwise || isRightBitwise)
11582     return;
11583
11584   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11585                                                    OpLoc)
11586                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11587   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11588   SourceRange ParensRange = isLeftComp ?
11589       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11590     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11591
11592   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11593     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11594   SuggestParentheses(Self, OpLoc,
11595     Self.PDiag(diag::note_precedence_silence) << OpStr,
11596     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11597   SuggestParentheses(Self, OpLoc,
11598     Self.PDiag(diag::note_precedence_bitwise_first)
11599       << BinaryOperator::getOpcodeStr(Opc),
11600     ParensRange);
11601 }
11602
11603 /// \brief It accepts a '&&' expr that is inside a '||' one.
11604 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11605 /// in parentheses.
11606 static void
11607 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11608                                        BinaryOperator *Bop) {
11609   assert(Bop->getOpcode() == BO_LAnd);
11610   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11611       << Bop->getSourceRange() << OpLoc;
11612   SuggestParentheses(Self, Bop->getOperatorLoc(),
11613     Self.PDiag(diag::note_precedence_silence)
11614       << Bop->getOpcodeStr(),
11615     Bop->getSourceRange());
11616 }
11617
11618 /// \brief Returns true if the given expression can be evaluated as a constant
11619 /// 'true'.
11620 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11621   bool Res;
11622   return !E->isValueDependent() &&
11623          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11624 }
11625
11626 /// \brief Returns true if the given expression can be evaluated as a constant
11627 /// 'false'.
11628 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11629   bool Res;
11630   return !E->isValueDependent() &&
11631          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11632 }
11633
11634 /// \brief Look for '&&' in the left hand of a '||' expr.
11635 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11636                                              Expr *LHSExpr, Expr *RHSExpr) {
11637   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11638     if (Bop->getOpcode() == BO_LAnd) {
11639       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11640       if (EvaluatesAsFalse(S, RHSExpr))
11641         return;
11642       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11643       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11644         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11645     } else if (Bop->getOpcode() == BO_LOr) {
11646       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11647         // If it's "a || b && 1 || c" we didn't warn earlier for
11648         // "a || b && 1", but warn now.
11649         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11650           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11651       }
11652     }
11653   }
11654 }
11655
11656 /// \brief Look for '&&' in the right hand of a '||' expr.
11657 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11658                                              Expr *LHSExpr, Expr *RHSExpr) {
11659   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11660     if (Bop->getOpcode() == BO_LAnd) {
11661       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11662       if (EvaluatesAsFalse(S, LHSExpr))
11663         return;
11664       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11665       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11666         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11667     }
11668   }
11669 }
11670
11671 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11672 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11673 /// the '&' expression in parentheses.
11674 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11675                                          SourceLocation OpLoc, Expr *SubExpr) {
11676   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11677     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11678       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11679         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11680         << Bop->getSourceRange() << OpLoc;
11681       SuggestParentheses(S, Bop->getOperatorLoc(),
11682         S.PDiag(diag::note_precedence_silence)
11683           << Bop->getOpcodeStr(),
11684         Bop->getSourceRange());
11685     }
11686   }
11687 }
11688
11689 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11690                                     Expr *SubExpr, StringRef Shift) {
11691   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11692     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11693       StringRef Op = Bop->getOpcodeStr();
11694       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11695           << Bop->getSourceRange() << OpLoc << Shift << Op;
11696       SuggestParentheses(S, Bop->getOperatorLoc(),
11697           S.PDiag(diag::note_precedence_silence) << Op,
11698           Bop->getSourceRange());
11699     }
11700   }
11701 }
11702
11703 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11704                                  Expr *LHSExpr, Expr *RHSExpr) {
11705   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11706   if (!OCE)
11707     return;
11708
11709   FunctionDecl *FD = OCE->getDirectCallee();
11710   if (!FD || !FD->isOverloadedOperator())
11711     return;
11712
11713   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11714   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11715     return;
11716
11717   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11718       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11719       << (Kind == OO_LessLess);
11720   SuggestParentheses(S, OCE->getOperatorLoc(),
11721                      S.PDiag(diag::note_precedence_silence)
11722                          << (Kind == OO_LessLess ? "<<" : ">>"),
11723                      OCE->getSourceRange());
11724   SuggestParentheses(S, OpLoc,
11725                      S.PDiag(diag::note_evaluate_comparison_first),
11726                      SourceRange(OCE->getArg(1)->getLocStart(),
11727                                  RHSExpr->getLocEnd()));
11728 }
11729
11730 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11731 /// precedence.
11732 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11733                                     SourceLocation OpLoc, Expr *LHSExpr,
11734                                     Expr *RHSExpr){
11735   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11736   if (BinaryOperator::isBitwiseOp(Opc))
11737     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11738
11739   // Diagnose "arg1 & arg2 | arg3"
11740   if ((Opc == BO_Or || Opc == BO_Xor) &&
11741       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11742     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11743     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11744   }
11745
11746   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11747   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11748   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11749     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11750     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11751   }
11752
11753   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11754       || Opc == BO_Shr) {
11755     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11756     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11757     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11758   }
11759
11760   // Warn on overloaded shift operators and comparisons, such as:
11761   // cout << 5 == 4;
11762   if (BinaryOperator::isComparisonOp(Opc))
11763     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11764 }
11765
11766 // Binary Operators.  'Tok' is the token for the operator.
11767 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11768                             tok::TokenKind Kind,
11769                             Expr *LHSExpr, Expr *RHSExpr) {
11770   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11771   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11772   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11773
11774   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11775   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11776
11777   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11778 }
11779
11780 /// Build an overloaded binary operator expression in the given scope.
11781 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11782                                        BinaryOperatorKind Opc,
11783                                        Expr *LHS, Expr *RHS) {
11784   // Find all of the overloaded operators visible from this
11785   // point. We perform both an operator-name lookup from the local
11786   // scope and an argument-dependent lookup based on the types of
11787   // the arguments.
11788   UnresolvedSet<16> Functions;
11789   OverloadedOperatorKind OverOp
11790     = BinaryOperator::getOverloadedOperator(Opc);
11791   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11792     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11793                                    RHS->getType(), Functions);
11794
11795   // Build the (potentially-overloaded, potentially-dependent)
11796   // binary operation.
11797   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11798 }
11799
11800 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11801                             BinaryOperatorKind Opc,
11802                             Expr *LHSExpr, Expr *RHSExpr) {
11803   // We want to end up calling one of checkPseudoObjectAssignment
11804   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11805   // both expressions are overloadable or either is type-dependent),
11806   // or CreateBuiltinBinOp (in any other case).  We also want to get
11807   // any placeholder types out of the way.
11808
11809   // Handle pseudo-objects in the LHS.
11810   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11811     // Assignments with a pseudo-object l-value need special analysis.
11812     if (pty->getKind() == BuiltinType::PseudoObject &&
11813         BinaryOperator::isAssignmentOp(Opc))
11814       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11815
11816     // Don't resolve overloads if the other type is overloadable.
11817     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11818       // We can't actually test that if we still have a placeholder,
11819       // though.  Fortunately, none of the exceptions we see in that
11820       // code below are valid when the LHS is an overload set.  Note
11821       // that an overload set can be dependently-typed, but it never
11822       // instantiates to having an overloadable type.
11823       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11824       if (resolvedRHS.isInvalid()) return ExprError();
11825       RHSExpr = resolvedRHS.get();
11826
11827       if (RHSExpr->isTypeDependent() ||
11828           RHSExpr->getType()->isOverloadableType())
11829         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11830     }
11831         
11832     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11833     if (LHS.isInvalid()) return ExprError();
11834     LHSExpr = LHS.get();
11835   }
11836
11837   // Handle pseudo-objects in the RHS.
11838   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11839     // An overload in the RHS can potentially be resolved by the type
11840     // being assigned to.
11841     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11842       if (getLangOpts().CPlusPlus &&
11843           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11844            LHSExpr->getType()->isOverloadableType()))
11845         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11846
11847       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11848     }
11849
11850     // Don't resolve overloads if the other type is overloadable.
11851     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11852         LHSExpr->getType()->isOverloadableType())
11853       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11854
11855     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11856     if (!resolvedRHS.isUsable()) return ExprError();
11857     RHSExpr = resolvedRHS.get();
11858   }
11859
11860   if (getLangOpts().CPlusPlus) {
11861     // If either expression is type-dependent, always build an
11862     // overloaded op.
11863     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11864       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11865
11866     // Otherwise, build an overloaded op if either expression has an
11867     // overloadable type.
11868     if (LHSExpr->getType()->isOverloadableType() ||
11869         RHSExpr->getType()->isOverloadableType())
11870       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11871   }
11872
11873   // Build a built-in binary operation.
11874   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11875 }
11876
11877 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11878                                       UnaryOperatorKind Opc,
11879                                       Expr *InputExpr) {
11880   ExprResult Input = InputExpr;
11881   ExprValueKind VK = VK_RValue;
11882   ExprObjectKind OK = OK_Ordinary;
11883   QualType resultType;
11884   if (getLangOpts().OpenCL) {
11885     QualType Ty = InputExpr->getType();
11886     // The only legal unary operation for atomics is '&'.
11887     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11888     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11889     // only with a builtin functions and therefore should be disallowed here.
11890         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11891         || Ty->isBlockPointerType())) {
11892       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11893                        << InputExpr->getType()
11894                        << Input.get()->getSourceRange());
11895     }
11896   }
11897   switch (Opc) {
11898   case UO_PreInc:
11899   case UO_PreDec:
11900   case UO_PostInc:
11901   case UO_PostDec:
11902     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11903                                                 OpLoc,
11904                                                 Opc == UO_PreInc ||
11905                                                 Opc == UO_PostInc,
11906                                                 Opc == UO_PreInc ||
11907                                                 Opc == UO_PreDec);
11908     break;
11909   case UO_AddrOf:
11910     resultType = CheckAddressOfOperand(Input, OpLoc);
11911     RecordModifiableNonNullParam(*this, InputExpr);
11912     break;
11913   case UO_Deref: {
11914     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11915     if (Input.isInvalid()) return ExprError();
11916     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11917     break;
11918   }
11919   case UO_Plus:
11920   case UO_Minus:
11921     Input = UsualUnaryConversions(Input.get());
11922     if (Input.isInvalid()) return ExprError();
11923     resultType = Input.get()->getType();
11924     if (resultType->isDependentType())
11925       break;
11926     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11927       break;
11928     else if (resultType->isVectorType() &&
11929              // The z vector extensions don't allow + or - with bool vectors.
11930              (!Context.getLangOpts().ZVector ||
11931               resultType->getAs<VectorType>()->getVectorKind() !=
11932               VectorType::AltiVecBool))
11933       break;
11934     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11935              Opc == UO_Plus &&
11936              resultType->isPointerType())
11937       break;
11938
11939     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11940       << resultType << Input.get()->getSourceRange());
11941
11942   case UO_Not: // bitwise complement
11943     Input = UsualUnaryConversions(Input.get());
11944     if (Input.isInvalid())
11945       return ExprError();
11946     resultType = Input.get()->getType();
11947     if (resultType->isDependentType())
11948       break;
11949     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11950     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11951       // C99 does not support '~' for complex conjugation.
11952       Diag(OpLoc, diag::ext_integer_complement_complex)
11953           << resultType << Input.get()->getSourceRange();
11954     else if (resultType->hasIntegerRepresentation())
11955       break;
11956     else if (resultType->isExtVectorType()) {
11957       if (Context.getLangOpts().OpenCL) {
11958         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11959         // on vector float types.
11960         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11961         if (!T->isIntegerType())
11962           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11963                            << resultType << Input.get()->getSourceRange());
11964       }
11965       break;
11966     } else {
11967       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11968                        << resultType << Input.get()->getSourceRange());
11969     }
11970     break;
11971
11972   case UO_LNot: // logical negation
11973     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11974     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11975     if (Input.isInvalid()) return ExprError();
11976     resultType = Input.get()->getType();
11977
11978     // Though we still have to promote half FP to float...
11979     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11980       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11981       resultType = Context.FloatTy;
11982     }
11983
11984     if (resultType->isDependentType())
11985       break;
11986     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11987       // C99 6.5.3.3p1: ok, fallthrough;
11988       if (Context.getLangOpts().CPlusPlus) {
11989         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11990         // operand contextually converted to bool.
11991         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11992                                   ScalarTypeToBooleanCastKind(resultType));
11993       } else if (Context.getLangOpts().OpenCL &&
11994                  Context.getLangOpts().OpenCLVersion < 120) {
11995         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11996         // operate on scalar float types.
11997         if (!resultType->isIntegerType() && !resultType->isPointerType())
11998           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11999                            << resultType << Input.get()->getSourceRange());
12000       }
12001     } else if (resultType->isExtVectorType()) {
12002       if (Context.getLangOpts().OpenCL &&
12003           Context.getLangOpts().OpenCLVersion < 120) {
12004         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12005         // operate on vector float types.
12006         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12007         if (!T->isIntegerType())
12008           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12009                            << resultType << Input.get()->getSourceRange());
12010       }
12011       // Vector logical not returns the signed variant of the operand type.
12012       resultType = GetSignedVectorType(resultType);
12013       break;
12014     } else {
12015       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12016       //        type in C++. We should allow that here too.
12017       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12018         << resultType << Input.get()->getSourceRange());
12019     }
12020     
12021     // LNot always has type int. C99 6.5.3.3p5.
12022     // In C++, it's bool. C++ 5.3.1p8
12023     resultType = Context.getLogicalOperationType();
12024     break;
12025   case UO_Real:
12026   case UO_Imag:
12027     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12028     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12029     // complex l-values to ordinary l-values and all other values to r-values.
12030     if (Input.isInvalid()) return ExprError();
12031     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12032       if (Input.get()->getValueKind() != VK_RValue &&
12033           Input.get()->getObjectKind() == OK_Ordinary)
12034         VK = Input.get()->getValueKind();
12035     } else if (!getLangOpts().CPlusPlus) {
12036       // In C, a volatile scalar is read by __imag. In C++, it is not.
12037       Input = DefaultLvalueConversion(Input.get());
12038     }
12039     break;
12040   case UO_Extension:
12041   case UO_Coawait:
12042     resultType = Input.get()->getType();
12043     VK = Input.get()->getValueKind();
12044     OK = Input.get()->getObjectKind();
12045     break;
12046   }
12047   if (resultType.isNull() || Input.isInvalid())
12048     return ExprError();
12049
12050   // Check for array bounds violations in the operand of the UnaryOperator,
12051   // except for the '*' and '&' operators that have to be handled specially
12052   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12053   // that are explicitly defined as valid by the standard).
12054   if (Opc != UO_AddrOf && Opc != UO_Deref)
12055     CheckArrayAccess(Input.get());
12056
12057   return new (Context)
12058       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
12059 }
12060
12061 /// \brief Determine whether the given expression is a qualified member
12062 /// access expression, of a form that could be turned into a pointer to member
12063 /// with the address-of operator.
12064 static bool isQualifiedMemberAccess(Expr *E) {
12065   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12066     if (!DRE->getQualifier())
12067       return false;
12068     
12069     ValueDecl *VD = DRE->getDecl();
12070     if (!VD->isCXXClassMember())
12071       return false;
12072     
12073     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12074       return true;
12075     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12076       return Method->isInstance();
12077       
12078     return false;
12079   }
12080   
12081   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12082     if (!ULE->getQualifier())
12083       return false;
12084     
12085     for (NamedDecl *D : ULE->decls()) {
12086       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12087         if (Method->isInstance())
12088           return true;
12089       } else {
12090         // Overload set does not contain methods.
12091         break;
12092       }
12093     }
12094     
12095     return false;
12096   }
12097   
12098   return false;
12099 }
12100
12101 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12102                               UnaryOperatorKind Opc, Expr *Input) {
12103   // First things first: handle placeholders so that the
12104   // overloaded-operator check considers the right type.
12105   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12106     // Increment and decrement of pseudo-object references.
12107     if (pty->getKind() == BuiltinType::PseudoObject &&
12108         UnaryOperator::isIncrementDecrementOp(Opc))
12109       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12110
12111     // extension is always a builtin operator.
12112     if (Opc == UO_Extension)
12113       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12114
12115     // & gets special logic for several kinds of placeholder.
12116     // The builtin code knows what to do.
12117     if (Opc == UO_AddrOf &&
12118         (pty->getKind() == BuiltinType::Overload ||
12119          pty->getKind() == BuiltinType::UnknownAny ||
12120          pty->getKind() == BuiltinType::BoundMember))
12121       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12122
12123     // Anything else needs to be handled now.
12124     ExprResult Result = CheckPlaceholderExpr(Input);
12125     if (Result.isInvalid()) return ExprError();
12126     Input = Result.get();
12127   }
12128
12129   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12130       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12131       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12132     // Find all of the overloaded operators visible from this
12133     // point. We perform both an operator-name lookup from the local
12134     // scope and an argument-dependent lookup based on the types of
12135     // the arguments.
12136     UnresolvedSet<16> Functions;
12137     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12138     if (S && OverOp != OO_None)
12139       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12140                                    Functions);
12141
12142     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12143   }
12144
12145   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12146 }
12147
12148 // Unary Operators.  'Tok' is the token for the operator.
12149 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12150                               tok::TokenKind Op, Expr *Input) {
12151   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12152 }
12153
12154 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12155 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12156                                 LabelDecl *TheDecl) {
12157   TheDecl->markUsed(Context);
12158   // Create the AST node.  The address of a label always has type 'void*'.
12159   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12160                                      Context.getPointerType(Context.VoidTy));
12161 }
12162
12163 /// Given the last statement in a statement-expression, check whether
12164 /// the result is a producing expression (like a call to an
12165 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12166 /// release out of the full-expression.  Otherwise, return null.
12167 /// Cannot fail.
12168 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12169   // Should always be wrapped with one of these.
12170   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12171   if (!cleanups) return nullptr;
12172
12173   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12174   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12175     return nullptr;
12176
12177   // Splice out the cast.  This shouldn't modify any interesting
12178   // features of the statement.
12179   Expr *producer = cast->getSubExpr();
12180   assert(producer->getType() == cast->getType());
12181   assert(producer->getValueKind() == cast->getValueKind());
12182   cleanups->setSubExpr(producer);
12183   return cleanups;
12184 }
12185
12186 void Sema::ActOnStartStmtExpr() {
12187   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12188 }
12189
12190 void Sema::ActOnStmtExprError() {
12191   // Note that function is also called by TreeTransform when leaving a
12192   // StmtExpr scope without rebuilding anything.
12193
12194   DiscardCleanupsInEvaluationContext();
12195   PopExpressionEvaluationContext();
12196 }
12197
12198 ExprResult
12199 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12200                     SourceLocation RPLoc) { // "({..})"
12201   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12202   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12203
12204   if (hasAnyUnrecoverableErrorsInThisFunction())
12205     DiscardCleanupsInEvaluationContext();
12206   assert(!Cleanup.exprNeedsCleanups() &&
12207          "cleanups within StmtExpr not correctly bound!");
12208   PopExpressionEvaluationContext();
12209
12210   // FIXME: there are a variety of strange constraints to enforce here, for
12211   // example, it is not possible to goto into a stmt expression apparently.
12212   // More semantic analysis is needed.
12213
12214   // If there are sub-stmts in the compound stmt, take the type of the last one
12215   // as the type of the stmtexpr.
12216   QualType Ty = Context.VoidTy;
12217   bool StmtExprMayBindToTemp = false;
12218   if (!Compound->body_empty()) {
12219     Stmt *LastStmt = Compound->body_back();
12220     LabelStmt *LastLabelStmt = nullptr;
12221     // If LastStmt is a label, skip down through into the body.
12222     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12223       LastLabelStmt = Label;
12224       LastStmt = Label->getSubStmt();
12225     }
12226
12227     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12228       // Do function/array conversion on the last expression, but not
12229       // lvalue-to-rvalue.  However, initialize an unqualified type.
12230       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12231       if (LastExpr.isInvalid())
12232         return ExprError();
12233       Ty = LastExpr.get()->getType().getUnqualifiedType();
12234
12235       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12236         // In ARC, if the final expression ends in a consume, splice
12237         // the consume out and bind it later.  In the alternate case
12238         // (when dealing with a retainable type), the result
12239         // initialization will create a produce.  In both cases the
12240         // result will be +1, and we'll need to balance that out with
12241         // a bind.
12242         if (Expr *rebuiltLastStmt
12243               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12244           LastExpr = rebuiltLastStmt;
12245         } else {
12246           LastExpr = PerformCopyInitialization(
12247                             InitializedEntity::InitializeResult(LPLoc, 
12248                                                                 Ty,
12249                                                                 false),
12250                                                    SourceLocation(),
12251                                                LastExpr);
12252         }
12253
12254         if (LastExpr.isInvalid())
12255           return ExprError();
12256         if (LastExpr.get() != nullptr) {
12257           if (!LastLabelStmt)
12258             Compound->setLastStmt(LastExpr.get());
12259           else
12260             LastLabelStmt->setSubStmt(LastExpr.get());
12261           StmtExprMayBindToTemp = true;
12262         }
12263       }
12264     }
12265   }
12266
12267   // FIXME: Check that expression type is complete/non-abstract; statement
12268   // expressions are not lvalues.
12269   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12270   if (StmtExprMayBindToTemp)
12271     return MaybeBindToTemporary(ResStmtExpr);
12272   return ResStmtExpr;
12273 }
12274
12275 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12276                                       TypeSourceInfo *TInfo,
12277                                       ArrayRef<OffsetOfComponent> Components,
12278                                       SourceLocation RParenLoc) {
12279   QualType ArgTy = TInfo->getType();
12280   bool Dependent = ArgTy->isDependentType();
12281   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12282   
12283   // We must have at least one component that refers to the type, and the first
12284   // one is known to be a field designator.  Verify that the ArgTy represents
12285   // a struct/union/class.
12286   if (!Dependent && !ArgTy->isRecordType())
12287     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
12288                        << ArgTy << TypeRange);
12289   
12290   // Type must be complete per C99 7.17p3 because a declaring a variable
12291   // with an incomplete type would be ill-formed.
12292   if (!Dependent 
12293       && RequireCompleteType(BuiltinLoc, ArgTy,
12294                              diag::err_offsetof_incomplete_type, TypeRange))
12295     return ExprError();
12296   
12297   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12298   // GCC extension, diagnose them.
12299   // FIXME: This diagnostic isn't actually visible because the location is in
12300   // a system header!
12301   if (Components.size() != 1)
12302     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12303       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12304   
12305   bool DidWarnAboutNonPOD = false;
12306   QualType CurrentType = ArgTy;
12307   SmallVector<OffsetOfNode, 4> Comps;
12308   SmallVector<Expr*, 4> Exprs;
12309   for (const OffsetOfComponent &OC : Components) {
12310     if (OC.isBrackets) {
12311       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12312       if (!CurrentType->isDependentType()) {
12313         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12314         if(!AT)
12315           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12316                            << CurrentType);
12317         CurrentType = AT->getElementType();
12318       } else
12319         CurrentType = Context.DependentTy;
12320       
12321       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12322       if (IdxRval.isInvalid())
12323         return ExprError();
12324       Expr *Idx = IdxRval.get();
12325
12326       // The expression must be an integral expression.
12327       // FIXME: An integral constant expression?
12328       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12329           !Idx->getType()->isIntegerType())
12330         return ExprError(Diag(Idx->getLocStart(),
12331                               diag::err_typecheck_subscript_not_integer)
12332                          << Idx->getSourceRange());
12333
12334       // Record this array index.
12335       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12336       Exprs.push_back(Idx);
12337       continue;
12338     }
12339     
12340     // Offset of a field.
12341     if (CurrentType->isDependentType()) {
12342       // We have the offset of a field, but we can't look into the dependent
12343       // type. Just record the identifier of the field.
12344       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12345       CurrentType = Context.DependentTy;
12346       continue;
12347     }
12348     
12349     // We need to have a complete type to look into.
12350     if (RequireCompleteType(OC.LocStart, CurrentType,
12351                             diag::err_offsetof_incomplete_type))
12352       return ExprError();
12353     
12354     // Look for the designated field.
12355     const RecordType *RC = CurrentType->getAs<RecordType>();
12356     if (!RC) 
12357       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12358                        << CurrentType);
12359     RecordDecl *RD = RC->getDecl();
12360     
12361     // C++ [lib.support.types]p5:
12362     //   The macro offsetof accepts a restricted set of type arguments in this
12363     //   International Standard. type shall be a POD structure or a POD union
12364     //   (clause 9).
12365     // C++11 [support.types]p4:
12366     //   If type is not a standard-layout class (Clause 9), the results are
12367     //   undefined.
12368     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12369       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12370       unsigned DiagID =
12371         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12372                             : diag::ext_offsetof_non_pod_type;
12373
12374       if (!IsSafe && !DidWarnAboutNonPOD &&
12375           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12376                               PDiag(DiagID)
12377                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12378                               << CurrentType))
12379         DidWarnAboutNonPOD = true;
12380     }
12381     
12382     // Look for the field.
12383     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12384     LookupQualifiedName(R, RD);
12385     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12386     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12387     if (!MemberDecl) {
12388       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12389         MemberDecl = IndirectMemberDecl->getAnonField();
12390     }
12391
12392     if (!MemberDecl)
12393       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12394                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
12395                                                               OC.LocEnd));
12396     
12397     // C99 7.17p3:
12398     //   (If the specified member is a bit-field, the behavior is undefined.)
12399     //
12400     // We diagnose this as an error.
12401     if (MemberDecl->isBitField()) {
12402       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12403         << MemberDecl->getDeclName()
12404         << SourceRange(BuiltinLoc, RParenLoc);
12405       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12406       return ExprError();
12407     }
12408
12409     RecordDecl *Parent = MemberDecl->getParent();
12410     if (IndirectMemberDecl)
12411       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12412
12413     // If the member was found in a base class, introduce OffsetOfNodes for
12414     // the base class indirections.
12415     CXXBasePaths Paths;
12416     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12417                       Paths)) {
12418       if (Paths.getDetectedVirtual()) {
12419         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12420           << MemberDecl->getDeclName()
12421           << SourceRange(BuiltinLoc, RParenLoc);
12422         return ExprError();
12423       }
12424
12425       CXXBasePath &Path = Paths.front();
12426       for (const CXXBasePathElement &B : Path)
12427         Comps.push_back(OffsetOfNode(B.Base));
12428     }
12429
12430     if (IndirectMemberDecl) {
12431       for (auto *FI : IndirectMemberDecl->chain()) {
12432         assert(isa<FieldDecl>(FI));
12433         Comps.push_back(OffsetOfNode(OC.LocStart,
12434                                      cast<FieldDecl>(FI), OC.LocEnd));
12435       }
12436     } else
12437       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12438
12439     CurrentType = MemberDecl->getType().getNonReferenceType(); 
12440   }
12441   
12442   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12443                               Comps, Exprs, RParenLoc);
12444 }
12445
12446 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12447                                       SourceLocation BuiltinLoc,
12448                                       SourceLocation TypeLoc,
12449                                       ParsedType ParsedArgTy,
12450                                       ArrayRef<OffsetOfComponent> Components,
12451                                       SourceLocation RParenLoc) {
12452   
12453   TypeSourceInfo *ArgTInfo;
12454   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12455   if (ArgTy.isNull())
12456     return ExprError();
12457
12458   if (!ArgTInfo)
12459     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12460
12461   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12462 }
12463
12464
12465 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12466                                  Expr *CondExpr,
12467                                  Expr *LHSExpr, Expr *RHSExpr,
12468                                  SourceLocation RPLoc) {
12469   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12470
12471   ExprValueKind VK = VK_RValue;
12472   ExprObjectKind OK = OK_Ordinary;
12473   QualType resType;
12474   bool ValueDependent = false;
12475   bool CondIsTrue = false;
12476   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12477     resType = Context.DependentTy;
12478     ValueDependent = true;
12479   } else {
12480     // The conditional expression is required to be a constant expression.
12481     llvm::APSInt condEval(32);
12482     ExprResult CondICE
12483       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12484           diag::err_typecheck_choose_expr_requires_constant, false);
12485     if (CondICE.isInvalid())
12486       return ExprError();
12487     CondExpr = CondICE.get();
12488     CondIsTrue = condEval.getZExtValue();
12489
12490     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12491     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12492
12493     resType = ActiveExpr->getType();
12494     ValueDependent = ActiveExpr->isValueDependent();
12495     VK = ActiveExpr->getValueKind();
12496     OK = ActiveExpr->getObjectKind();
12497   }
12498
12499   return new (Context)
12500       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12501                  CondIsTrue, resType->isDependentType(), ValueDependent);
12502 }
12503
12504 //===----------------------------------------------------------------------===//
12505 // Clang Extensions.
12506 //===----------------------------------------------------------------------===//
12507
12508 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12509 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12510   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12511
12512   if (LangOpts.CPlusPlus) {
12513     Decl *ManglingContextDecl;
12514     if (MangleNumberingContext *MCtx =
12515             getCurrentMangleNumberContext(Block->getDeclContext(),
12516                                           ManglingContextDecl)) {
12517       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12518       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12519     }
12520   }
12521
12522   PushBlockScope(CurScope, Block);
12523   CurContext->addDecl(Block);
12524   if (CurScope)
12525     PushDeclContext(CurScope, Block);
12526   else
12527     CurContext = Block;
12528
12529   getCurBlock()->HasImplicitReturnType = true;
12530
12531   // Enter a new evaluation context to insulate the block from any
12532   // cleanups from the enclosing full-expression.
12533   PushExpressionEvaluationContext(
12534       ExpressionEvaluationContext::PotentiallyEvaluated);
12535 }
12536
12537 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12538                                Scope *CurScope) {
12539   assert(ParamInfo.getIdentifier() == nullptr &&
12540          "block-id should have no identifier!");
12541   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12542   BlockScopeInfo *CurBlock = getCurBlock();
12543
12544   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12545   QualType T = Sig->getType();
12546
12547   // FIXME: We should allow unexpanded parameter packs here, but that would,
12548   // in turn, make the block expression contain unexpanded parameter packs.
12549   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12550     // Drop the parameters.
12551     FunctionProtoType::ExtProtoInfo EPI;
12552     EPI.HasTrailingReturn = false;
12553     EPI.TypeQuals |= DeclSpec::TQ_const;
12554     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12555     Sig = Context.getTrivialTypeSourceInfo(T);
12556   }
12557   
12558   // GetTypeForDeclarator always produces a function type for a block
12559   // literal signature.  Furthermore, it is always a FunctionProtoType
12560   // unless the function was written with a typedef.
12561   assert(T->isFunctionType() &&
12562          "GetTypeForDeclarator made a non-function block signature");
12563
12564   // Look for an explicit signature in that function type.
12565   FunctionProtoTypeLoc ExplicitSignature;
12566
12567   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12568   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12569
12570     // Check whether that explicit signature was synthesized by
12571     // GetTypeForDeclarator.  If so, don't save that as part of the
12572     // written signature.
12573     if (ExplicitSignature.getLocalRangeBegin() ==
12574         ExplicitSignature.getLocalRangeEnd()) {
12575       // This would be much cheaper if we stored TypeLocs instead of
12576       // TypeSourceInfos.
12577       TypeLoc Result = ExplicitSignature.getReturnLoc();
12578       unsigned Size = Result.getFullDataSize();
12579       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12580       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12581
12582       ExplicitSignature = FunctionProtoTypeLoc();
12583     }
12584   }
12585
12586   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12587   CurBlock->FunctionType = T;
12588
12589   const FunctionType *Fn = T->getAs<FunctionType>();
12590   QualType RetTy = Fn->getReturnType();
12591   bool isVariadic =
12592     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12593
12594   CurBlock->TheDecl->setIsVariadic(isVariadic);
12595
12596   // Context.DependentTy is used as a placeholder for a missing block
12597   // return type.  TODO:  what should we do with declarators like:
12598   //   ^ * { ... }
12599   // If the answer is "apply template argument deduction"....
12600   if (RetTy != Context.DependentTy) {
12601     CurBlock->ReturnType = RetTy;
12602     CurBlock->TheDecl->setBlockMissingReturnType(false);
12603     CurBlock->HasImplicitReturnType = false;
12604   }
12605
12606   // Push block parameters from the declarator if we had them.
12607   SmallVector<ParmVarDecl*, 8> Params;
12608   if (ExplicitSignature) {
12609     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12610       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12611       if (Param->getIdentifier() == nullptr &&
12612           !Param->isImplicit() &&
12613           !Param->isInvalidDecl() &&
12614           !getLangOpts().CPlusPlus)
12615         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12616       Params.push_back(Param);
12617     }
12618
12619   // Fake up parameter variables if we have a typedef, like
12620   //   ^ fntype { ... }
12621   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12622     for (const auto &I : Fn->param_types()) {
12623       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12624           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12625       Params.push_back(Param);
12626     }
12627   }
12628
12629   // Set the parameters on the block decl.
12630   if (!Params.empty()) {
12631     CurBlock->TheDecl->setParams(Params);
12632     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12633                              /*CheckParameterNames=*/false);
12634   }
12635   
12636   // Finally we can process decl attributes.
12637   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12638
12639   // Put the parameter variables in scope.
12640   for (auto AI : CurBlock->TheDecl->parameters()) {
12641     AI->setOwningFunction(CurBlock->TheDecl);
12642
12643     // If this has an identifier, add it to the scope stack.
12644     if (AI->getIdentifier()) {
12645       CheckShadow(CurBlock->TheScope, AI);
12646
12647       PushOnScopeChains(AI, CurBlock->TheScope);
12648     }
12649   }
12650 }
12651
12652 /// ActOnBlockError - If there is an error parsing a block, this callback
12653 /// is invoked to pop the information about the block from the action impl.
12654 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12655   // Leave the expression-evaluation context.
12656   DiscardCleanupsInEvaluationContext();
12657   PopExpressionEvaluationContext();
12658
12659   // Pop off CurBlock, handle nested blocks.
12660   PopDeclContext();
12661   PopFunctionScopeInfo();
12662 }
12663
12664 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12665 /// literal was successfully completed.  ^(int x){...}
12666 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12667                                     Stmt *Body, Scope *CurScope) {
12668   // If blocks are disabled, emit an error.
12669   if (!LangOpts.Blocks)
12670     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12671
12672   // Leave the expression-evaluation context.
12673   if (hasAnyUnrecoverableErrorsInThisFunction())
12674     DiscardCleanupsInEvaluationContext();
12675   assert(!Cleanup.exprNeedsCleanups() &&
12676          "cleanups within block not correctly bound!");
12677   PopExpressionEvaluationContext();
12678
12679   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12680
12681   if (BSI->HasImplicitReturnType)
12682     deduceClosureReturnType(*BSI);
12683
12684   PopDeclContext();
12685
12686   QualType RetTy = Context.VoidTy;
12687   if (!BSI->ReturnType.isNull())
12688     RetTy = BSI->ReturnType;
12689
12690   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12691   QualType BlockTy;
12692
12693   // Set the captured variables on the block.
12694   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12695   SmallVector<BlockDecl::Capture, 4> Captures;
12696   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12697     if (Cap.isThisCapture())
12698       continue;
12699     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12700                               Cap.isNested(), Cap.getInitExpr());
12701     Captures.push_back(NewCap);
12702   }
12703   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12704
12705   // If the user wrote a function type in some form, try to use that.
12706   if (!BSI->FunctionType.isNull()) {
12707     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12708
12709     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12710     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12711     
12712     // Turn protoless block types into nullary block types.
12713     if (isa<FunctionNoProtoType>(FTy)) {
12714       FunctionProtoType::ExtProtoInfo EPI;
12715       EPI.ExtInfo = Ext;
12716       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12717
12718     // Otherwise, if we don't need to change anything about the function type,
12719     // preserve its sugar structure.
12720     } else if (FTy->getReturnType() == RetTy &&
12721                (!NoReturn || FTy->getNoReturnAttr())) {
12722       BlockTy = BSI->FunctionType;
12723
12724     // Otherwise, make the minimal modifications to the function type.
12725     } else {
12726       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12727       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12728       EPI.TypeQuals = 0; // FIXME: silently?
12729       EPI.ExtInfo = Ext;
12730       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12731     }
12732
12733   // If we don't have a function type, just build one from nothing.
12734   } else {
12735     FunctionProtoType::ExtProtoInfo EPI;
12736     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12737     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12738   }
12739
12740   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12741   BlockTy = Context.getBlockPointerType(BlockTy);
12742
12743   // If needed, diagnose invalid gotos and switches in the block.
12744   if (getCurFunction()->NeedsScopeChecking() &&
12745       !PP.isCodeCompletionEnabled())
12746     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12747
12748   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12749
12750   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12751     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12752
12753   // Try to apply the named return value optimization. We have to check again
12754   // if we can do this, though, because blocks keep return statements around
12755   // to deduce an implicit return type.
12756   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12757       !BSI->TheDecl->isDependentContext())
12758     computeNRVO(Body, BSI);
12759   
12760   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12761   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12762   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12763
12764   // If the block isn't obviously global, i.e. it captures anything at
12765   // all, then we need to do a few things in the surrounding context:
12766   if (Result->getBlockDecl()->hasCaptures()) {
12767     // First, this expression has a new cleanup object.
12768     ExprCleanupObjects.push_back(Result->getBlockDecl());
12769     Cleanup.setExprNeedsCleanups(true);
12770
12771     // It also gets a branch-protected scope if any of the captured
12772     // variables needs destruction.
12773     for (const auto &CI : Result->getBlockDecl()->captures()) {
12774       const VarDecl *var = CI.getVariable();
12775       if (var->getType().isDestructedType() != QualType::DK_none) {
12776         getCurFunction()->setHasBranchProtectedScope();
12777         break;
12778       }
12779     }
12780   }
12781
12782   return Result;
12783 }
12784
12785 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12786                             SourceLocation RPLoc) {
12787   TypeSourceInfo *TInfo;
12788   GetTypeFromParser(Ty, &TInfo);
12789   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12790 }
12791
12792 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12793                                 Expr *E, TypeSourceInfo *TInfo,
12794                                 SourceLocation RPLoc) {
12795   Expr *OrigExpr = E;
12796   bool IsMS = false;
12797
12798   // CUDA device code does not support varargs.
12799   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12800     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12801       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12802       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12803         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12804     }
12805   }
12806
12807   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12808   // as Microsoft ABI on an actual Microsoft platform, where
12809   // __builtin_ms_va_list and __builtin_va_list are the same.)
12810   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12811       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12812     QualType MSVaListType = Context.getBuiltinMSVaListType();
12813     if (Context.hasSameType(MSVaListType, E->getType())) {
12814       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12815         return ExprError();
12816       IsMS = true;
12817     }
12818   }
12819
12820   // Get the va_list type
12821   QualType VaListType = Context.getBuiltinVaListType();
12822   if (!IsMS) {
12823     if (VaListType->isArrayType()) {
12824       // Deal with implicit array decay; for example, on x86-64,
12825       // va_list is an array, but it's supposed to decay to
12826       // a pointer for va_arg.
12827       VaListType = Context.getArrayDecayedType(VaListType);
12828       // Make sure the input expression also decays appropriately.
12829       ExprResult Result = UsualUnaryConversions(E);
12830       if (Result.isInvalid())
12831         return ExprError();
12832       E = Result.get();
12833     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12834       // If va_list is a record type and we are compiling in C++ mode,
12835       // check the argument using reference binding.
12836       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12837           Context, Context.getLValueReferenceType(VaListType), false);
12838       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12839       if (Init.isInvalid())
12840         return ExprError();
12841       E = Init.getAs<Expr>();
12842     } else {
12843       // Otherwise, the va_list argument must be an l-value because
12844       // it is modified by va_arg.
12845       if (!E->isTypeDependent() &&
12846           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12847         return ExprError();
12848     }
12849   }
12850
12851   if (!IsMS && !E->isTypeDependent() &&
12852       !Context.hasSameType(VaListType, E->getType()))
12853     return ExprError(Diag(E->getLocStart(),
12854                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12855       << OrigExpr->getType() << E->getSourceRange());
12856
12857   if (!TInfo->getType()->isDependentType()) {
12858     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12859                             diag::err_second_parameter_to_va_arg_incomplete,
12860                             TInfo->getTypeLoc()))
12861       return ExprError();
12862
12863     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12864                                TInfo->getType(),
12865                                diag::err_second_parameter_to_va_arg_abstract,
12866                                TInfo->getTypeLoc()))
12867       return ExprError();
12868
12869     if (!TInfo->getType().isPODType(Context)) {
12870       Diag(TInfo->getTypeLoc().getBeginLoc(),
12871            TInfo->getType()->isObjCLifetimeType()
12872              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12873              : diag::warn_second_parameter_to_va_arg_not_pod)
12874         << TInfo->getType()
12875         << TInfo->getTypeLoc().getSourceRange();
12876     }
12877
12878     // Check for va_arg where arguments of the given type will be promoted
12879     // (i.e. this va_arg is guaranteed to have undefined behavior).
12880     QualType PromoteType;
12881     if (TInfo->getType()->isPromotableIntegerType()) {
12882       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12883       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12884         PromoteType = QualType();
12885     }
12886     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12887       PromoteType = Context.DoubleTy;
12888     if (!PromoteType.isNull())
12889       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12890                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12891                           << TInfo->getType()
12892                           << PromoteType
12893                           << TInfo->getTypeLoc().getSourceRange());
12894   }
12895
12896   QualType T = TInfo->getType().getNonLValueExprType(Context);
12897   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12898 }
12899
12900 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12901   // The type of __null will be int or long, depending on the size of
12902   // pointers on the target.
12903   QualType Ty;
12904   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12905   if (pw == Context.getTargetInfo().getIntWidth())
12906     Ty = Context.IntTy;
12907   else if (pw == Context.getTargetInfo().getLongWidth())
12908     Ty = Context.LongTy;
12909   else if (pw == Context.getTargetInfo().getLongLongWidth())
12910     Ty = Context.LongLongTy;
12911   else {
12912     llvm_unreachable("I don't know size of pointer!");
12913   }
12914
12915   return new (Context) GNUNullExpr(Ty, TokenLoc);
12916 }
12917
12918 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12919                                               bool Diagnose) {
12920   if (!getLangOpts().ObjC1)
12921     return false;
12922
12923   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12924   if (!PT)
12925     return false;
12926
12927   if (!PT->isObjCIdType()) {
12928     // Check if the destination is the 'NSString' interface.
12929     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12930     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12931       return false;
12932   }
12933   
12934   // Ignore any parens, implicit casts (should only be
12935   // array-to-pointer decays), and not-so-opaque values.  The last is
12936   // important for making this trigger for property assignments.
12937   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12938   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12939     if (OV->getSourceExpr())
12940       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12941
12942   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12943   if (!SL || !SL->isAscii())
12944     return false;
12945   if (Diagnose) {
12946     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12947       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12948     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12949   }
12950   return true;
12951 }
12952
12953 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12954                                               const Expr *SrcExpr) {
12955   if (!DstType->isFunctionPointerType() ||
12956       !SrcExpr->getType()->isFunctionType())
12957     return false;
12958
12959   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12960   if (!DRE)
12961     return false;
12962
12963   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12964   if (!FD)
12965     return false;
12966
12967   return !S.checkAddressOfFunctionIsAvailable(FD,
12968                                               /*Complain=*/true,
12969                                               SrcExpr->getLocStart());
12970 }
12971
12972 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12973                                     SourceLocation Loc,
12974                                     QualType DstType, QualType SrcType,
12975                                     Expr *SrcExpr, AssignmentAction Action,
12976                                     bool *Complained) {
12977   if (Complained)
12978     *Complained = false;
12979
12980   // Decode the result (notice that AST's are still created for extensions).
12981   bool CheckInferredResultType = false;
12982   bool isInvalid = false;
12983   unsigned DiagKind = 0;
12984   FixItHint Hint;
12985   ConversionFixItGenerator ConvHints;
12986   bool MayHaveConvFixit = false;
12987   bool MayHaveFunctionDiff = false;
12988   const ObjCInterfaceDecl *IFace = nullptr;
12989   const ObjCProtocolDecl *PDecl = nullptr;
12990
12991   switch (ConvTy) {
12992   case Compatible:
12993       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12994       return false;
12995
12996   case PointerToInt:
12997     DiagKind = diag::ext_typecheck_convert_pointer_int;
12998     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12999     MayHaveConvFixit = true;
13000     break;
13001   case IntToPointer:
13002     DiagKind = diag::ext_typecheck_convert_int_pointer;
13003     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13004     MayHaveConvFixit = true;
13005     break;
13006   case IncompatiblePointer:
13007     if (Action == AA_Passing_CFAudited)
13008       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13009     else if (SrcType->isFunctionPointerType() &&
13010              DstType->isFunctionPointerType())
13011       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13012     else
13013       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13014
13015     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13016       SrcType->isObjCObjectPointerType();
13017     if (Hint.isNull() && !CheckInferredResultType) {
13018       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13019     }
13020     else if (CheckInferredResultType) {
13021       SrcType = SrcType.getUnqualifiedType();
13022       DstType = DstType.getUnqualifiedType();
13023     }
13024     MayHaveConvFixit = true;
13025     break;
13026   case IncompatiblePointerSign:
13027     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13028     break;
13029   case FunctionVoidPointer:
13030     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13031     break;
13032   case IncompatiblePointerDiscardsQualifiers: {
13033     // Perform array-to-pointer decay if necessary.
13034     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13035
13036     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13037     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13038     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13039       DiagKind = diag::err_typecheck_incompatible_address_space;
13040       break;
13041
13042
13043     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13044       DiagKind = diag::err_typecheck_incompatible_ownership;
13045       break;
13046     }
13047
13048     llvm_unreachable("unknown error case for discarding qualifiers!");
13049     // fallthrough
13050   }
13051   case CompatiblePointerDiscardsQualifiers:
13052     // If the qualifiers lost were because we were applying the
13053     // (deprecated) C++ conversion from a string literal to a char*
13054     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13055     // Ideally, this check would be performed in
13056     // checkPointerTypesForAssignment. However, that would require a
13057     // bit of refactoring (so that the second argument is an
13058     // expression, rather than a type), which should be done as part
13059     // of a larger effort to fix checkPointerTypesForAssignment for
13060     // C++ semantics.
13061     if (getLangOpts().CPlusPlus &&
13062         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13063       return false;
13064     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13065     break;
13066   case IncompatibleNestedPointerQualifiers:
13067     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13068     break;
13069   case IntToBlockPointer:
13070     DiagKind = diag::err_int_to_block_pointer;
13071     break;
13072   case IncompatibleBlockPointer:
13073     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13074     break;
13075   case IncompatibleObjCQualifiedId: {
13076     if (SrcType->isObjCQualifiedIdType()) {
13077       const ObjCObjectPointerType *srcOPT =
13078                 SrcType->getAs<ObjCObjectPointerType>();
13079       for (auto *srcProto : srcOPT->quals()) {
13080         PDecl = srcProto;
13081         break;
13082       }
13083       if (const ObjCInterfaceType *IFaceT =
13084             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13085         IFace = IFaceT->getDecl();
13086     }
13087     else if (DstType->isObjCQualifiedIdType()) {
13088       const ObjCObjectPointerType *dstOPT =
13089         DstType->getAs<ObjCObjectPointerType>();
13090       for (auto *dstProto : dstOPT->quals()) {
13091         PDecl = dstProto;
13092         break;
13093       }
13094       if (const ObjCInterfaceType *IFaceT =
13095             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13096         IFace = IFaceT->getDecl();
13097     }
13098     DiagKind = diag::warn_incompatible_qualified_id;
13099     break;
13100   }
13101   case IncompatibleVectors:
13102     DiagKind = diag::warn_incompatible_vectors;
13103     break;
13104   case IncompatibleObjCWeakRef:
13105     DiagKind = diag::err_arc_weak_unavailable_assign;
13106     break;
13107   case Incompatible:
13108     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13109       if (Complained)
13110         *Complained = true;
13111       return true;
13112     }
13113
13114     DiagKind = diag::err_typecheck_convert_incompatible;
13115     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13116     MayHaveConvFixit = true;
13117     isInvalid = true;
13118     MayHaveFunctionDiff = true;
13119     break;
13120   }
13121
13122   QualType FirstType, SecondType;
13123   switch (Action) {
13124   case AA_Assigning:
13125   case AA_Initializing:
13126     // The destination type comes first.
13127     FirstType = DstType;
13128     SecondType = SrcType;
13129     break;
13130
13131   case AA_Returning:
13132   case AA_Passing:
13133   case AA_Passing_CFAudited:
13134   case AA_Converting:
13135   case AA_Sending:
13136   case AA_Casting:
13137     // The source type comes first.
13138     FirstType = SrcType;
13139     SecondType = DstType;
13140     break;
13141   }
13142
13143   PartialDiagnostic FDiag = PDiag(DiagKind);
13144   if (Action == AA_Passing_CFAudited)
13145     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13146   else
13147     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13148
13149   // If we can fix the conversion, suggest the FixIts.
13150   assert(ConvHints.isNull() || Hint.isNull());
13151   if (!ConvHints.isNull()) {
13152     for (FixItHint &H : ConvHints.Hints)
13153       FDiag << H;
13154   } else {
13155     FDiag << Hint;
13156   }
13157   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13158
13159   if (MayHaveFunctionDiff)
13160     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13161
13162   Diag(Loc, FDiag);
13163   if (DiagKind == diag::warn_incompatible_qualified_id &&
13164       PDecl && IFace && !IFace->hasDefinition())
13165       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13166         << IFace->getName() << PDecl->getName();
13167     
13168   if (SecondType == Context.OverloadTy)
13169     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13170                               FirstType, /*TakingAddress=*/true);
13171
13172   if (CheckInferredResultType)
13173     EmitRelatedResultTypeNote(SrcExpr);
13174
13175   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13176     EmitRelatedResultTypeNoteForReturn(DstType);
13177   
13178   if (Complained)
13179     *Complained = true;
13180   return isInvalid;
13181 }
13182
13183 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13184                                                  llvm::APSInt *Result) {
13185   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13186   public:
13187     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13188       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13189     }
13190   } Diagnoser;
13191   
13192   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13193 }
13194
13195 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13196                                                  llvm::APSInt *Result,
13197                                                  unsigned DiagID,
13198                                                  bool AllowFold) {
13199   class IDDiagnoser : public VerifyICEDiagnoser {
13200     unsigned DiagID;
13201     
13202   public:
13203     IDDiagnoser(unsigned DiagID)
13204       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13205     
13206     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13207       S.Diag(Loc, DiagID) << SR;
13208     }
13209   } Diagnoser(DiagID);
13210   
13211   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13212 }
13213
13214 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13215                                             SourceRange SR) {
13216   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13217 }
13218
13219 ExprResult
13220 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13221                                       VerifyICEDiagnoser &Diagnoser,
13222                                       bool AllowFold) {
13223   SourceLocation DiagLoc = E->getLocStart();
13224
13225   if (getLangOpts().CPlusPlus11) {
13226     // C++11 [expr.const]p5:
13227     //   If an expression of literal class type is used in a context where an
13228     //   integral constant expression is required, then that class type shall
13229     //   have a single non-explicit conversion function to an integral or
13230     //   unscoped enumeration type
13231     ExprResult Converted;
13232     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13233     public:
13234       CXX11ConvertDiagnoser(bool Silent)
13235           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13236                                 Silent, true) {}
13237
13238       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13239                                            QualType T) override {
13240         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13241       }
13242
13243       SemaDiagnosticBuilder diagnoseIncomplete(
13244           Sema &S, SourceLocation Loc, QualType T) override {
13245         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13246       }
13247
13248       SemaDiagnosticBuilder diagnoseExplicitConv(
13249           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13250         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13251       }
13252
13253       SemaDiagnosticBuilder noteExplicitConv(
13254           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13255         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13256                  << ConvTy->isEnumeralType() << ConvTy;
13257       }
13258
13259       SemaDiagnosticBuilder diagnoseAmbiguous(
13260           Sema &S, SourceLocation Loc, QualType T) override {
13261         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13262       }
13263
13264       SemaDiagnosticBuilder noteAmbiguous(
13265           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13266         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13267                  << ConvTy->isEnumeralType() << ConvTy;
13268       }
13269
13270       SemaDiagnosticBuilder diagnoseConversion(
13271           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13272         llvm_unreachable("conversion functions are permitted");
13273       }
13274     } ConvertDiagnoser(Diagnoser.Suppress);
13275
13276     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13277                                                     ConvertDiagnoser);
13278     if (Converted.isInvalid())
13279       return Converted;
13280     E = Converted.get();
13281     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13282       return ExprError();
13283   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13284     // An ICE must be of integral or unscoped enumeration type.
13285     if (!Diagnoser.Suppress)
13286       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13287     return ExprError();
13288   }
13289
13290   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13291   // in the non-ICE case.
13292   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13293     if (Result)
13294       *Result = E->EvaluateKnownConstInt(Context);
13295     return E;
13296   }
13297
13298   Expr::EvalResult EvalResult;
13299   SmallVector<PartialDiagnosticAt, 8> Notes;
13300   EvalResult.Diag = &Notes;
13301
13302   // Try to evaluate the expression, and produce diagnostics explaining why it's
13303   // not a constant expression as a side-effect.
13304   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13305                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13306
13307   // In C++11, we can rely on diagnostics being produced for any expression
13308   // which is not a constant expression. If no diagnostics were produced, then
13309   // this is a constant expression.
13310   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13311     if (Result)
13312       *Result = EvalResult.Val.getInt();
13313     return E;
13314   }
13315
13316   // If our only note is the usual "invalid subexpression" note, just point
13317   // the caret at its location rather than producing an essentially
13318   // redundant note.
13319   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13320         diag::note_invalid_subexpr_in_const_expr) {
13321     DiagLoc = Notes[0].first;
13322     Notes.clear();
13323   }
13324
13325   if (!Folded || !AllowFold) {
13326     if (!Diagnoser.Suppress) {
13327       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13328       for (const PartialDiagnosticAt &Note : Notes)
13329         Diag(Note.first, Note.second);
13330     }
13331
13332     return ExprError();
13333   }
13334
13335   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13336   for (const PartialDiagnosticAt &Note : Notes)
13337     Diag(Note.first, Note.second);
13338
13339   if (Result)
13340     *Result = EvalResult.Val.getInt();
13341   return E;
13342 }
13343
13344 namespace {
13345   // Handle the case where we conclude a expression which we speculatively
13346   // considered to be unevaluated is actually evaluated.
13347   class TransformToPE : public TreeTransform<TransformToPE> {
13348     typedef TreeTransform<TransformToPE> BaseTransform;
13349
13350   public:
13351     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13352
13353     // Make sure we redo semantic analysis
13354     bool AlwaysRebuild() { return true; }
13355
13356     // Make sure we handle LabelStmts correctly.
13357     // FIXME: This does the right thing, but maybe we need a more general
13358     // fix to TreeTransform?
13359     StmtResult TransformLabelStmt(LabelStmt *S) {
13360       S->getDecl()->setStmt(nullptr);
13361       return BaseTransform::TransformLabelStmt(S);
13362     }
13363
13364     // We need to special-case DeclRefExprs referring to FieldDecls which
13365     // are not part of a member pointer formation; normal TreeTransforming
13366     // doesn't catch this case because of the way we represent them in the AST.
13367     // FIXME: This is a bit ugly; is it really the best way to handle this
13368     // case?
13369     //
13370     // Error on DeclRefExprs referring to FieldDecls.
13371     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13372       if (isa<FieldDecl>(E->getDecl()) &&
13373           !SemaRef.isUnevaluatedContext())
13374         return SemaRef.Diag(E->getLocation(),
13375                             diag::err_invalid_non_static_member_use)
13376             << E->getDecl() << E->getSourceRange();
13377
13378       return BaseTransform::TransformDeclRefExpr(E);
13379     }
13380
13381     // Exception: filter out member pointer formation
13382     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13383       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13384         return E;
13385
13386       return BaseTransform::TransformUnaryOperator(E);
13387     }
13388
13389     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13390       // Lambdas never need to be transformed.
13391       return E;
13392     }
13393   };
13394 }
13395
13396 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13397   assert(isUnevaluatedContext() &&
13398          "Should only transform unevaluated expressions");
13399   ExprEvalContexts.back().Context =
13400       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13401   if (isUnevaluatedContext())
13402     return E;
13403   return TransformToPE(*this).TransformExpr(E);
13404 }
13405
13406 void
13407 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13408                                       Decl *LambdaContextDecl,
13409                                       bool IsDecltype) {
13410   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13411                                 LambdaContextDecl, IsDecltype);
13412   Cleanup.reset();
13413   if (!MaybeODRUseExprs.empty())
13414     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13415 }
13416
13417 void
13418 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13419                                       ReuseLambdaContextDecl_t,
13420                                       bool IsDecltype) {
13421   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13422   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13423 }
13424
13425 void Sema::PopExpressionEvaluationContext() {
13426   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13427   unsigned NumTypos = Rec.NumTypos;
13428
13429   if (!Rec.Lambdas.empty()) {
13430     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13431       unsigned D;
13432       if (Rec.isUnevaluated()) {
13433         // C++11 [expr.prim.lambda]p2:
13434         //   A lambda-expression shall not appear in an unevaluated operand
13435         //   (Clause 5).
13436         D = diag::err_lambda_unevaluated_operand;
13437       } else {
13438         // C++1y [expr.const]p2:
13439         //   A conditional-expression e is a core constant expression unless the
13440         //   evaluation of e, following the rules of the abstract machine, would
13441         //   evaluate [...] a lambda-expression.
13442         D = diag::err_lambda_in_constant_expression;
13443       }
13444
13445       // C++1z allows lambda expressions as core constant expressions.
13446       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13447       // 1607) from appearing within template-arguments and array-bounds that
13448       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13449       // unevaluated contexts) might lift some of these restrictions in a 
13450       // future version.
13451       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13452         for (const auto *L : Rec.Lambdas)
13453           Diag(L->getLocStart(), D);
13454     } else {
13455       // Mark the capture expressions odr-used. This was deferred
13456       // during lambda expression creation.
13457       for (auto *Lambda : Rec.Lambdas) {
13458         for (auto *C : Lambda->capture_inits())
13459           MarkDeclarationsReferencedInExpr(C);
13460       }
13461     }
13462   }
13463
13464   // When are coming out of an unevaluated context, clear out any
13465   // temporaries that we may have created as part of the evaluation of
13466   // the expression in that context: they aren't relevant because they
13467   // will never be constructed.
13468   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13469     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13470                              ExprCleanupObjects.end());
13471     Cleanup = Rec.ParentCleanup;
13472     CleanupVarDeclMarking();
13473     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13474   // Otherwise, merge the contexts together.
13475   } else {
13476     Cleanup.mergeFrom(Rec.ParentCleanup);
13477     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13478                             Rec.SavedMaybeODRUseExprs.end());
13479   }
13480
13481   // Pop the current expression evaluation context off the stack.
13482   ExprEvalContexts.pop_back();
13483
13484   if (!ExprEvalContexts.empty())
13485     ExprEvalContexts.back().NumTypos += NumTypos;
13486   else
13487     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13488                             "last ExpressionEvaluationContextRecord");
13489 }
13490
13491 void Sema::DiscardCleanupsInEvaluationContext() {
13492   ExprCleanupObjects.erase(
13493          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13494          ExprCleanupObjects.end());
13495   Cleanup.reset();
13496   MaybeODRUseExprs.clear();
13497 }
13498
13499 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13500   if (!E->getType()->isVariablyModifiedType())
13501     return E;
13502   return TransformToPotentiallyEvaluated(E);
13503 }
13504
13505 /// Are we within a context in which some evaluation could be performed (be it
13506 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13507 /// captured by C++'s idea of an "unevaluated context".
13508 static bool isEvaluatableContext(Sema &SemaRef) {
13509   switch (SemaRef.ExprEvalContexts.back().Context) {
13510     case Sema::ExpressionEvaluationContext::Unevaluated:
13511     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13512     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13513       // Expressions in this context are never evaluated.
13514       return false;
13515
13516     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13517     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13518     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13519       // Expressions in this context could be evaluated.
13520       return true;
13521
13522     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13523       // Referenced declarations will only be used if the construct in the
13524       // containing expression is used, at which point we'll be given another
13525       // turn to mark them.
13526       return false;
13527   }
13528   llvm_unreachable("Invalid context");
13529 }
13530
13531 /// Are we within a context in which references to resolved functions or to
13532 /// variables result in odr-use?
13533 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13534   // An expression in a template is not really an expression until it's been
13535   // instantiated, so it doesn't trigger odr-use.
13536   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13537     return false;
13538
13539   switch (SemaRef.ExprEvalContexts.back().Context) {
13540     case Sema::ExpressionEvaluationContext::Unevaluated:
13541     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13542     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13543     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13544       return false;
13545
13546     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13547     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13548       return true;
13549
13550     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13551       return false;
13552   }
13553   llvm_unreachable("Invalid context");
13554 }
13555
13556 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13557   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13558   return Func->isConstexpr() &&
13559          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13560 }
13561
13562 /// \brief Mark a function referenced, and check whether it is odr-used
13563 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13564 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13565                                   bool MightBeOdrUse) {
13566   assert(Func && "No function?");
13567
13568   Func->setReferenced();
13569
13570   // C++11 [basic.def.odr]p3:
13571   //   A function whose name appears as a potentially-evaluated expression is
13572   //   odr-used if it is the unique lookup result or the selected member of a
13573   //   set of overloaded functions [...].
13574   //
13575   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13576   // can just check that here.
13577   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13578
13579   // Determine whether we require a function definition to exist, per
13580   // C++11 [temp.inst]p3:
13581   //   Unless a function template specialization has been explicitly
13582   //   instantiated or explicitly specialized, the function template
13583   //   specialization is implicitly instantiated when the specialization is
13584   //   referenced in a context that requires a function definition to exist.
13585   //
13586   // That is either when this is an odr-use, or when a usage of a constexpr
13587   // function occurs within an evaluatable context.
13588   bool NeedDefinition =
13589       OdrUse || (isEvaluatableContext(*this) &&
13590                  isImplicitlyDefinableConstexprFunction(Func));
13591
13592   // C++14 [temp.expl.spec]p6:
13593   //   If a template [...] is explicitly specialized then that specialization
13594   //   shall be declared before the first use of that specialization that would
13595   //   cause an implicit instantiation to take place, in every translation unit
13596   //   in which such a use occurs
13597   if (NeedDefinition &&
13598       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13599        Func->getMemberSpecializationInfo()))
13600     checkSpecializationVisibility(Loc, Func);
13601
13602   // C++14 [except.spec]p17:
13603   //   An exception-specification is considered to be needed when:
13604   //   - the function is odr-used or, if it appears in an unevaluated operand,
13605   //     would be odr-used if the expression were potentially-evaluated;
13606   //
13607   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13608   // function is a pure virtual function we're calling, and in that case the
13609   // function was selected by overload resolution and we need to resolve its
13610   // exception specification for a different reason.
13611   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13612   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13613     ResolveExceptionSpec(Loc, FPT);
13614
13615   // If we don't need to mark the function as used, and we don't need to
13616   // try to provide a definition, there's nothing more to do.
13617   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13618       (!NeedDefinition || Func->getBody()))
13619     return;
13620
13621   // Note that this declaration has been used.
13622   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13623     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13624     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13625       if (Constructor->isDefaultConstructor()) {
13626         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13627           return;
13628         DefineImplicitDefaultConstructor(Loc, Constructor);
13629       } else if (Constructor->isCopyConstructor()) {
13630         DefineImplicitCopyConstructor(Loc, Constructor);
13631       } else if (Constructor->isMoveConstructor()) {
13632         DefineImplicitMoveConstructor(Loc, Constructor);
13633       }
13634     } else if (Constructor->getInheritedConstructor()) {
13635       DefineInheritingConstructor(Loc, Constructor);
13636     }
13637   } else if (CXXDestructorDecl *Destructor =
13638                  dyn_cast<CXXDestructorDecl>(Func)) {
13639     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13640     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13641       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13642         return;
13643       DefineImplicitDestructor(Loc, Destructor);
13644     }
13645     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13646       MarkVTableUsed(Loc, Destructor->getParent());
13647   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13648     if (MethodDecl->isOverloadedOperator() &&
13649         MethodDecl->getOverloadedOperator() == OO_Equal) {
13650       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13651       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13652         if (MethodDecl->isCopyAssignmentOperator())
13653           DefineImplicitCopyAssignment(Loc, MethodDecl);
13654         else if (MethodDecl->isMoveAssignmentOperator())
13655           DefineImplicitMoveAssignment(Loc, MethodDecl);
13656       }
13657     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13658                MethodDecl->getParent()->isLambda()) {
13659       CXXConversionDecl *Conversion =
13660           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13661       if (Conversion->isLambdaToBlockPointerConversion())
13662         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13663       else
13664         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13665     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13666       MarkVTableUsed(Loc, MethodDecl->getParent());
13667   }
13668
13669   // Recursive functions should be marked when used from another function.
13670   // FIXME: Is this really right?
13671   if (CurContext == Func) return;
13672
13673   // Implicit instantiation of function templates and member functions of
13674   // class templates.
13675   if (Func->isImplicitlyInstantiable()) {
13676     bool AlreadyInstantiated = false;
13677     SourceLocation PointOfInstantiation = Loc;
13678     if (FunctionTemplateSpecializationInfo *SpecInfo
13679                               = Func->getTemplateSpecializationInfo()) {
13680       if (SpecInfo->getPointOfInstantiation().isInvalid())
13681         SpecInfo->setPointOfInstantiation(Loc);
13682       else if (SpecInfo->getTemplateSpecializationKind()
13683                  == TSK_ImplicitInstantiation) {
13684         AlreadyInstantiated = true;
13685         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13686       }
13687     } else if (MemberSpecializationInfo *MSInfo
13688                                 = Func->getMemberSpecializationInfo()) {
13689       if (MSInfo->getPointOfInstantiation().isInvalid())
13690         MSInfo->setPointOfInstantiation(Loc);
13691       else if (MSInfo->getTemplateSpecializationKind()
13692                  == TSK_ImplicitInstantiation) {
13693         AlreadyInstantiated = true;
13694         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13695       }
13696     }
13697
13698     if (!AlreadyInstantiated || Func->isConstexpr()) {
13699       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13700           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13701           CodeSynthesisContexts.size())
13702         PendingLocalImplicitInstantiations.push_back(
13703             std::make_pair(Func, PointOfInstantiation));
13704       else if (Func->isConstexpr())
13705         // Do not defer instantiations of constexpr functions, to avoid the
13706         // expression evaluator needing to call back into Sema if it sees a
13707         // call to such a function.
13708         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13709       else {
13710         PendingInstantiations.push_back(std::make_pair(Func,
13711                                                        PointOfInstantiation));
13712         // Notify the consumer that a function was implicitly instantiated.
13713         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13714       }
13715     }
13716   } else {
13717     // Walk redefinitions, as some of them may be instantiable.
13718     for (auto i : Func->redecls()) {
13719       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13720         MarkFunctionReferenced(Loc, i, OdrUse);
13721     }
13722   }
13723
13724   if (!OdrUse) return;
13725
13726   // Keep track of used but undefined functions.
13727   if (!Func->isDefined()) {
13728     if (mightHaveNonExternalLinkage(Func))
13729       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13730     else if (Func->getMostRecentDecl()->isInlined() &&
13731              !LangOpts.GNUInline &&
13732              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13733       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13734   }
13735
13736   Func->markUsed(Context);
13737 }
13738
13739 static void
13740 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13741                                    ValueDecl *var, DeclContext *DC) {
13742   DeclContext *VarDC = var->getDeclContext();
13743
13744   //  If the parameter still belongs to the translation unit, then
13745   //  we're actually just using one parameter in the declaration of
13746   //  the next.
13747   if (isa<ParmVarDecl>(var) &&
13748       isa<TranslationUnitDecl>(VarDC))
13749     return;
13750
13751   // For C code, don't diagnose about capture if we're not actually in code
13752   // right now; it's impossible to write a non-constant expression outside of
13753   // function context, so we'll get other (more useful) diagnostics later.
13754   //
13755   // For C++, things get a bit more nasty... it would be nice to suppress this
13756   // diagnostic for certain cases like using a local variable in an array bound
13757   // for a member of a local class, but the correct predicate is not obvious.
13758   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13759     return;
13760
13761   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13762   unsigned ContextKind = 3; // unknown
13763   if (isa<CXXMethodDecl>(VarDC) &&
13764       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13765     ContextKind = 2;
13766   } else if (isa<FunctionDecl>(VarDC)) {
13767     ContextKind = 0;
13768   } else if (isa<BlockDecl>(VarDC)) {
13769     ContextKind = 1;
13770   }
13771
13772   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13773     << var << ValueKind << ContextKind << VarDC;
13774   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13775       << var;
13776
13777   // FIXME: Add additional diagnostic info about class etc. which prevents
13778   // capture.
13779 }
13780
13781  
13782 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
13783                                       bool &SubCapturesAreNested,
13784                                       QualType &CaptureType, 
13785                                       QualType &DeclRefType) {
13786    // Check whether we've already captured it.
13787   if (CSI->CaptureMap.count(Var)) {
13788     // If we found a capture, any subcaptures are nested.
13789     SubCapturesAreNested = true;
13790       
13791     // Retrieve the capture type for this variable.
13792     CaptureType = CSI->getCapture(Var).getCaptureType();
13793       
13794     // Compute the type of an expression that refers to this variable.
13795     DeclRefType = CaptureType.getNonReferenceType();
13796
13797     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13798     // are mutable in the sense that user can change their value - they are
13799     // private instances of the captured declarations.
13800     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13801     if (Cap.isCopyCapture() &&
13802         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13803         !(isa<CapturedRegionScopeInfo>(CSI) &&
13804           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13805       DeclRefType.addConst();
13806     return true;
13807   }
13808   return false;
13809 }
13810
13811 // Only block literals, captured statements, and lambda expressions can
13812 // capture; other scopes don't work.
13813 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
13814                                  SourceLocation Loc, 
13815                                  const bool Diagnose, Sema &S) {
13816   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13817     return getLambdaAwareParentOfDeclContext(DC);
13818   else if (Var->hasLocalStorage()) {
13819     if (Diagnose)
13820        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13821   }
13822   return nullptr;
13823 }
13824
13825 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13826 // certain types of variables (unnamed, variably modified types etc.)
13827 // so check for eligibility.
13828 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
13829                                  SourceLocation Loc, 
13830                                  const bool Diagnose, Sema &S) {
13831
13832   bool IsBlock = isa<BlockScopeInfo>(CSI);
13833   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13834
13835   // Lambdas are not allowed to capture unnamed variables
13836   // (e.g. anonymous unions).
13837   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13838   // assuming that's the intent.
13839   if (IsLambda && !Var->getDeclName()) {
13840     if (Diagnose) {
13841       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13842       S.Diag(Var->getLocation(), diag::note_declared_at);
13843     }
13844     return false;
13845   }
13846
13847   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13848   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13849     if (Diagnose) {
13850       S.Diag(Loc, diag::err_ref_vm_type);
13851       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13852         << Var->getDeclName();
13853     }
13854     return false;
13855   }
13856   // Prohibit structs with flexible array members too.
13857   // We cannot capture what is in the tail end of the struct.
13858   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13859     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13860       if (Diagnose) {
13861         if (IsBlock)
13862           S.Diag(Loc, diag::err_ref_flexarray_type);
13863         else
13864           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13865             << Var->getDeclName();
13866         S.Diag(Var->getLocation(), diag::note_previous_decl)
13867           << Var->getDeclName();
13868       }
13869       return false;
13870     }
13871   }
13872   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13873   // Lambdas and captured statements are not allowed to capture __block
13874   // variables; they don't support the expected semantics.
13875   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13876     if (Diagnose) {
13877       S.Diag(Loc, diag::err_capture_block_variable)
13878         << Var->getDeclName() << !IsLambda;
13879       S.Diag(Var->getLocation(), diag::note_previous_decl)
13880         << Var->getDeclName();
13881     }
13882     return false;
13883   }
13884   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13885   if (S.getLangOpts().OpenCL && IsBlock &&
13886       Var->getType()->isBlockPointerType()) {
13887     if (Diagnose)
13888       S.Diag(Loc, diag::err_opencl_block_ref_block);
13889     return false;
13890   }
13891
13892   return true;
13893 }
13894
13895 // Returns true if the capture by block was successful.
13896 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
13897                                  SourceLocation Loc, 
13898                                  const bool BuildAndDiagnose, 
13899                                  QualType &CaptureType,
13900                                  QualType &DeclRefType, 
13901                                  const bool Nested,
13902                                  Sema &S) {
13903   Expr *CopyExpr = nullptr;
13904   bool ByRef = false;
13905       
13906   // Blocks are not allowed to capture arrays.
13907   if (CaptureType->isArrayType()) {
13908     if (BuildAndDiagnose) {
13909       S.Diag(Loc, diag::err_ref_array_type);
13910       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13911       << Var->getDeclName();
13912     }
13913     return false;
13914   }
13915
13916   // Forbid the block-capture of autoreleasing variables.
13917   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13918     if (BuildAndDiagnose) {
13919       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13920         << /*block*/ 0;
13921       S.Diag(Var->getLocation(), diag::note_previous_decl)
13922         << Var->getDeclName();
13923     }
13924     return false;
13925   }
13926
13927   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13928   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13929     // This function finds out whether there is an AttributedType of kind
13930     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13931     // attr_objc_ownership implies __autoreleasing was explicitly specified
13932     // rather than being added implicitly by the compiler.
13933     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13934       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13935         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13936           return true;
13937
13938         // Peel off AttributedTypes that are not of kind objc_ownership.
13939         Ty = AttrTy->getModifiedType();
13940       }
13941
13942       return false;
13943     };
13944
13945     QualType PointeeTy = PT->getPointeeType();
13946
13947     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13948         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13949         !IsObjCOwnershipAttributedType(PointeeTy)) {
13950       if (BuildAndDiagnose) {
13951         SourceLocation VarLoc = Var->getLocation();
13952         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13953         {
13954           auto AddAutoreleaseNote =
13955               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13956           // Provide a fix-it for the '__autoreleasing' keyword at the
13957           // appropriate location in the variable's type.
13958           if (const auto *TSI = Var->getTypeSourceInfo()) {
13959             PointerTypeLoc PTL =
13960                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13961             if (PTL) {
13962               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13963               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13964                                                S.getLangOpts());
13965               if (Loc.isValid()) {
13966                 StringRef CharAtLoc = Lexer::getSourceText(
13967                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13968                     S.getSourceManager(), S.getLangOpts());
13969                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13970                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13971                              ? " __autoreleasing "
13972                              : " __autoreleasing");
13973               }
13974             }
13975           }
13976         }
13977         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13978       }
13979     }
13980   }
13981
13982   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13983   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13984       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13985     // Block capture by reference does not change the capture or
13986     // declaration reference types.
13987     ByRef = true;
13988   } else {
13989     // Block capture by copy introduces 'const'.
13990     CaptureType = CaptureType.getNonReferenceType().withConst();
13991     DeclRefType = CaptureType;
13992                 
13993     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13994       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13995         // The capture logic needs the destructor, so make sure we mark it.
13996         // Usually this is unnecessary because most local variables have
13997         // their destructors marked at declaration time, but parameters are
13998         // an exception because it's technically only the call site that
13999         // actually requires the destructor.
14000         if (isa<ParmVarDecl>(Var))
14001           S.FinalizeVarWithDestructor(Var, Record);
14002
14003         // Enter a new evaluation context to insulate the copy
14004         // full-expression.
14005         EnterExpressionEvaluationContext scope(
14006             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14007
14008         // According to the blocks spec, the capture of a variable from
14009         // the stack requires a const copy constructor.  This is not true
14010         // of the copy/move done to move a __block variable to the heap.
14011         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14012                                                   DeclRefType.withConst(), 
14013                                                   VK_LValue, Loc);
14014             
14015         ExprResult Result
14016           = S.PerformCopyInitialization(
14017               InitializedEntity::InitializeBlock(Var->getLocation(),
14018                                                   CaptureType, false),
14019               Loc, DeclRef);
14020             
14021         // Build a full-expression copy expression if initialization
14022         // succeeded and used a non-trivial constructor.  Recover from
14023         // errors by pretending that the copy isn't necessary.
14024         if (!Result.isInvalid() &&
14025             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14026                 ->isTrivial()) {
14027           Result = S.MaybeCreateExprWithCleanups(Result);
14028           CopyExpr = Result.get();
14029         }
14030       }
14031     }
14032   }
14033
14034   // Actually capture the variable.
14035   if (BuildAndDiagnose)
14036     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
14037                     SourceLocation(), CaptureType, CopyExpr);
14038
14039   return true;
14040
14041 }
14042
14043
14044 /// \brief Capture the given variable in the captured region.
14045 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14046                                     VarDecl *Var, 
14047                                     SourceLocation Loc, 
14048                                     const bool BuildAndDiagnose, 
14049                                     QualType &CaptureType,
14050                                     QualType &DeclRefType, 
14051                                     const bool RefersToCapturedVariable,
14052                                     Sema &S) {
14053   // By default, capture variables by reference.
14054   bool ByRef = true;
14055   // Using an LValue reference type is consistent with Lambdas (see below).
14056   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14057     if (S.IsOpenMPCapturedDecl(Var))
14058       DeclRefType = DeclRefType.getUnqualifiedType();
14059     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14060   }
14061
14062   if (ByRef)
14063     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14064   else
14065     CaptureType = DeclRefType;
14066
14067   Expr *CopyExpr = nullptr;
14068   if (BuildAndDiagnose) {
14069     // The current implementation assumes that all variables are captured
14070     // by references. Since there is no capture by copy, no expression
14071     // evaluation will be needed.
14072     RecordDecl *RD = RSI->TheRecordDecl;
14073
14074     FieldDecl *Field
14075       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14076                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14077                           nullptr, false, ICIS_NoInit);
14078     Field->setImplicit(true);
14079     Field->setAccess(AS_private);
14080     RD->addDecl(Field);
14081  
14082     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14083                                             DeclRefType, VK_LValue, Loc);
14084     Var->setReferenced(true);
14085     Var->markUsed(S.Context);
14086   }
14087
14088   // Actually capture the variable.
14089   if (BuildAndDiagnose)
14090     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14091                     SourceLocation(), CaptureType, CopyExpr);
14092   
14093   
14094   return true;
14095 }
14096
14097 /// \brief Create a field within the lambda class for the variable
14098 /// being captured.
14099 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 
14100                                     QualType FieldType, QualType DeclRefType,
14101                                     SourceLocation Loc,
14102                                     bool RefersToCapturedVariable) {
14103   CXXRecordDecl *Lambda = LSI->Lambda;
14104
14105   // Build the non-static data member.
14106   FieldDecl *Field
14107     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14108                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14109                         nullptr, false, ICIS_NoInit);
14110   Field->setImplicit(true);
14111   Field->setAccess(AS_private);
14112   Lambda->addDecl(Field);
14113 }
14114
14115 /// \brief Capture the given variable in the lambda.
14116 static bool captureInLambda(LambdaScopeInfo *LSI,
14117                             VarDecl *Var, 
14118                             SourceLocation Loc, 
14119                             const bool BuildAndDiagnose, 
14120                             QualType &CaptureType,
14121                             QualType &DeclRefType, 
14122                             const bool RefersToCapturedVariable,
14123                             const Sema::TryCaptureKind Kind, 
14124                             SourceLocation EllipsisLoc,
14125                             const bool IsTopScope,
14126                             Sema &S) {
14127
14128   // Determine whether we are capturing by reference or by value.
14129   bool ByRef = false;
14130   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14131     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14132   } else {
14133     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14134   }
14135     
14136   // Compute the type of the field that will capture this variable.
14137   if (ByRef) {
14138     // C++11 [expr.prim.lambda]p15:
14139     //   An entity is captured by reference if it is implicitly or
14140     //   explicitly captured but not captured by copy. It is
14141     //   unspecified whether additional unnamed non-static data
14142     //   members are declared in the closure type for entities
14143     //   captured by reference.
14144     //
14145     // FIXME: It is not clear whether we want to build an lvalue reference
14146     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14147     // to do the former, while EDG does the latter. Core issue 1249 will 
14148     // clarify, but for now we follow GCC because it's a more permissive and
14149     // easily defensible position.
14150     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14151   } else {
14152     // C++11 [expr.prim.lambda]p14:
14153     //   For each entity captured by copy, an unnamed non-static
14154     //   data member is declared in the closure type. The
14155     //   declaration order of these members is unspecified. The type
14156     //   of such a data member is the type of the corresponding
14157     //   captured entity if the entity is not a reference to an
14158     //   object, or the referenced type otherwise. [Note: If the
14159     //   captured entity is a reference to a function, the
14160     //   corresponding data member is also a reference to a
14161     //   function. - end note ]
14162     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14163       if (!RefType->getPointeeType()->isFunctionType())
14164         CaptureType = RefType->getPointeeType();
14165     }
14166
14167     // Forbid the lambda copy-capture of autoreleasing variables.
14168     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14169       if (BuildAndDiagnose) {
14170         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14171         S.Diag(Var->getLocation(), diag::note_previous_decl)
14172           << Var->getDeclName();
14173       }
14174       return false;
14175     }
14176
14177     // Make sure that by-copy captures are of a complete and non-abstract type.
14178     if (BuildAndDiagnose) {
14179       if (!CaptureType->isDependentType() &&
14180           S.RequireCompleteType(Loc, CaptureType,
14181                                 diag::err_capture_of_incomplete_type,
14182                                 Var->getDeclName()))
14183         return false;
14184
14185       if (S.RequireNonAbstractType(Loc, CaptureType,
14186                                    diag::err_capture_of_abstract_type))
14187         return false;
14188     }
14189   }
14190
14191   // Capture this variable in the lambda.
14192   if (BuildAndDiagnose)
14193     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14194                             RefersToCapturedVariable);
14195     
14196   // Compute the type of a reference to this captured variable.
14197   if (ByRef)
14198     DeclRefType = CaptureType.getNonReferenceType();
14199   else {
14200     // C++ [expr.prim.lambda]p5:
14201     //   The closure type for a lambda-expression has a public inline 
14202     //   function call operator [...]. This function call operator is 
14203     //   declared const (9.3.1) if and only if the lambda-expression's 
14204     //   parameter-declaration-clause is not followed by mutable.
14205     DeclRefType = CaptureType.getNonReferenceType();
14206     if (!LSI->Mutable && !CaptureType->isReferenceType())
14207       DeclRefType.addConst();      
14208   }
14209     
14210   // Add the capture.
14211   if (BuildAndDiagnose)
14212     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
14213                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14214       
14215   return true;
14216 }
14217
14218 bool Sema::tryCaptureVariable(
14219     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14220     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14221     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14222   // An init-capture is notionally from the context surrounding its
14223   // declaration, but its parent DC is the lambda class.
14224   DeclContext *VarDC = Var->getDeclContext();
14225   if (Var->isInitCapture())
14226     VarDC = VarDC->getParent();
14227   
14228   DeclContext *DC = CurContext;
14229   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
14230       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
14231   // We need to sync up the Declaration Context with the
14232   // FunctionScopeIndexToStopAt
14233   if (FunctionScopeIndexToStopAt) {
14234     unsigned FSIndex = FunctionScopes.size() - 1;
14235     while (FSIndex != MaxFunctionScopesIndex) {
14236       DC = getLambdaAwareParentOfDeclContext(DC);
14237       --FSIndex;
14238     }
14239   }
14240
14241   
14242   // If the variable is declared in the current context, there is no need to
14243   // capture it.
14244   if (VarDC == DC) return true;
14245
14246   // Capture global variables if it is required to use private copy of this
14247   // variable.
14248   bool IsGlobal = !Var->hasLocalStorage();
14249   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14250     return true;
14251
14252   // Walk up the stack to determine whether we can capture the variable,
14253   // performing the "simple" checks that don't depend on type. We stop when
14254   // we've either hit the declared scope of the variable or find an existing
14255   // capture of that variable.  We start from the innermost capturing-entity
14256   // (the DC) and ensure that all intervening capturing-entities 
14257   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14258   // declcontext can either capture the variable or have already captured
14259   // the variable.
14260   CaptureType = Var->getType();
14261   DeclRefType = CaptureType.getNonReferenceType();
14262   bool Nested = false;
14263   bool Explicit = (Kind != TryCapture_Implicit);
14264   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14265   do {
14266     // Only block literals, captured statements, and lambda expressions can
14267     // capture; other scopes don't work.
14268     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
14269                                                               ExprLoc, 
14270                                                               BuildAndDiagnose,
14271                                                               *this);
14272     // We need to check for the parent *first* because, if we *have*
14273     // private-captured a global variable, we need to recursively capture it in
14274     // intermediate blocks, lambdas, etc.
14275     if (!ParentDC) {
14276       if (IsGlobal) {
14277         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14278         break;
14279       }
14280       return true;
14281     }
14282
14283     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14284     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14285
14286
14287     // Check whether we've already captured it.
14288     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
14289                                              DeclRefType)) {
14290       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14291       break;
14292     }
14293     // If we are instantiating a generic lambda call operator body, 
14294     // we do not want to capture new variables.  What was captured
14295     // during either a lambdas transformation or initial parsing
14296     // should be used. 
14297     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14298       if (BuildAndDiagnose) {
14299         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
14300         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14301           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14302           Diag(Var->getLocation(), diag::note_previous_decl) 
14303              << Var->getDeclName();
14304           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
14305         } else
14306           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14307       }
14308       return true;
14309     }
14310     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
14311     // certain types of variables (unnamed, variably modified types etc.)
14312     // so check for eligibility.
14313     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14314        return true;
14315
14316     // Try to capture variable-length arrays types.
14317     if (Var->getType()->isVariablyModifiedType()) {
14318       // We're going to walk down into the type and look for VLA
14319       // expressions.
14320       QualType QTy = Var->getType();
14321       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14322         QTy = PVD->getOriginalType();
14323       captureVariablyModifiedType(Context, QTy, CSI);
14324     }
14325
14326     if (getLangOpts().OpenMP) {
14327       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14328         // OpenMP private variables should not be captured in outer scope, so
14329         // just break here. Similarly, global variables that are captured in a
14330         // target region should not be captured outside the scope of the region.
14331         if (RSI->CapRegionKind == CR_OpenMP) {
14332           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14333           // When we detect target captures we are looking from inside the
14334           // target region, therefore we need to propagate the capture from the
14335           // enclosing region. Therefore, the capture is not initially nested.
14336           if (IsTargetCap)
14337             FunctionScopesIndex--;
14338
14339           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14340             Nested = !IsTargetCap;
14341             DeclRefType = DeclRefType.getUnqualifiedType();
14342             CaptureType = Context.getLValueReferenceType(DeclRefType);
14343             break;
14344           }
14345         }
14346       }
14347     }
14348     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14349       // No capture-default, and this is not an explicit capture 
14350       // so cannot capture this variable.  
14351       if (BuildAndDiagnose) {
14352         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14353         Diag(Var->getLocation(), diag::note_previous_decl) 
14354           << Var->getDeclName();
14355         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14356           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14357                diag::note_lambda_decl);
14358         // FIXME: If we error out because an outer lambda can not implicitly
14359         // capture a variable that an inner lambda explicitly captures, we
14360         // should have the inner lambda do the explicit capture - because
14361         // it makes for cleaner diagnostics later.  This would purely be done
14362         // so that the diagnostic does not misleadingly claim that a variable 
14363         // can not be captured by a lambda implicitly even though it is captured 
14364         // explicitly.  Suggestion:
14365         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
14366         //    at the function head
14367         //  - cache the StartingDeclContext - this must be a lambda 
14368         //  - captureInLambda in the innermost lambda the variable.
14369       }
14370       return true;
14371     }
14372
14373     FunctionScopesIndex--;
14374     DC = ParentDC;
14375     Explicit = false;
14376   } while (!VarDC->Equals(DC));
14377
14378   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14379   // computing the type of the capture at each step, checking type-specific 
14380   // requirements, and adding captures if requested. 
14381   // If the variable had already been captured previously, we start capturing 
14382   // at the lambda nested within that one.   
14383   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
14384        ++I) {
14385     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14386     
14387     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14388       if (!captureInBlock(BSI, Var, ExprLoc, 
14389                           BuildAndDiagnose, CaptureType, 
14390                           DeclRefType, Nested, *this))
14391         return true;
14392       Nested = true;
14393     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14394       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
14395                                    BuildAndDiagnose, CaptureType, 
14396                                    DeclRefType, Nested, *this))
14397         return true;
14398       Nested = true;
14399     } else {
14400       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14401       if (!captureInLambda(LSI, Var, ExprLoc, 
14402                            BuildAndDiagnose, CaptureType, 
14403                            DeclRefType, Nested, Kind, EllipsisLoc, 
14404                             /*IsTopScope*/I == N - 1, *this))
14405         return true;
14406       Nested = true;
14407     }
14408   }
14409   return false;
14410 }
14411
14412 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14413                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
14414   QualType CaptureType;
14415   QualType DeclRefType;
14416   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14417                             /*BuildAndDiagnose=*/true, CaptureType,
14418                             DeclRefType, nullptr);
14419 }
14420
14421 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14422   QualType CaptureType;
14423   QualType DeclRefType;
14424   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14425                              /*BuildAndDiagnose=*/false, CaptureType,
14426                              DeclRefType, nullptr);
14427 }
14428
14429 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14430   QualType CaptureType;
14431   QualType DeclRefType;
14432   
14433   // Determine whether we can capture this variable.
14434   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14435                          /*BuildAndDiagnose=*/false, CaptureType, 
14436                          DeclRefType, nullptr))
14437     return QualType();
14438
14439   return DeclRefType;
14440 }
14441
14442
14443
14444 // If either the type of the variable or the initializer is dependent, 
14445 // return false. Otherwise, determine whether the variable is a constant
14446 // expression. Use this if you need to know if a variable that might or
14447 // might not be dependent is truly a constant expression.
14448 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
14449     ASTContext &Context) {
14450  
14451   if (Var->getType()->isDependentType()) 
14452     return false;
14453   const VarDecl *DefVD = nullptr;
14454   Var->getAnyInitializer(DefVD);
14455   if (!DefVD) 
14456     return false;
14457   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14458   Expr *Init = cast<Expr>(Eval->Value);
14459   if (Init->isValueDependent()) 
14460     return false;
14461   return IsVariableAConstantExpression(Var, Context); 
14462 }
14463
14464
14465 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14466   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
14467   // an object that satisfies the requirements for appearing in a
14468   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14469   // is immediately applied."  This function handles the lvalue-to-rvalue
14470   // conversion part.
14471   MaybeODRUseExprs.erase(E->IgnoreParens());
14472   
14473   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14474   // to a variable that is a constant expression, and if so, identify it as
14475   // a reference to a variable that does not involve an odr-use of that 
14476   // variable. 
14477   if (LambdaScopeInfo *LSI = getCurLambda()) {
14478     Expr *SansParensExpr = E->IgnoreParens();
14479     VarDecl *Var = nullptr;
14480     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
14481       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14482     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14483       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14484     
14485     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
14486       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
14487   }
14488 }
14489
14490 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14491   Res = CorrectDelayedTyposInExpr(Res);
14492
14493   if (!Res.isUsable())
14494     return Res;
14495
14496   // If a constant-expression is a reference to a variable where we delay
14497   // deciding whether it is an odr-use, just assume we will apply the
14498   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14499   // (a non-type template argument), we have special handling anyway.
14500   UpdateMarkingForLValueToRValue(Res.get());
14501   return Res;
14502 }
14503
14504 void Sema::CleanupVarDeclMarking() {
14505   for (Expr *E : MaybeODRUseExprs) {
14506     VarDecl *Var;
14507     SourceLocation Loc;
14508     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14509       Var = cast<VarDecl>(DRE->getDecl());
14510       Loc = DRE->getLocation();
14511     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14512       Var = cast<VarDecl>(ME->getMemberDecl());
14513       Loc = ME->getMemberLoc();
14514     } else {
14515       llvm_unreachable("Unexpected expression");
14516     }
14517
14518     MarkVarDeclODRUsed(Var, Loc, *this,
14519                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14520   }
14521
14522   MaybeODRUseExprs.clear();
14523 }
14524
14525
14526 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14527                                     VarDecl *Var, Expr *E) {
14528   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14529          "Invalid Expr argument to DoMarkVarDeclReferenced");
14530   Var->setReferenced();
14531
14532   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14533
14534   bool OdrUseContext = isOdrUseContext(SemaRef);
14535   bool NeedDefinition =
14536       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14537                         Var->isUsableInConstantExpressions(SemaRef.Context));
14538
14539   VarTemplateSpecializationDecl *VarSpec =
14540       dyn_cast<VarTemplateSpecializationDecl>(Var);
14541   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14542          "Can't instantiate a partial template specialization.");
14543
14544   // If this might be a member specialization of a static data member, check
14545   // the specialization is visible. We already did the checks for variable
14546   // template specializations when we created them.
14547   if (NeedDefinition && TSK != TSK_Undeclared &&
14548       !isa<VarTemplateSpecializationDecl>(Var))
14549     SemaRef.checkSpecializationVisibility(Loc, Var);
14550
14551   // Perform implicit instantiation of static data members, static data member
14552   // templates of class templates, and variable template specializations. Delay
14553   // instantiations of variable templates, except for those that could be used
14554   // in a constant expression.
14555   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14556     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14557
14558     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14559       if (Var->getPointOfInstantiation().isInvalid()) {
14560         // This is a modification of an existing AST node. Notify listeners.
14561         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14562           L->StaticDataMemberInstantiated(Var);
14563       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14564         // Don't bother trying to instantiate it again, unless we might need
14565         // its initializer before we get to the end of the TU.
14566         TryInstantiating = false;
14567     }
14568
14569     if (Var->getPointOfInstantiation().isInvalid())
14570       Var->setTemplateSpecializationKind(TSK, Loc);
14571
14572     if (TryInstantiating) {
14573       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14574       bool InstantiationDependent = false;
14575       bool IsNonDependent =
14576           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14577                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14578                   : true;
14579
14580       // Do not instantiate specializations that are still type-dependent.
14581       if (IsNonDependent) {
14582         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14583           // Do not defer instantiations of variables which could be used in a
14584           // constant expression.
14585           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14586         } else {
14587           SemaRef.PendingInstantiations
14588               .push_back(std::make_pair(Var, PointOfInstantiation));
14589         }
14590       }
14591     }
14592   }
14593
14594   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14595   // the requirements for appearing in a constant expression (5.19) and, if
14596   // it is an object, the lvalue-to-rvalue conversion (4.1)
14597   // is immediately applied."  We check the first part here, and
14598   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14599   // Note that we use the C++11 definition everywhere because nothing in
14600   // C++03 depends on whether we get the C++03 version correct. The second
14601   // part does not apply to references, since they are not objects.
14602   if (OdrUseContext && E &&
14603       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14604     // A reference initialized by a constant expression can never be
14605     // odr-used, so simply ignore it.
14606     if (!Var->getType()->isReferenceType())
14607       SemaRef.MaybeODRUseExprs.insert(E);
14608   } else if (OdrUseContext) {
14609     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14610                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14611   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14612     // If this is a dependent context, we don't need to mark variables as
14613     // odr-used, but we may still need to track them for lambda capture.
14614     // FIXME: Do we also need to do this inside dependent typeid expressions
14615     // (which are modeled as unevaluated at this point)?
14616     const bool RefersToEnclosingScope =
14617         (SemaRef.CurContext != Var->getDeclContext() &&
14618          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14619     if (RefersToEnclosingScope) {
14620       LambdaScopeInfo *const LSI =
14621           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14622       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14623         // If a variable could potentially be odr-used, defer marking it so
14624         // until we finish analyzing the full expression for any
14625         // lvalue-to-rvalue
14626         // or discarded value conversions that would obviate odr-use.
14627         // Add it to the list of potential captures that will be analyzed
14628         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14629         // unless the variable is a reference that was initialized by a constant
14630         // expression (this will never need to be captured or odr-used).
14631         assert(E && "Capture variable should be used in an expression.");
14632         if (!Var->getType()->isReferenceType() ||
14633             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14634           LSI->addPotentialCapture(E->IgnoreParens());
14635       }
14636     }
14637   }
14638 }
14639
14640 /// \brief Mark a variable referenced, and check whether it is odr-used
14641 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14642 /// used directly for normal expressions referring to VarDecl.
14643 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14644   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14645 }
14646
14647 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14648                                Decl *D, Expr *E, bool MightBeOdrUse) {
14649   if (SemaRef.isInOpenMPDeclareTargetContext())
14650     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14651
14652   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14653     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14654     return;
14655   }
14656
14657   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14658
14659   // If this is a call to a method via a cast, also mark the method in the
14660   // derived class used in case codegen can devirtualize the call.
14661   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14662   if (!ME)
14663     return;
14664   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14665   if (!MD)
14666     return;
14667   // Only attempt to devirtualize if this is truly a virtual call.
14668   bool IsVirtualCall = MD->isVirtual() &&
14669                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14670   if (!IsVirtualCall)
14671     return;
14672   const Expr *Base = ME->getBase();
14673   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14674   if (!MostDerivedClassDecl)
14675     return;
14676   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14677   if (!DM || DM->isPure())
14678     return;
14679   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14680
14681
14682 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14683 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14684   // TODO: update this with DR# once a defect report is filed.
14685   // C++11 defect. The address of a pure member should not be an ODR use, even
14686   // if it's a qualified reference.
14687   bool OdrUse = true;
14688   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14689     if (Method->isVirtual())
14690       OdrUse = false;
14691   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14692 }
14693
14694 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14695 void Sema::MarkMemberReferenced(MemberExpr *E) {
14696   // C++11 [basic.def.odr]p2:
14697   //   A non-overloaded function whose name appears as a potentially-evaluated
14698   //   expression or a member of a set of candidate functions, if selected by
14699   //   overload resolution when referred to from a potentially-evaluated
14700   //   expression, is odr-used, unless it is a pure virtual function and its
14701   //   name is not explicitly qualified.
14702   bool MightBeOdrUse = true;
14703   if (E->performsVirtualDispatch(getLangOpts())) {
14704     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14705       if (Method->isPure())
14706         MightBeOdrUse = false;
14707   }
14708   SourceLocation Loc = E->getMemberLoc().isValid() ?
14709                             E->getMemberLoc() : E->getLocStart();
14710   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14711 }
14712
14713 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14714 /// marks the declaration referenced, and performs odr-use checking for
14715 /// functions and variables. This method should not be used when building a
14716 /// normal expression which refers to a variable.
14717 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14718                                  bool MightBeOdrUse) {
14719   if (MightBeOdrUse) {
14720     if (auto *VD = dyn_cast<VarDecl>(D)) {
14721       MarkVariableReferenced(Loc, VD);
14722       return;
14723     }
14724   }
14725   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14726     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14727     return;
14728   }
14729   D->setReferenced();
14730 }
14731
14732 namespace {
14733   // Mark all of the declarations used by a type as referenced.
14734   // FIXME: Not fully implemented yet! We need to have a better understanding
14735   // of when we're entering a context we should not recurse into.
14736   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14737   // TreeTransforms rebuilding the type in a new context. Rather than
14738   // duplicating the TreeTransform logic, we should consider reusing it here.
14739   // Currently that causes problems when rebuilding LambdaExprs.
14740   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14741     Sema &S;
14742     SourceLocation Loc;
14743
14744   public:
14745     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14746
14747     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14748
14749     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14750   };
14751 }
14752
14753 bool MarkReferencedDecls::TraverseTemplateArgument(
14754     const TemplateArgument &Arg) {
14755   {
14756     // A non-type template argument is a constant-evaluated context.
14757     EnterExpressionEvaluationContext Evaluated(
14758         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14759     if (Arg.getKind() == TemplateArgument::Declaration) {
14760       if (Decl *D = Arg.getAsDecl())
14761         S.MarkAnyDeclReferenced(Loc, D, true);
14762     } else if (Arg.getKind() == TemplateArgument::Expression) {
14763       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14764     }
14765   }
14766
14767   return Inherited::TraverseTemplateArgument(Arg);
14768 }
14769
14770 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14771   MarkReferencedDecls Marker(*this, Loc);
14772   Marker.TraverseType(T);
14773 }
14774
14775 namespace {
14776   /// \brief Helper class that marks all of the declarations referenced by
14777   /// potentially-evaluated subexpressions as "referenced".
14778   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14779     Sema &S;
14780     bool SkipLocalVariables;
14781     
14782   public:
14783     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14784     
14785     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
14786       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14787     
14788     void VisitDeclRefExpr(DeclRefExpr *E) {
14789       // If we were asked not to visit local variables, don't.
14790       if (SkipLocalVariables) {
14791         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14792           if (VD->hasLocalStorage())
14793             return;
14794       }
14795       
14796       S.MarkDeclRefReferenced(E);
14797     }
14798
14799     void VisitMemberExpr(MemberExpr *E) {
14800       S.MarkMemberReferenced(E);
14801       Inherited::VisitMemberExpr(E);
14802     }
14803     
14804     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14805       S.MarkFunctionReferenced(E->getLocStart(),
14806             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14807       Visit(E->getSubExpr());
14808     }
14809     
14810     void VisitCXXNewExpr(CXXNewExpr *E) {
14811       if (E->getOperatorNew())
14812         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14813       if (E->getOperatorDelete())
14814         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14815       Inherited::VisitCXXNewExpr(E);
14816     }
14817
14818     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14819       if (E->getOperatorDelete())
14820         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14821       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14822       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14823         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14824         S.MarkFunctionReferenced(E->getLocStart(), 
14825                                     S.LookupDestructor(Record));
14826       }
14827       
14828       Inherited::VisitCXXDeleteExpr(E);
14829     }
14830     
14831     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14832       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14833       Inherited::VisitCXXConstructExpr(E);
14834     }
14835     
14836     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14837       Visit(E->getExpr());
14838     }
14839
14840     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14841       Inherited::VisitImplicitCastExpr(E);
14842
14843       if (E->getCastKind() == CK_LValueToRValue)
14844         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14845     }
14846   };
14847 }
14848
14849 /// \brief Mark any declarations that appear within this expression or any
14850 /// potentially-evaluated subexpressions as "referenced".
14851 ///
14852 /// \param SkipLocalVariables If true, don't mark local variables as 
14853 /// 'referenced'.
14854 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
14855                                             bool SkipLocalVariables) {
14856   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14857 }
14858
14859 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14860 /// of the program being compiled.
14861 ///
14862 /// This routine emits the given diagnostic when the code currently being
14863 /// type-checked is "potentially evaluated", meaning that there is a
14864 /// possibility that the code will actually be executable. Code in sizeof()
14865 /// expressions, code used only during overload resolution, etc., are not
14866 /// potentially evaluated. This routine will suppress such diagnostics or,
14867 /// in the absolutely nutty case of potentially potentially evaluated
14868 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14869 /// later.
14870 ///
14871 /// This routine should be used for all diagnostics that describe the run-time
14872 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14873 /// Failure to do so will likely result in spurious diagnostics or failures
14874 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14875 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14876                                const PartialDiagnostic &PD) {
14877   switch (ExprEvalContexts.back().Context) {
14878   case ExpressionEvaluationContext::Unevaluated:
14879   case ExpressionEvaluationContext::UnevaluatedList:
14880   case ExpressionEvaluationContext::UnevaluatedAbstract:
14881   case ExpressionEvaluationContext::DiscardedStatement:
14882     // The argument will never be evaluated, so don't complain.
14883     break;
14884
14885   case ExpressionEvaluationContext::ConstantEvaluated:
14886     // Relevant diagnostics should be produced by constant evaluation.
14887     break;
14888
14889   case ExpressionEvaluationContext::PotentiallyEvaluated:
14890   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14891     if (Statement && getCurFunctionOrMethodDecl()) {
14892       FunctionScopes.back()->PossiblyUnreachableDiags.
14893         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14894     }
14895     else
14896       Diag(Loc, PD);
14897       
14898     return true;
14899   }
14900
14901   return false;
14902 }
14903
14904 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14905                                CallExpr *CE, FunctionDecl *FD) {
14906   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14907     return false;
14908
14909   // If we're inside a decltype's expression, don't check for a valid return
14910   // type or construct temporaries until we know whether this is the last call.
14911   if (ExprEvalContexts.back().IsDecltype) {
14912     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14913     return false;
14914   }
14915
14916   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14917     FunctionDecl *FD;
14918     CallExpr *CE;
14919     
14920   public:
14921     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14922       : FD(FD), CE(CE) { }
14923
14924     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14925       if (!FD) {
14926         S.Diag(Loc, diag::err_call_incomplete_return)
14927           << T << CE->getSourceRange();
14928         return;
14929       }
14930       
14931       S.Diag(Loc, diag::err_call_function_incomplete_return)
14932         << CE->getSourceRange() << FD->getDeclName() << T;
14933       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14934           << FD->getDeclName();
14935     }
14936   } Diagnoser(FD, CE);
14937   
14938   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14939     return true;
14940
14941   return false;
14942 }
14943
14944 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14945 // will prevent this condition from triggering, which is what we want.
14946 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14947   SourceLocation Loc;
14948
14949   unsigned diagnostic = diag::warn_condition_is_assignment;
14950   bool IsOrAssign = false;
14951
14952   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14953     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14954       return;
14955
14956     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14957
14958     // Greylist some idioms by putting them into a warning subcategory.
14959     if (ObjCMessageExpr *ME
14960           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14961       Selector Sel = ME->getSelector();
14962
14963       // self = [<foo> init...]
14964       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14965         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14966
14967       // <foo> = [<bar> nextObject]
14968       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14969         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14970     }
14971
14972     Loc = Op->getOperatorLoc();
14973   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14974     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14975       return;
14976
14977     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14978     Loc = Op->getOperatorLoc();
14979   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14980     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14981   else {
14982     // Not an assignment.
14983     return;
14984   }
14985
14986   Diag(Loc, diagnostic) << E->getSourceRange();
14987
14988   SourceLocation Open = E->getLocStart();
14989   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14990   Diag(Loc, diag::note_condition_assign_silence)
14991         << FixItHint::CreateInsertion(Open, "(")
14992         << FixItHint::CreateInsertion(Close, ")");
14993
14994   if (IsOrAssign)
14995     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14996       << FixItHint::CreateReplacement(Loc, "!=");
14997   else
14998     Diag(Loc, diag::note_condition_assign_to_comparison)
14999       << FixItHint::CreateReplacement(Loc, "==");
15000 }
15001
15002 /// \brief Redundant parentheses over an equality comparison can indicate
15003 /// that the user intended an assignment used as condition.
15004 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15005   // Don't warn if the parens came from a macro.
15006   SourceLocation parenLoc = ParenE->getLocStart();
15007   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15008     return;
15009   // Don't warn for dependent expressions.
15010   if (ParenE->isTypeDependent())
15011     return;
15012
15013   Expr *E = ParenE->IgnoreParens();
15014
15015   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15016     if (opE->getOpcode() == BO_EQ &&
15017         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15018                                                            == Expr::MLV_Valid) {
15019       SourceLocation Loc = opE->getOperatorLoc();
15020       
15021       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15022       SourceRange ParenERange = ParenE->getSourceRange();
15023       Diag(Loc, diag::note_equality_comparison_silence)
15024         << FixItHint::CreateRemoval(ParenERange.getBegin())
15025         << FixItHint::CreateRemoval(ParenERange.getEnd());
15026       Diag(Loc, diag::note_equality_comparison_to_assign)
15027         << FixItHint::CreateReplacement(Loc, "=");
15028     }
15029 }
15030
15031 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15032                                        bool IsConstexpr) {
15033   DiagnoseAssignmentAsCondition(E);
15034   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15035     DiagnoseEqualityWithExtraParens(parenE);
15036
15037   ExprResult result = CheckPlaceholderExpr(E);
15038   if (result.isInvalid()) return ExprError();
15039   E = result.get();
15040
15041   if (!E->isTypeDependent()) {
15042     if (getLangOpts().CPlusPlus)
15043       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15044
15045     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15046     if (ERes.isInvalid())
15047       return ExprError();
15048     E = ERes.get();
15049
15050     QualType T = E->getType();
15051     if (!T->isScalarType()) { // C99 6.8.4.1p1
15052       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15053         << T << E->getSourceRange();
15054       return ExprError();
15055     }
15056     CheckBoolLikeConversion(E, Loc);
15057   }
15058
15059   return E;
15060 }
15061
15062 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15063                                            Expr *SubExpr, ConditionKind CK) {
15064   // Empty conditions are valid in for-statements.
15065   if (!SubExpr)
15066     return ConditionResult();
15067
15068   ExprResult Cond;
15069   switch (CK) {
15070   case ConditionKind::Boolean:
15071     Cond = CheckBooleanCondition(Loc, SubExpr);
15072     break;
15073
15074   case ConditionKind::ConstexprIf:
15075     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15076     break;
15077
15078   case ConditionKind::Switch:
15079     Cond = CheckSwitchCondition(Loc, SubExpr);
15080     break;
15081   }
15082   if (Cond.isInvalid())
15083     return ConditionError();
15084
15085   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15086   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15087   if (!FullExpr.get())
15088     return ConditionError();
15089
15090   return ConditionResult(*this, nullptr, FullExpr,
15091                          CK == ConditionKind::ConstexprIf);
15092 }
15093
15094 namespace {
15095   /// A visitor for rebuilding a call to an __unknown_any expression
15096   /// to have an appropriate type.
15097   struct RebuildUnknownAnyFunction
15098     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15099
15100     Sema &S;
15101
15102     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15103
15104     ExprResult VisitStmt(Stmt *S) {
15105       llvm_unreachable("unexpected statement!");
15106     }
15107
15108     ExprResult VisitExpr(Expr *E) {
15109       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15110         << E->getSourceRange();
15111       return ExprError();
15112     }
15113
15114     /// Rebuild an expression which simply semantically wraps another
15115     /// expression which it shares the type and value kind of.
15116     template <class T> ExprResult rebuildSugarExpr(T *E) {
15117       ExprResult SubResult = Visit(E->getSubExpr());
15118       if (SubResult.isInvalid()) return ExprError();
15119
15120       Expr *SubExpr = SubResult.get();
15121       E->setSubExpr(SubExpr);
15122       E->setType(SubExpr->getType());
15123       E->setValueKind(SubExpr->getValueKind());
15124       assert(E->getObjectKind() == OK_Ordinary);
15125       return E;
15126     }
15127
15128     ExprResult VisitParenExpr(ParenExpr *E) {
15129       return rebuildSugarExpr(E);
15130     }
15131
15132     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15133       return rebuildSugarExpr(E);
15134     }
15135
15136     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15137       ExprResult SubResult = Visit(E->getSubExpr());
15138       if (SubResult.isInvalid()) return ExprError();
15139
15140       Expr *SubExpr = SubResult.get();
15141       E->setSubExpr(SubExpr);
15142       E->setType(S.Context.getPointerType(SubExpr->getType()));
15143       assert(E->getValueKind() == VK_RValue);
15144       assert(E->getObjectKind() == OK_Ordinary);
15145       return E;
15146     }
15147
15148     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15149       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15150
15151       E->setType(VD->getType());
15152
15153       assert(E->getValueKind() == VK_RValue);
15154       if (S.getLangOpts().CPlusPlus &&
15155           !(isa<CXXMethodDecl>(VD) &&
15156             cast<CXXMethodDecl>(VD)->isInstance()))
15157         E->setValueKind(VK_LValue);
15158
15159       return E;
15160     }
15161
15162     ExprResult VisitMemberExpr(MemberExpr *E) {
15163       return resolveDecl(E, E->getMemberDecl());
15164     }
15165
15166     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15167       return resolveDecl(E, E->getDecl());
15168     }
15169   };
15170 }
15171
15172 /// Given a function expression of unknown-any type, try to rebuild it
15173 /// to have a function type.
15174 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15175   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15176   if (Result.isInvalid()) return ExprError();
15177   return S.DefaultFunctionArrayConversion(Result.get());
15178 }
15179
15180 namespace {
15181   /// A visitor for rebuilding an expression of type __unknown_anytype
15182   /// into one which resolves the type directly on the referring
15183   /// expression.  Strict preservation of the original source
15184   /// structure is not a goal.
15185   struct RebuildUnknownAnyExpr
15186     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15187
15188     Sema &S;
15189
15190     /// The current destination type.
15191     QualType DestType;
15192
15193     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15194       : S(S), DestType(CastType) {}
15195
15196     ExprResult VisitStmt(Stmt *S) {
15197       llvm_unreachable("unexpected statement!");
15198     }
15199
15200     ExprResult VisitExpr(Expr *E) {
15201       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15202         << E->getSourceRange();
15203       return ExprError();
15204     }
15205
15206     ExprResult VisitCallExpr(CallExpr *E);
15207     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15208
15209     /// Rebuild an expression which simply semantically wraps another
15210     /// expression which it shares the type and value kind of.
15211     template <class T> ExprResult rebuildSugarExpr(T *E) {
15212       ExprResult SubResult = Visit(E->getSubExpr());
15213       if (SubResult.isInvalid()) return ExprError();
15214       Expr *SubExpr = SubResult.get();
15215       E->setSubExpr(SubExpr);
15216       E->setType(SubExpr->getType());
15217       E->setValueKind(SubExpr->getValueKind());
15218       assert(E->getObjectKind() == OK_Ordinary);
15219       return E;
15220     }
15221
15222     ExprResult VisitParenExpr(ParenExpr *E) {
15223       return rebuildSugarExpr(E);
15224     }
15225
15226     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15227       return rebuildSugarExpr(E);
15228     }
15229
15230     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15231       const PointerType *Ptr = DestType->getAs<PointerType>();
15232       if (!Ptr) {
15233         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15234           << E->getSourceRange();
15235         return ExprError();
15236       }
15237
15238       if (isa<CallExpr>(E->getSubExpr())) {
15239         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15240           << E->getSourceRange();
15241         return ExprError();
15242       }
15243
15244       assert(E->getValueKind() == VK_RValue);
15245       assert(E->getObjectKind() == OK_Ordinary);
15246       E->setType(DestType);
15247
15248       // Build the sub-expression as if it were an object of the pointee type.
15249       DestType = Ptr->getPointeeType();
15250       ExprResult SubResult = Visit(E->getSubExpr());
15251       if (SubResult.isInvalid()) return ExprError();
15252       E->setSubExpr(SubResult.get());
15253       return E;
15254     }
15255
15256     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15257
15258     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15259
15260     ExprResult VisitMemberExpr(MemberExpr *E) {
15261       return resolveDecl(E, E->getMemberDecl());
15262     }
15263
15264     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15265       return resolveDecl(E, E->getDecl());
15266     }
15267   };
15268 }
15269
15270 /// Rebuilds a call expression which yielded __unknown_anytype.
15271 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15272   Expr *CalleeExpr = E->getCallee();
15273
15274   enum FnKind {
15275     FK_MemberFunction,
15276     FK_FunctionPointer,
15277     FK_BlockPointer
15278   };
15279
15280   FnKind Kind;
15281   QualType CalleeType = CalleeExpr->getType();
15282   if (CalleeType == S.Context.BoundMemberTy) {
15283     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15284     Kind = FK_MemberFunction;
15285     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15286   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15287     CalleeType = Ptr->getPointeeType();
15288     Kind = FK_FunctionPointer;
15289   } else {
15290     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15291     Kind = FK_BlockPointer;
15292   }
15293   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15294
15295   // Verify that this is a legal result type of a function.
15296   if (DestType->isArrayType() || DestType->isFunctionType()) {
15297     unsigned diagID = diag::err_func_returning_array_function;
15298     if (Kind == FK_BlockPointer)
15299       diagID = diag::err_block_returning_array_function;
15300
15301     S.Diag(E->getExprLoc(), diagID)
15302       << DestType->isFunctionType() << DestType;
15303     return ExprError();
15304   }
15305
15306   // Otherwise, go ahead and set DestType as the call's result.
15307   E->setType(DestType.getNonLValueExprType(S.Context));
15308   E->setValueKind(Expr::getValueKindForType(DestType));
15309   assert(E->getObjectKind() == OK_Ordinary);
15310
15311   // Rebuild the function type, replacing the result type with DestType.
15312   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15313   if (Proto) {
15314     // __unknown_anytype(...) is a special case used by the debugger when
15315     // it has no idea what a function's signature is.
15316     //
15317     // We want to build this call essentially under the K&R
15318     // unprototyped rules, but making a FunctionNoProtoType in C++
15319     // would foul up all sorts of assumptions.  However, we cannot
15320     // simply pass all arguments as variadic arguments, nor can we
15321     // portably just call the function under a non-variadic type; see
15322     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15323     // However, it turns out that in practice it is generally safe to
15324     // call a function declared as "A foo(B,C,D);" under the prototype
15325     // "A foo(B,C,D,...);".  The only known exception is with the
15326     // Windows ABI, where any variadic function is implicitly cdecl
15327     // regardless of its normal CC.  Therefore we change the parameter
15328     // types to match the types of the arguments.
15329     //
15330     // This is a hack, but it is far superior to moving the
15331     // corresponding target-specific code from IR-gen to Sema/AST.
15332
15333     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15334     SmallVector<QualType, 8> ArgTypes;
15335     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15336       ArgTypes.reserve(E->getNumArgs());
15337       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15338         Expr *Arg = E->getArg(i);
15339         QualType ArgType = Arg->getType();
15340         if (E->isLValue()) {
15341           ArgType = S.Context.getLValueReferenceType(ArgType);
15342         } else if (E->isXValue()) {
15343           ArgType = S.Context.getRValueReferenceType(ArgType);
15344         }
15345         ArgTypes.push_back(ArgType);
15346       }
15347       ParamTypes = ArgTypes;
15348     }
15349     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15350                                          Proto->getExtProtoInfo());
15351   } else {
15352     DestType = S.Context.getFunctionNoProtoType(DestType,
15353                                                 FnType->getExtInfo());
15354   }
15355
15356   // Rebuild the appropriate pointer-to-function type.
15357   switch (Kind) { 
15358   case FK_MemberFunction:
15359     // Nothing to do.
15360     break;
15361
15362   case FK_FunctionPointer:
15363     DestType = S.Context.getPointerType(DestType);
15364     break;
15365
15366   case FK_BlockPointer:
15367     DestType = S.Context.getBlockPointerType(DestType);
15368     break;
15369   }
15370
15371   // Finally, we can recurse.
15372   ExprResult CalleeResult = Visit(CalleeExpr);
15373   if (!CalleeResult.isUsable()) return ExprError();
15374   E->setCallee(CalleeResult.get());
15375
15376   // Bind a temporary if necessary.
15377   return S.MaybeBindToTemporary(E);
15378 }
15379
15380 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15381   // Verify that this is a legal result type of a call.
15382   if (DestType->isArrayType() || DestType->isFunctionType()) {
15383     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15384       << DestType->isFunctionType() << DestType;
15385     return ExprError();
15386   }
15387
15388   // Rewrite the method result type if available.
15389   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15390     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15391     Method->setReturnType(DestType);
15392   }
15393
15394   // Change the type of the message.
15395   E->setType(DestType.getNonReferenceType());
15396   E->setValueKind(Expr::getValueKindForType(DestType));
15397
15398   return S.MaybeBindToTemporary(E);
15399 }
15400
15401 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15402   // The only case we should ever see here is a function-to-pointer decay.
15403   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15404     assert(E->getValueKind() == VK_RValue);
15405     assert(E->getObjectKind() == OK_Ordinary);
15406   
15407     E->setType(DestType);
15408   
15409     // Rebuild the sub-expression as the pointee (function) type.
15410     DestType = DestType->castAs<PointerType>()->getPointeeType();
15411   
15412     ExprResult Result = Visit(E->getSubExpr());
15413     if (!Result.isUsable()) return ExprError();
15414   
15415     E->setSubExpr(Result.get());
15416     return E;
15417   } else if (E->getCastKind() == CK_LValueToRValue) {
15418     assert(E->getValueKind() == VK_RValue);
15419     assert(E->getObjectKind() == OK_Ordinary);
15420
15421     assert(isa<BlockPointerType>(E->getType()));
15422
15423     E->setType(DestType);
15424
15425     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15426     DestType = S.Context.getLValueReferenceType(DestType);
15427
15428     ExprResult Result = Visit(E->getSubExpr());
15429     if (!Result.isUsable()) return ExprError();
15430
15431     E->setSubExpr(Result.get());
15432     return E;
15433   } else {
15434     llvm_unreachable("Unhandled cast type!");
15435   }
15436 }
15437
15438 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15439   ExprValueKind ValueKind = VK_LValue;
15440   QualType Type = DestType;
15441
15442   // We know how to make this work for certain kinds of decls:
15443
15444   //  - functions
15445   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15446     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15447       DestType = Ptr->getPointeeType();
15448       ExprResult Result = resolveDecl(E, VD);
15449       if (Result.isInvalid()) return ExprError();
15450       return S.ImpCastExprToType(Result.get(), Type,
15451                                  CK_FunctionToPointerDecay, VK_RValue);
15452     }
15453
15454     if (!Type->isFunctionType()) {
15455       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15456         << VD << E->getSourceRange();
15457       return ExprError();
15458     }
15459     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15460       // We must match the FunctionDecl's type to the hack introduced in
15461       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15462       // type. See the lengthy commentary in that routine.
15463       QualType FDT = FD->getType();
15464       const FunctionType *FnType = FDT->castAs<FunctionType>();
15465       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15466       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15467       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15468         SourceLocation Loc = FD->getLocation();
15469         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15470                                       FD->getDeclContext(),
15471                                       Loc, Loc, FD->getNameInfo().getName(),
15472                                       DestType, FD->getTypeSourceInfo(),
15473                                       SC_None, false/*isInlineSpecified*/,
15474                                       FD->hasPrototype(),
15475                                       false/*isConstexprSpecified*/);
15476           
15477         if (FD->getQualifier())
15478           NewFD->setQualifierInfo(FD->getQualifierLoc());
15479
15480         SmallVector<ParmVarDecl*, 16> Params;
15481         for (const auto &AI : FT->param_types()) {
15482           ParmVarDecl *Param =
15483             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15484           Param->setScopeInfo(0, Params.size());
15485           Params.push_back(Param);
15486         }
15487         NewFD->setParams(Params);
15488         DRE->setDecl(NewFD);
15489         VD = DRE->getDecl();
15490       }
15491     }
15492
15493     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15494       if (MD->isInstance()) {
15495         ValueKind = VK_RValue;
15496         Type = S.Context.BoundMemberTy;
15497       }
15498
15499     // Function references aren't l-values in C.
15500     if (!S.getLangOpts().CPlusPlus)
15501       ValueKind = VK_RValue;
15502
15503   //  - variables
15504   } else if (isa<VarDecl>(VD)) {
15505     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15506       Type = RefTy->getPointeeType();
15507     } else if (Type->isFunctionType()) {
15508       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15509         << VD << E->getSourceRange();
15510       return ExprError();
15511     }
15512
15513   //  - nothing else
15514   } else {
15515     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15516       << VD << E->getSourceRange();
15517     return ExprError();
15518   }
15519
15520   // Modifying the declaration like this is friendly to IR-gen but
15521   // also really dangerous.
15522   VD->setType(DestType);
15523   E->setType(Type);
15524   E->setValueKind(ValueKind);
15525   return E;
15526 }
15527
15528 /// Check a cast of an unknown-any type.  We intentionally only
15529 /// trigger this for C-style casts.
15530 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15531                                      Expr *CastExpr, CastKind &CastKind,
15532                                      ExprValueKind &VK, CXXCastPath &Path) {
15533   // The type we're casting to must be either void or complete.
15534   if (!CastType->isVoidType() &&
15535       RequireCompleteType(TypeRange.getBegin(), CastType,
15536                           diag::err_typecheck_cast_to_incomplete))
15537     return ExprError();
15538
15539   // Rewrite the casted expression from scratch.
15540   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15541   if (!result.isUsable()) return ExprError();
15542
15543   CastExpr = result.get();
15544   VK = CastExpr->getValueKind();
15545   CastKind = CK_NoOp;
15546
15547   return CastExpr;
15548 }
15549
15550 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15551   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15552 }
15553
15554 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15555                                     Expr *arg, QualType &paramType) {
15556   // If the syntactic form of the argument is not an explicit cast of
15557   // any sort, just do default argument promotion.
15558   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15559   if (!castArg) {
15560     ExprResult result = DefaultArgumentPromotion(arg);
15561     if (result.isInvalid()) return ExprError();
15562     paramType = result.get()->getType();
15563     return result;
15564   }
15565
15566   // Otherwise, use the type that was written in the explicit cast.
15567   assert(!arg->hasPlaceholderType());
15568   paramType = castArg->getTypeAsWritten();
15569
15570   // Copy-initialize a parameter of that type.
15571   InitializedEntity entity =
15572     InitializedEntity::InitializeParameter(Context, paramType,
15573                                            /*consumed*/ false);
15574   return PerformCopyInitialization(entity, callLoc, arg);
15575 }
15576
15577 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15578   Expr *orig = E;
15579   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15580   while (true) {
15581     E = E->IgnoreParenImpCasts();
15582     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15583       E = call->getCallee();
15584       diagID = diag::err_uncasted_call_of_unknown_any;
15585     } else {
15586       break;
15587     }
15588   }
15589
15590   SourceLocation loc;
15591   NamedDecl *d;
15592   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15593     loc = ref->getLocation();
15594     d = ref->getDecl();
15595   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15596     loc = mem->getMemberLoc();
15597     d = mem->getMemberDecl();
15598   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15599     diagID = diag::err_uncasted_call_of_unknown_any;
15600     loc = msg->getSelectorStartLoc();
15601     d = msg->getMethodDecl();
15602     if (!d) {
15603       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15604         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15605         << orig->getSourceRange();
15606       return ExprError();
15607     }
15608   } else {
15609     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15610       << E->getSourceRange();
15611     return ExprError();
15612   }
15613
15614   S.Diag(loc, diagID) << d << orig->getSourceRange();
15615
15616   // Never recoverable.
15617   return ExprError();
15618 }
15619
15620 /// Check for operands with placeholder types and complain if found.
15621 /// Returns ExprError() if there was an error and no recovery was possible.
15622 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15623   if (!getLangOpts().CPlusPlus) {
15624     // C cannot handle TypoExpr nodes on either side of a binop because it
15625     // doesn't handle dependent types properly, so make sure any TypoExprs have
15626     // been dealt with before checking the operands.
15627     ExprResult Result = CorrectDelayedTyposInExpr(E);
15628     if (!Result.isUsable()) return ExprError();
15629     E = Result.get();
15630   }
15631
15632   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15633   if (!placeholderType) return E;
15634
15635   switch (placeholderType->getKind()) {
15636
15637   // Overloaded expressions.
15638   case BuiltinType::Overload: {
15639     // Try to resolve a single function template specialization.
15640     // This is obligatory.
15641     ExprResult Result = E;
15642     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15643       return Result;
15644
15645     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15646     // leaves Result unchanged on failure.
15647     Result = E;
15648     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15649       return Result;
15650
15651     // If that failed, try to recover with a call.
15652     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15653                          /*complain*/ true);
15654     return Result;
15655   }
15656
15657   // Bound member functions.
15658   case BuiltinType::BoundMember: {
15659     ExprResult result = E;
15660     const Expr *BME = E->IgnoreParens();
15661     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15662     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15663     if (isa<CXXPseudoDestructorExpr>(BME)) {
15664       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15665     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15666       if (ME->getMemberNameInfo().getName().getNameKind() ==
15667           DeclarationName::CXXDestructorName)
15668         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15669     }
15670     tryToRecoverWithCall(result, PD,
15671                          /*complain*/ true);
15672     return result;
15673   }
15674
15675   // ARC unbridged casts.
15676   case BuiltinType::ARCUnbridgedCast: {
15677     Expr *realCast = stripARCUnbridgedCast(E);
15678     diagnoseARCUnbridgedCast(realCast);
15679     return realCast;
15680   }
15681
15682   // Expressions of unknown type.
15683   case BuiltinType::UnknownAny:
15684     return diagnoseUnknownAnyExpr(*this, E);
15685
15686   // Pseudo-objects.
15687   case BuiltinType::PseudoObject:
15688     return checkPseudoObjectRValue(E);
15689
15690   case BuiltinType::BuiltinFn: {
15691     // Accept __noop without parens by implicitly converting it to a call expr.
15692     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15693     if (DRE) {
15694       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15695       if (FD->getBuiltinID() == Builtin::BI__noop) {
15696         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15697                               CK_BuiltinFnToFnPtr).get();
15698         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15699                                       VK_RValue, SourceLocation());
15700       }
15701     }
15702
15703     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15704     return ExprError();
15705   }
15706
15707   // Expressions of unknown type.
15708   case BuiltinType::OMPArraySection:
15709     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15710     return ExprError();
15711
15712   // Everything else should be impossible.
15713 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15714   case BuiltinType::Id:
15715 #include "clang/Basic/OpenCLImageTypes.def"
15716 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15717 #define PLACEHOLDER_TYPE(Id, SingletonId)
15718 #include "clang/AST/BuiltinTypes.def"
15719     break;
15720   }
15721
15722   llvm_unreachable("invalid placeholder type!");
15723 }
15724
15725 bool Sema::CheckCaseExpression(Expr *E) {
15726   if (E->isTypeDependent())
15727     return true;
15728   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15729     return E->getType()->isIntegralOrEnumerationType();
15730   return false;
15731 }
15732
15733 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15734 ExprResult
15735 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15736   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15737          "Unknown Objective-C Boolean value!");
15738   QualType BoolT = Context.ObjCBuiltinBoolTy;
15739   if (!Context.getBOOLDecl()) {
15740     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15741                         Sema::LookupOrdinaryName);
15742     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15743       NamedDecl *ND = Result.getFoundDecl();
15744       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
15745         Context.setBOOLDecl(TD);
15746     }
15747   }
15748   if (Context.getBOOLDecl())
15749     BoolT = Context.getBOOLType();
15750   return new (Context)
15751       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15752 }
15753
15754 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15755     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15756     SourceLocation RParen) {
15757
15758   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15759
15760   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15761                            [&](const AvailabilitySpec &Spec) {
15762                              return Spec.getPlatform() == Platform;
15763                            });
15764
15765   VersionTuple Version;
15766   if (Spec != AvailSpecs.end())
15767     Version = Spec->getVersion();
15768
15769   // The use of `@available` in the enclosing function should be analyzed to
15770   // warn when it's used inappropriately (i.e. not if(@available)).
15771   if (getCurFunctionOrMethodDecl())
15772     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
15773   else if (getCurBlock() || getCurLambda())
15774     getCurFunction()->HasPotentialAvailabilityViolations = true;
15775
15776   return new (Context)
15777       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15778 }