]> granicus.if.org Git - clang/blob - lib/Sema/SemaExpr.cpp
P0012R1: Make exception specifications be part of the type system. This
[clang] / lib / Sema / SemaExpr.cpp
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73
74   return true;
75 }
76
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message);
109
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message);
117         continue;
118       }
119     }
120     break;
121   }
122
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message);
128     }
129   }
130
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message);
136     }
137
138   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161
162   return Result;
163 }
164
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173
174     if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
175       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
176       return;
177     }
178
179     const ObjCPropertyDecl *ObjCPDecl = nullptr;
180     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183         if (PDeclResult == Result)
184           ObjCPDecl = PD;
185       }
186     }
187
188     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189                               ObjCPDecl, ObjCPropertyAccess);
190   }
191 }
192
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195   assert(Decl->isDeleted());
196
197   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
198
199   if (Method && Method->isDeleted() && Method->isDefaulted()) {
200     // If the method was explicitly defaulted, point at that declaration.
201     if (!Method->isImplicit())
202       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
203
204     // Try to diagnose why this special member function was implicitly
205     // deleted. This might fail, if that reason no longer applies.
206     CXXSpecialMember CSM = getSpecialMember(Method);
207     if (CSM != CXXInvalid)
208       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
209
210     return;
211   }
212
213   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214   if (Ctor && Ctor->isInheritingConstructor())
215     return NoteDeletedInheritingConstructor(Ctor);
216
217   Diag(Decl->getLocation(), diag::note_availability_specified_here)
218     << Decl << true;
219 }
220
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224   for (auto I : D->redecls()) {
225     if (I->getStorageClass() != SC_None)
226       return true;
227   }
228   return false;
229 }
230
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
233 ///
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
240                                                       const NamedDecl *D,
241                                                       SourceLocation Loc) {
242   // This is disabled under C++; there are too many ways for this to fire in
243   // contexts where the warning is a false positive, or where it is technically
244   // correct but benign.
245   if (S.getLangOpts().CPlusPlus)
246     return;
247
248   // Check if this is an inlined function or method.
249   FunctionDecl *Current = S.getCurFunctionDecl();
250   if (!Current)
251     return;
252   if (!Current->isInlined())
253     return;
254   if (!Current->isExternallyVisible())
255     return;
256
257   // Check if the decl has internal linkage.
258   if (D->getFormalLinkage() != InternalLinkage)
259     return;
260
261   // Downgrade from ExtWarn to Extension if
262   //  (1) the supposedly external inline function is in the main file,
263   //      and probably won't be included anywhere else.
264   //  (2) the thing we're referencing is a pure function.
265   //  (3) the thing we're referencing is another inline function.
266   // This last can give us false negatives, but it's better than warning on
267   // wrappers for simple C library functions.
268   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270   if (!DowngradeWarning && UsedFn)
271     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
272
273   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274                                : diag::ext_internal_in_extern_inline)
275     << /*IsVar=*/!UsedFn << D;
276
277   S.MaybeSuggestAddingStaticToDecl(Current);
278
279   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
280       << D;
281 }
282
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284   const FunctionDecl *First = Cur->getFirstDecl();
285
286   // Suggest "static" on the function, if possible.
287   if (!hasAnyExplicitStorageClass(First)) {
288     SourceLocation DeclBegin = First->getSourceRange().getBegin();
289     Diag(DeclBegin, diag::note_convert_inline_to_static)
290       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
291   }
292 }
293
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
296 ///
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
302 ///
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
305 ///
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307                              const ObjCInterfaceDecl *UnknownObjCClass,
308                              bool ObjCPropertyAccess) {
309   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310     // If there were any diagnostics suppressed by template argument deduction,
311     // emit them now.
312     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313     if (Pos != SuppressedDiagnostics.end()) {
314       for (const PartialDiagnosticAt &Suppressed : Pos->second)
315         Diag(Suppressed.first, Suppressed.second);
316
317       // Clear out the list of suppressed diagnostics, so that we don't emit
318       // them again for this specialization. However, we don't obsolete this
319       // entry from the table, because we want to avoid ever emitting these
320       // diagnostics again.
321       Pos->second.clear();
322     }
323
324     // C++ [basic.start.main]p3:
325     //   The function 'main' shall not be used within a program.
326     if (cast<FunctionDecl>(D)->isMain())
327       Diag(Loc, diag::ext_main_used);
328   }
329
330   // See if this is an auto-typed variable whose initializer we are parsing.
331   if (ParsingInitForAutoVars.count(D)) {
332     if (isa<BindingDecl>(D)) {
333       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
334         << D->getDeclName();
335     } else {
336       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
337
338       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339         << D->getDeclName() << (unsigned)AT->getKeyword();
340     }
341     return true;
342   }
343
344   // See if this is a deleted function.
345   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346     if (FD->isDeleted()) {
347       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
348       if (Ctor && Ctor->isInheritingConstructor())
349         Diag(Loc, diag::err_deleted_inherited_ctor_use)
350             << Ctor->getParent()
351             << Ctor->getInheritedConstructor().getConstructor()->getParent();
352       else 
353         Diag(Loc, diag::err_deleted_function_use);
354       NoteDeletedFunction(FD);
355       return true;
356     }
357
358     // If the function has a deduced return type, and we can't deduce it,
359     // then we can't use it either.
360     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
361         DeduceReturnType(FD, Loc))
362       return true;
363
364     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
365       return true;
366   }
367
368   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
369   // Only the variables omp_in and omp_out are allowed in the combiner.
370   // Only the variables omp_priv and omp_orig are allowed in the
371   // initializer-clause.
372   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
373   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
374       isa<VarDecl>(D)) {
375     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
376         << getCurFunction()->HasOMPDeclareReductionCombiner;
377     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
378     return true;
379   }
380   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
381                              ObjCPropertyAccess);
382
383   DiagnoseUnusedOfDecl(*this, D, Loc);
384
385   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
386
387   return false;
388 }
389
390 /// \brief Retrieve the message suffix that should be added to a
391 /// diagnostic complaining about the given function being deleted or
392 /// unavailable.
393 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
394   std::string Message;
395   if (FD->getAvailability(&Message))
396     return ": " + Message;
397
398   return std::string();
399 }
400
401 /// DiagnoseSentinelCalls - This routine checks whether a call or
402 /// message-send is to a declaration with the sentinel attribute, and
403 /// if so, it checks that the requirements of the sentinel are
404 /// satisfied.
405 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
406                                  ArrayRef<Expr *> Args) {
407   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
408   if (!attr)
409     return;
410
411   // The number of formal parameters of the declaration.
412   unsigned numFormalParams;
413
414   // The kind of declaration.  This is also an index into a %select in
415   // the diagnostic.
416   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
417
418   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
419     numFormalParams = MD->param_size();
420     calleeType = CT_Method;
421   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
422     numFormalParams = FD->param_size();
423     calleeType = CT_Function;
424   } else if (isa<VarDecl>(D)) {
425     QualType type = cast<ValueDecl>(D)->getType();
426     const FunctionType *fn = nullptr;
427     if (const PointerType *ptr = type->getAs<PointerType>()) {
428       fn = ptr->getPointeeType()->getAs<FunctionType>();
429       if (!fn) return;
430       calleeType = CT_Function;
431     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
432       fn = ptr->getPointeeType()->castAs<FunctionType>();
433       calleeType = CT_Block;
434     } else {
435       return;
436     }
437
438     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
439       numFormalParams = proto->getNumParams();
440     } else {
441       numFormalParams = 0;
442     }
443   } else {
444     return;
445   }
446
447   // "nullPos" is the number of formal parameters at the end which
448   // effectively count as part of the variadic arguments.  This is
449   // useful if you would prefer to not have *any* formal parameters,
450   // but the language forces you to have at least one.
451   unsigned nullPos = attr->getNullPos();
452   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
453   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
454
455   // The number of arguments which should follow the sentinel.
456   unsigned numArgsAfterSentinel = attr->getSentinel();
457
458   // If there aren't enough arguments for all the formal parameters,
459   // the sentinel, and the args after the sentinel, complain.
460   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
461     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
463     return;
464   }
465
466   // Otherwise, find the sentinel expression.
467   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
468   if (!sentinelExpr) return;
469   if (sentinelExpr->isValueDependent()) return;
470   if (Context.isSentinelNullExpr(sentinelExpr)) return;
471
472   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
473   // or 'NULL' if those are actually defined in the context.  Only use
474   // 'nil' for ObjC methods, where it's much more likely that the
475   // variadic arguments form a list of object pointers.
476   SourceLocation MissingNilLoc
477     = getLocForEndOfToken(sentinelExpr->getLocEnd());
478   std::string NullValue;
479   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
480     NullValue = "nil";
481   else if (getLangOpts().CPlusPlus11)
482     NullValue = "nullptr";
483   else if (PP.isMacroDefined("NULL"))
484     NullValue = "NULL";
485   else
486     NullValue = "(void*) 0";
487
488   if (MissingNilLoc.isInvalid())
489     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
490   else
491     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
492       << int(calleeType)
493       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
494   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
495 }
496
497 SourceRange Sema::getExprRange(Expr *E) const {
498   return E ? E->getSourceRange() : SourceRange();
499 }
500
501 //===----------------------------------------------------------------------===//
502 //  Standard Promotions and Conversions
503 //===----------------------------------------------------------------------===//
504
505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
507   // Handle any placeholder expressions which made it here.
508   if (E->getType()->isPlaceholderType()) {
509     ExprResult result = CheckPlaceholderExpr(E);
510     if (result.isInvalid()) return ExprError();
511     E = result.get();
512   }
513   
514   QualType Ty = E->getType();
515   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
516
517   if (Ty->isFunctionType()) {
518     // If we are here, we are not calling a function but taking
519     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
520     if (getLangOpts().OpenCL) {
521       if (Diagnose)
522         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
523       return ExprError();
524     }
525
526     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
527       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
528         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
529           return ExprError();
530
531     E = ImpCastExprToType(E, Context.getPointerType(Ty),
532                           CK_FunctionToPointerDecay).get();
533   } else if (Ty->isArrayType()) {
534     // In C90 mode, arrays only promote to pointers if the array expression is
535     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
536     // type 'array of type' is converted to an expression that has type 'pointer
537     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
538     // that has type 'array of type' ...".  The relevant change is "an lvalue"
539     // (C90) to "an expression" (C99).
540     //
541     // C++ 4.2p1:
542     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
543     // T" can be converted to an rvalue of type "pointer to T".
544     //
545     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
546       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
547                             CK_ArrayToPointerDecay).get();
548   }
549   return E;
550 }
551
552 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
553   // Check to see if we are dereferencing a null pointer.  If so,
554   // and if not volatile-qualified, this is undefined behavior that the
555   // optimizer will delete, so warn about it.  People sometimes try to use this
556   // to get a deterministic trap and are surprised by clang's behavior.  This
557   // only handles the pattern "*null", which is a very syntactic check.
558   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
559     if (UO->getOpcode() == UO_Deref &&
560         UO->getSubExpr()->IgnoreParenCasts()->
561           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
562         !UO->getType().isVolatileQualified()) {
563     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564                           S.PDiag(diag::warn_indirection_through_null)
565                             << UO->getSubExpr()->getSourceRange());
566     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
567                         S.PDiag(diag::note_indirection_through_null));
568   }
569 }
570
571 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
572                                     SourceLocation AssignLoc,
573                                     const Expr* RHS) {
574   const ObjCIvarDecl *IV = OIRE->getDecl();
575   if (!IV)
576     return;
577   
578   DeclarationName MemberName = IV->getDeclName();
579   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
580   if (!Member || !Member->isStr("isa"))
581     return;
582   
583   const Expr *Base = OIRE->getBase();
584   QualType BaseType = Base->getType();
585   if (OIRE->isArrow())
586     BaseType = BaseType->getPointeeType();
587   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
588     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
589       ObjCInterfaceDecl *ClassDeclared = nullptr;
590       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
591       if (!ClassDeclared->getSuperClass()
592           && (*ClassDeclared->ivar_begin()) == IV) {
593         if (RHS) {
594           NamedDecl *ObjectSetClass =
595             S.LookupSingleName(S.TUScope,
596                                &S.Context.Idents.get("object_setClass"),
597                                SourceLocation(), S.LookupOrdinaryName);
598           if (ObjectSetClass) {
599             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
600             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
601             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
602             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
603                                                      AssignLoc), ",") <<
604             FixItHint::CreateInsertion(RHSLocEnd, ")");
605           }
606           else
607             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
608         } else {
609           NamedDecl *ObjectGetClass =
610             S.LookupSingleName(S.TUScope,
611                                &S.Context.Idents.get("object_getClass"),
612                                SourceLocation(), S.LookupOrdinaryName);
613           if (ObjectGetClass)
614             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
615             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
616             FixItHint::CreateReplacement(
617                                          SourceRange(OIRE->getOpLoc(),
618                                                      OIRE->getLocEnd()), ")");
619           else
620             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
621         }
622         S.Diag(IV->getLocation(), diag::note_ivar_decl);
623       }
624     }
625 }
626
627 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
628   // Handle any placeholder expressions which made it here.
629   if (E->getType()->isPlaceholderType()) {
630     ExprResult result = CheckPlaceholderExpr(E);
631     if (result.isInvalid()) return ExprError();
632     E = result.get();
633   }
634   
635   // C++ [conv.lval]p1:
636   //   A glvalue of a non-function, non-array type T can be
637   //   converted to a prvalue.
638   if (!E->isGLValue()) return E;
639
640   QualType T = E->getType();
641   assert(!T.isNull() && "r-value conversion on typeless expression?");
642
643   // We don't want to throw lvalue-to-rvalue casts on top of
644   // expressions of certain types in C++.
645   if (getLangOpts().CPlusPlus &&
646       (E->getType() == Context.OverloadTy ||
647        T->isDependentType() ||
648        T->isRecordType()))
649     return E;
650
651   // The C standard is actually really unclear on this point, and
652   // DR106 tells us what the result should be but not why.  It's
653   // generally best to say that void types just doesn't undergo
654   // lvalue-to-rvalue at all.  Note that expressions of unqualified
655   // 'void' type are never l-values, but qualified void can be.
656   if (T->isVoidType())
657     return E;
658
659   // OpenCL usually rejects direct accesses to values of 'half' type.
660   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
661       T->isHalfType()) {
662     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663       << 0 << T;
664     return ExprError();
665   }
666
667   CheckForNullPointerDereference(*this, E);
668   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670                                      &Context.Idents.get("object_getClass"),
671                                      SourceLocation(), LookupOrdinaryName);
672     if (ObjectGetClass)
673       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
674         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
675         FixItHint::CreateReplacement(
676                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677     else
678       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679   }
680   else if (const ObjCIvarRefExpr *OIRE =
681             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683
684   // C++ [conv.lval]p1:
685   //   [...] If T is a non-class type, the type of the prvalue is the
686   //   cv-unqualified version of T. Otherwise, the type of the
687   //   rvalue is T.
688   //
689   // C99 6.3.2.1p2:
690   //   If the lvalue has qualified type, the value has the unqualified
691   //   version of the type of the lvalue; otherwise, the value has the
692   //   type of the lvalue.
693   if (T.hasQualifiers())
694     T = T.getUnqualifiedType();
695
696   // Under the MS ABI, lock down the inheritance model now.
697   if (T->isMemberPointerType() &&
698       Context.getTargetInfo().getCXXABI().isMicrosoft())
699     (void)isCompleteType(E->getExprLoc(), T);
700
701   UpdateMarkingForLValueToRValue(E);
702   
703   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
704   // balance that.
705   if (getLangOpts().ObjCAutoRefCount &&
706       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
707     Cleanup.setExprNeedsCleanups(true);
708
709   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
710                                             nullptr, VK_RValue);
711
712   // C11 6.3.2.1p2:
713   //   ... if the lvalue has atomic type, the value has the non-atomic version 
714   //   of the type of the lvalue ...
715   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
716     T = Atomic->getValueType().getUnqualifiedType();
717     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
718                                    nullptr, VK_RValue);
719   }
720   
721   return Res;
722 }
723
724 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
725   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
726   if (Res.isInvalid())
727     return ExprError();
728   Res = DefaultLvalueConversion(Res.get());
729   if (Res.isInvalid())
730     return ExprError();
731   return Res;
732 }
733
734 /// CallExprUnaryConversions - a special case of an unary conversion
735 /// performed on a function designator of a call expression.
736 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
737   QualType Ty = E->getType();
738   ExprResult Res = E;
739   // Only do implicit cast for a function type, but not for a pointer
740   // to function type.
741   if (Ty->isFunctionType()) {
742     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
743                             CK_FunctionToPointerDecay).get();
744     if (Res.isInvalid())
745       return ExprError();
746   }
747   Res = DefaultLvalueConversion(Res.get());
748   if (Res.isInvalid())
749     return ExprError();
750   return Res.get();
751 }
752
753 /// UsualUnaryConversions - Performs various conversions that are common to most
754 /// operators (C99 6.3). The conversions of array and function types are
755 /// sometimes suppressed. For example, the array->pointer conversion doesn't
756 /// apply if the array is an argument to the sizeof or address (&) operators.
757 /// In these instances, this routine should *not* be called.
758 ExprResult Sema::UsualUnaryConversions(Expr *E) {
759   // First, convert to an r-value.
760   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
761   if (Res.isInvalid())
762     return ExprError();
763   E = Res.get();
764
765   QualType Ty = E->getType();
766   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
767
768   // Half FP have to be promoted to float unless it is natively supported
769   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
770     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
771
772   // Try to perform integral promotions if the object has a theoretically
773   // promotable type.
774   if (Ty->isIntegralOrUnscopedEnumerationType()) {
775     // C99 6.3.1.1p2:
776     //
777     //   The following may be used in an expression wherever an int or
778     //   unsigned int may be used:
779     //     - an object or expression with an integer type whose integer
780     //       conversion rank is less than or equal to the rank of int
781     //       and unsigned int.
782     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
783     //
784     //   If an int can represent all values of the original type, the
785     //   value is converted to an int; otherwise, it is converted to an
786     //   unsigned int. These are called the integer promotions. All
787     //   other types are unchanged by the integer promotions.
788
789     QualType PTy = Context.isPromotableBitField(E);
790     if (!PTy.isNull()) {
791       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
792       return E;
793     }
794     if (Ty->isPromotableIntegerType()) {
795       QualType PT = Context.getPromotedIntegerType(Ty);
796       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
797       return E;
798     }
799   }
800   return E;
801 }
802
803 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
804 /// do not have a prototype. Arguments that have type float or __fp16
805 /// are promoted to double. All other argument types are converted by
806 /// UsualUnaryConversions().
807 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
808   QualType Ty = E->getType();
809   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
810
811   ExprResult Res = UsualUnaryConversions(E);
812   if (Res.isInvalid())
813     return ExprError();
814   E = Res.get();
815
816   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
817   // double.
818   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
819   if (BTy && (BTy->getKind() == BuiltinType::Half ||
820               BTy->getKind() == BuiltinType::Float))
821     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
822
823   // C++ performs lvalue-to-rvalue conversion as a default argument
824   // promotion, even on class types, but note:
825   //   C++11 [conv.lval]p2:
826   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
827   //     operand or a subexpression thereof the value contained in the
828   //     referenced object is not accessed. Otherwise, if the glvalue
829   //     has a class type, the conversion copy-initializes a temporary
830   //     of type T from the glvalue and the result of the conversion
831   //     is a prvalue for the temporary.
832   // FIXME: add some way to gate this entire thing for correctness in
833   // potentially potentially evaluated contexts.
834   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835     ExprResult Temp = PerformCopyInitialization(
836                        InitializedEntity::InitializeTemporary(E->getType()),
837                                                 E->getExprLoc(), E);
838     if (Temp.isInvalid())
839       return ExprError();
840     E = Temp.get();
841   }
842
843   return E;
844 }
845
846 /// Determine the degree of POD-ness for an expression.
847 /// Incomplete types are considered POD, since this check can be performed
848 /// when we're in an unevaluated context.
849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850   if (Ty->isIncompleteType()) {
851     // C++11 [expr.call]p7:
852     //   After these conversions, if the argument does not have arithmetic,
853     //   enumeration, pointer, pointer to member, or class type, the program
854     //   is ill-formed.
855     //
856     // Since we've already performed array-to-pointer and function-to-pointer
857     // decay, the only such type in C++ is cv void. This also handles
858     // initializer lists as variadic arguments.
859     if (Ty->isVoidType())
860       return VAK_Invalid;
861
862     if (Ty->isObjCObjectType())
863       return VAK_Invalid;
864     return VAK_Valid;
865   }
866
867   if (Ty.isCXX98PODType(Context))
868     return VAK_Valid;
869
870   // C++11 [expr.call]p7:
871   //   Passing a potentially-evaluated argument of class type (Clause 9)
872   //   having a non-trivial copy constructor, a non-trivial move constructor,
873   //   or a non-trivial destructor, with no corresponding parameter,
874   //   is conditionally-supported with implementation-defined semantics.
875   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
876     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
877       if (!Record->hasNonTrivialCopyConstructor() &&
878           !Record->hasNonTrivialMoveConstructor() &&
879           !Record->hasNonTrivialDestructor())
880         return VAK_ValidInCXX11;
881
882   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
883     return VAK_Valid;
884
885   if (Ty->isObjCObjectType())
886     return VAK_Invalid;
887
888   if (getLangOpts().MSVCCompat)
889     return VAK_MSVCUndefined;
890
891   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
892   // permitted to reject them. We should consider doing so.
893   return VAK_Undefined;
894 }
895
896 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
897   // Don't allow one to pass an Objective-C interface to a vararg.
898   const QualType &Ty = E->getType();
899   VarArgKind VAK = isValidVarArgType(Ty);
900
901   // Complain about passing non-POD types through varargs.
902   switch (VAK) {
903   case VAK_ValidInCXX11:
904     DiagRuntimeBehavior(
905         E->getLocStart(), nullptr,
906         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
907           << Ty << CT);
908     // Fall through.
909   case VAK_Valid:
910     if (Ty->isRecordType()) {
911       // This is unlikely to be what the user intended. If the class has a
912       // 'c_str' member function, the user probably meant to call that.
913       DiagRuntimeBehavior(E->getLocStart(), nullptr,
914                           PDiag(diag::warn_pass_class_arg_to_vararg)
915                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
916     }
917     break;
918
919   case VAK_Undefined:
920   case VAK_MSVCUndefined:
921     DiagRuntimeBehavior(
922         E->getLocStart(), nullptr,
923         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
924           << getLangOpts().CPlusPlus11 << Ty << CT);
925     break;
926
927   case VAK_Invalid:
928     if (Ty->isObjCObjectType())
929       DiagRuntimeBehavior(
930           E->getLocStart(), nullptr,
931           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
932             << Ty << CT);
933     else
934       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
935         << isa<InitListExpr>(E) << Ty << CT;
936     break;
937   }
938 }
939
940 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
941 /// will create a trap if the resulting type is not a POD type.
942 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
943                                                   FunctionDecl *FDecl) {
944   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
945     // Strip the unbridged-cast placeholder expression off, if applicable.
946     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
947         (CT == VariadicMethod ||
948          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
949       E = stripARCUnbridgedCast(E);
950
951     // Otherwise, do normal placeholder checking.
952     } else {
953       ExprResult ExprRes = CheckPlaceholderExpr(E);
954       if (ExprRes.isInvalid())
955         return ExprError();
956       E = ExprRes.get();
957     }
958   }
959   
960   ExprResult ExprRes = DefaultArgumentPromotion(E);
961   if (ExprRes.isInvalid())
962     return ExprError();
963   E = ExprRes.get();
964
965   // Diagnostics regarding non-POD argument types are
966   // emitted along with format string checking in Sema::CheckFunctionCall().
967   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
968     // Turn this into a trap.
969     CXXScopeSpec SS;
970     SourceLocation TemplateKWLoc;
971     UnqualifiedId Name;
972     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
973                        E->getLocStart());
974     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
975                                           Name, true, false);
976     if (TrapFn.isInvalid())
977       return ExprError();
978
979     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
980                                     E->getLocStart(), None,
981                                     E->getLocEnd());
982     if (Call.isInvalid())
983       return ExprError();
984
985     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
986                                   Call.get(), E);
987     if (Comma.isInvalid())
988       return ExprError();
989     return Comma.get();
990   }
991
992   if (!getLangOpts().CPlusPlus &&
993       RequireCompleteType(E->getExprLoc(), E->getType(),
994                           diag::err_call_incomplete_argument))
995     return ExprError();
996
997   return E;
998 }
999
1000 /// \brief Converts an integer to complex float type.  Helper function of
1001 /// UsualArithmeticConversions()
1002 ///
1003 /// \return false if the integer expression is an integer type and is
1004 /// successfully converted to the complex type.
1005 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1006                                                   ExprResult &ComplexExpr,
1007                                                   QualType IntTy,
1008                                                   QualType ComplexTy,
1009                                                   bool SkipCast) {
1010   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1011   if (SkipCast) return false;
1012   if (IntTy->isIntegerType()) {
1013     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1014     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1015     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1016                                   CK_FloatingRealToComplex);
1017   } else {
1018     assert(IntTy->isComplexIntegerType());
1019     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1020                                   CK_IntegralComplexToFloatingComplex);
1021   }
1022   return false;
1023 }
1024
1025 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1026 /// UsualArithmeticConversions()
1027 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1028                                              ExprResult &RHS, QualType LHSType,
1029                                              QualType RHSType,
1030                                              bool IsCompAssign) {
1031   // if we have an integer operand, the result is the complex type.
1032   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1033                                              /*skipCast*/false))
1034     return LHSType;
1035   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1036                                              /*skipCast*/IsCompAssign))
1037     return RHSType;
1038
1039   // This handles complex/complex, complex/float, or float/complex.
1040   // When both operands are complex, the shorter operand is converted to the
1041   // type of the longer, and that is the type of the result. This corresponds
1042   // to what is done when combining two real floating-point operands.
1043   // The fun begins when size promotion occur across type domains.
1044   // From H&S 6.3.4: When one operand is complex and the other is a real
1045   // floating-point type, the less precise type is converted, within it's
1046   // real or complex domain, to the precision of the other type. For example,
1047   // when combining a "long double" with a "double _Complex", the
1048   // "double _Complex" is promoted to "long double _Complex".
1049
1050   // Compute the rank of the two types, regardless of whether they are complex.
1051   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1052
1053   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1054   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1055   QualType LHSElementType =
1056       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1057   QualType RHSElementType =
1058       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1059
1060   QualType ResultType = S.Context.getComplexType(LHSElementType);
1061   if (Order < 0) {
1062     // Promote the precision of the LHS if not an assignment.
1063     ResultType = S.Context.getComplexType(RHSElementType);
1064     if (!IsCompAssign) {
1065       if (LHSComplexType)
1066         LHS =
1067             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1068       else
1069         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1070     }
1071   } else if (Order > 0) {
1072     // Promote the precision of the RHS.
1073     if (RHSComplexType)
1074       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1075     else
1076       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1077   }
1078   return ResultType;
1079 }
1080
1081 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1082 /// of UsualArithmeticConversions()
1083 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1084                                            ExprResult &IntExpr,
1085                                            QualType FloatTy, QualType IntTy,
1086                                            bool ConvertFloat, bool ConvertInt) {
1087   if (IntTy->isIntegerType()) {
1088     if (ConvertInt)
1089       // Convert intExpr to the lhs floating point type.
1090       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1091                                     CK_IntegralToFloating);
1092     return FloatTy;
1093   }
1094      
1095   // Convert both sides to the appropriate complex float.
1096   assert(IntTy->isComplexIntegerType());
1097   QualType result = S.Context.getComplexType(FloatTy);
1098
1099   // _Complex int -> _Complex float
1100   if (ConvertInt)
1101     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1102                                   CK_IntegralComplexToFloatingComplex);
1103
1104   // float -> _Complex float
1105   if (ConvertFloat)
1106     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1107                                     CK_FloatingRealToComplex);
1108
1109   return result;
1110 }
1111
1112 /// \brief Handle arithmethic conversion with floating point types.  Helper
1113 /// function of UsualArithmeticConversions()
1114 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1115                                       ExprResult &RHS, QualType LHSType,
1116                                       QualType RHSType, bool IsCompAssign) {
1117   bool LHSFloat = LHSType->isRealFloatingType();
1118   bool RHSFloat = RHSType->isRealFloatingType();
1119
1120   // If we have two real floating types, convert the smaller operand
1121   // to the bigger result.
1122   if (LHSFloat && RHSFloat) {
1123     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1124     if (order > 0) {
1125       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1126       return LHSType;
1127     }
1128
1129     assert(order < 0 && "illegal float comparison");
1130     if (!IsCompAssign)
1131       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1132     return RHSType;
1133   }
1134
1135   if (LHSFloat) {
1136     // Half FP has to be promoted to float unless it is natively supported
1137     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1138       LHSType = S.Context.FloatTy;
1139
1140     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1141                                       /*convertFloat=*/!IsCompAssign,
1142                                       /*convertInt=*/ true);
1143   }
1144   assert(RHSFloat);
1145   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1146                                     /*convertInt=*/ true,
1147                                     /*convertFloat=*/!IsCompAssign);
1148 }
1149
1150 /// \brief Diagnose attempts to convert between __float128 and long double if
1151 /// there is no support for such conversion. Helper function of
1152 /// UsualArithmeticConversions().
1153 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1154                                       QualType RHSType) {
1155   /*  No issue converting if at least one of the types is not a floating point
1156       type or the two types have the same rank.
1157   */
1158   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1159       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1160     return false;
1161
1162   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1163          "The remaining types must be floating point types.");
1164
1165   auto *LHSComplex = LHSType->getAs<ComplexType>();
1166   auto *RHSComplex = RHSType->getAs<ComplexType>();
1167
1168   QualType LHSElemType = LHSComplex ?
1169     LHSComplex->getElementType() : LHSType;
1170   QualType RHSElemType = RHSComplex ?
1171     RHSComplex->getElementType() : RHSType;
1172
1173   // No issue if the two types have the same representation
1174   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1175       &S.Context.getFloatTypeSemantics(RHSElemType))
1176     return false;
1177
1178   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1179                                 RHSElemType == S.Context.LongDoubleTy);
1180   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1181                             RHSElemType == S.Context.Float128Ty);
1182
1183   /* We've handled the situation where __float128 and long double have the same
1184      representation. The only other allowable conversion is if long double is
1185      really just double.
1186   */
1187   return Float128AndLongDouble &&
1188     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1189      &llvm::APFloat::IEEEdouble);
1190 }
1191
1192 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1193
1194 namespace {
1195 /// These helper callbacks are placed in an anonymous namespace to
1196 /// permit their use as function template parameters.
1197 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1198   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1199 }
1200
1201 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1202   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1203                              CK_IntegralComplexCast);
1204 }
1205 }
1206
1207 /// \brief Handle integer arithmetic conversions.  Helper function of
1208 /// UsualArithmeticConversions()
1209 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1210 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1211                                         ExprResult &RHS, QualType LHSType,
1212                                         QualType RHSType, bool IsCompAssign) {
1213   // The rules for this case are in C99 6.3.1.8
1214   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1215   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1216   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1217   if (LHSSigned == RHSSigned) {
1218     // Same signedness; use the higher-ranked type
1219     if (order >= 0) {
1220       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1221       return LHSType;
1222     } else if (!IsCompAssign)
1223       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1224     return RHSType;
1225   } else if (order != (LHSSigned ? 1 : -1)) {
1226     // The unsigned type has greater than or equal rank to the
1227     // signed type, so use the unsigned type
1228     if (RHSSigned) {
1229       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1230       return LHSType;
1231     } else if (!IsCompAssign)
1232       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1233     return RHSType;
1234   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1235     // The two types are different widths; if we are here, that
1236     // means the signed type is larger than the unsigned type, so
1237     // use the signed type.
1238     if (LHSSigned) {
1239       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1240       return LHSType;
1241     } else if (!IsCompAssign)
1242       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1243     return RHSType;
1244   } else {
1245     // The signed type is higher-ranked than the unsigned type,
1246     // but isn't actually any bigger (like unsigned int and long
1247     // on most 32-bit systems).  Use the unsigned type corresponding
1248     // to the signed type.
1249     QualType result =
1250       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1251     RHS = (*doRHSCast)(S, RHS.get(), result);
1252     if (!IsCompAssign)
1253       LHS = (*doLHSCast)(S, LHS.get(), result);
1254     return result;
1255   }
1256 }
1257
1258 /// \brief Handle conversions with GCC complex int extension.  Helper function
1259 /// of UsualArithmeticConversions()
1260 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1261                                            ExprResult &RHS, QualType LHSType,
1262                                            QualType RHSType,
1263                                            bool IsCompAssign) {
1264   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1265   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1266
1267   if (LHSComplexInt && RHSComplexInt) {
1268     QualType LHSEltType = LHSComplexInt->getElementType();
1269     QualType RHSEltType = RHSComplexInt->getElementType();
1270     QualType ScalarType =
1271       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1272         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1273
1274     return S.Context.getComplexType(ScalarType);
1275   }
1276
1277   if (LHSComplexInt) {
1278     QualType LHSEltType = LHSComplexInt->getElementType();
1279     QualType ScalarType =
1280       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1281         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1282     QualType ComplexType = S.Context.getComplexType(ScalarType);
1283     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1284                               CK_IntegralRealToComplex);
1285  
1286     return ComplexType;
1287   }
1288
1289   assert(RHSComplexInt);
1290
1291   QualType RHSEltType = RHSComplexInt->getElementType();
1292   QualType ScalarType =
1293     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1294       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1295   QualType ComplexType = S.Context.getComplexType(ScalarType);
1296   
1297   if (!IsCompAssign)
1298     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1299                               CK_IntegralRealToComplex);
1300   return ComplexType;
1301 }
1302
1303 /// UsualArithmeticConversions - Performs various conversions that are common to
1304 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1305 /// routine returns the first non-arithmetic type found. The client is
1306 /// responsible for emitting appropriate error diagnostics.
1307 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1308                                           bool IsCompAssign) {
1309   if (!IsCompAssign) {
1310     LHS = UsualUnaryConversions(LHS.get());
1311     if (LHS.isInvalid())
1312       return QualType();
1313   }
1314
1315   RHS = UsualUnaryConversions(RHS.get());
1316   if (RHS.isInvalid())
1317     return QualType();
1318
1319   // For conversion purposes, we ignore any qualifiers.
1320   // For example, "const float" and "float" are equivalent.
1321   QualType LHSType =
1322     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1323   QualType RHSType =
1324     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1325
1326   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1327   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1328     LHSType = AtomicLHS->getValueType();
1329
1330   // If both types are identical, no conversion is needed.
1331   if (LHSType == RHSType)
1332     return LHSType;
1333
1334   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1335   // The caller can deal with this (e.g. pointer + int).
1336   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1337     return QualType();
1338
1339   // Apply unary and bitfield promotions to the LHS's type.
1340   QualType LHSUnpromotedType = LHSType;
1341   if (LHSType->isPromotableIntegerType())
1342     LHSType = Context.getPromotedIntegerType(LHSType);
1343   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1344   if (!LHSBitfieldPromoteTy.isNull())
1345     LHSType = LHSBitfieldPromoteTy;
1346   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1347     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1348
1349   // If both types are identical, no conversion is needed.
1350   if (LHSType == RHSType)
1351     return LHSType;
1352
1353   // At this point, we have two different arithmetic types.
1354
1355   // Diagnose attempts to convert between __float128 and long double where
1356   // such conversions currently can't be handled.
1357   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1358     return QualType();
1359
1360   // Handle complex types first (C99 6.3.1.8p1).
1361   if (LHSType->isComplexType() || RHSType->isComplexType())
1362     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1363                                         IsCompAssign);
1364
1365   // Now handle "real" floating types (i.e. float, double, long double).
1366   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1367     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1368                                  IsCompAssign);
1369
1370   // Handle GCC complex int extension.
1371   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1372     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1373                                       IsCompAssign);
1374
1375   // Finally, we have two differing integer types.
1376   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1377            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1378 }
1379
1380
1381 //===----------------------------------------------------------------------===//
1382 //  Semantic Analysis for various Expression Types
1383 //===----------------------------------------------------------------------===//
1384
1385
1386 ExprResult
1387 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1388                                 SourceLocation DefaultLoc,
1389                                 SourceLocation RParenLoc,
1390                                 Expr *ControllingExpr,
1391                                 ArrayRef<ParsedType> ArgTypes,
1392                                 ArrayRef<Expr *> ArgExprs) {
1393   unsigned NumAssocs = ArgTypes.size();
1394   assert(NumAssocs == ArgExprs.size());
1395
1396   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1397   for (unsigned i = 0; i < NumAssocs; ++i) {
1398     if (ArgTypes[i])
1399       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1400     else
1401       Types[i] = nullptr;
1402   }
1403
1404   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1405                                              ControllingExpr,
1406                                              llvm::makeArrayRef(Types, NumAssocs),
1407                                              ArgExprs);
1408   delete [] Types;
1409   return ER;
1410 }
1411
1412 ExprResult
1413 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1414                                  SourceLocation DefaultLoc,
1415                                  SourceLocation RParenLoc,
1416                                  Expr *ControllingExpr,
1417                                  ArrayRef<TypeSourceInfo *> Types,
1418                                  ArrayRef<Expr *> Exprs) {
1419   unsigned NumAssocs = Types.size();
1420   assert(NumAssocs == Exprs.size());
1421
1422   // Decay and strip qualifiers for the controlling expression type, and handle
1423   // placeholder type replacement. See committee discussion from WG14 DR423.
1424   {
1425     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1426     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1427     if (R.isInvalid())
1428       return ExprError();
1429     ControllingExpr = R.get();
1430   }
1431
1432   // The controlling expression is an unevaluated operand, so side effects are
1433   // likely unintended.
1434   if (ActiveTemplateInstantiations.empty() &&
1435       ControllingExpr->HasSideEffects(Context, false))
1436     Diag(ControllingExpr->getExprLoc(),
1437          diag::warn_side_effects_unevaluated_context);
1438
1439   bool TypeErrorFound = false,
1440        IsResultDependent = ControllingExpr->isTypeDependent(),
1441        ContainsUnexpandedParameterPack
1442          = ControllingExpr->containsUnexpandedParameterPack();
1443
1444   for (unsigned i = 0; i < NumAssocs; ++i) {
1445     if (Exprs[i]->containsUnexpandedParameterPack())
1446       ContainsUnexpandedParameterPack = true;
1447
1448     if (Types[i]) {
1449       if (Types[i]->getType()->containsUnexpandedParameterPack())
1450         ContainsUnexpandedParameterPack = true;
1451
1452       if (Types[i]->getType()->isDependentType()) {
1453         IsResultDependent = true;
1454       } else {
1455         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1456         // complete object type other than a variably modified type."
1457         unsigned D = 0;
1458         if (Types[i]->getType()->isIncompleteType())
1459           D = diag::err_assoc_type_incomplete;
1460         else if (!Types[i]->getType()->isObjectType())
1461           D = diag::err_assoc_type_nonobject;
1462         else if (Types[i]->getType()->isVariablyModifiedType())
1463           D = diag::err_assoc_type_variably_modified;
1464
1465         if (D != 0) {
1466           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1467             << Types[i]->getTypeLoc().getSourceRange()
1468             << Types[i]->getType();
1469           TypeErrorFound = true;
1470         }
1471
1472         // C11 6.5.1.1p2 "No two generic associations in the same generic
1473         // selection shall specify compatible types."
1474         for (unsigned j = i+1; j < NumAssocs; ++j)
1475           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1476               Context.typesAreCompatible(Types[i]->getType(),
1477                                          Types[j]->getType())) {
1478             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1479                  diag::err_assoc_compatible_types)
1480               << Types[j]->getTypeLoc().getSourceRange()
1481               << Types[j]->getType()
1482               << Types[i]->getType();
1483             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1484                  diag::note_compat_assoc)
1485               << Types[i]->getTypeLoc().getSourceRange()
1486               << Types[i]->getType();
1487             TypeErrorFound = true;
1488           }
1489       }
1490     }
1491   }
1492   if (TypeErrorFound)
1493     return ExprError();
1494
1495   // If we determined that the generic selection is result-dependent, don't
1496   // try to compute the result expression.
1497   if (IsResultDependent)
1498     return new (Context) GenericSelectionExpr(
1499         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1500         ContainsUnexpandedParameterPack);
1501
1502   SmallVector<unsigned, 1> CompatIndices;
1503   unsigned DefaultIndex = -1U;
1504   for (unsigned i = 0; i < NumAssocs; ++i) {
1505     if (!Types[i])
1506       DefaultIndex = i;
1507     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1508                                         Types[i]->getType()))
1509       CompatIndices.push_back(i);
1510   }
1511
1512   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1513   // type compatible with at most one of the types named in its generic
1514   // association list."
1515   if (CompatIndices.size() > 1) {
1516     // We strip parens here because the controlling expression is typically
1517     // parenthesized in macro definitions.
1518     ControllingExpr = ControllingExpr->IgnoreParens();
1519     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1520       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1521       << (unsigned) CompatIndices.size();
1522     for (unsigned I : CompatIndices) {
1523       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1524            diag::note_compat_assoc)
1525         << Types[I]->getTypeLoc().getSourceRange()
1526         << Types[I]->getType();
1527     }
1528     return ExprError();
1529   }
1530
1531   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1532   // its controlling expression shall have type compatible with exactly one of
1533   // the types named in its generic association list."
1534   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1535     // We strip parens here because the controlling expression is typically
1536     // parenthesized in macro definitions.
1537     ControllingExpr = ControllingExpr->IgnoreParens();
1538     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1539       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1540     return ExprError();
1541   }
1542
1543   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1544   // type name that is compatible with the type of the controlling expression,
1545   // then the result expression of the generic selection is the expression
1546   // in that generic association. Otherwise, the result expression of the
1547   // generic selection is the expression in the default generic association."
1548   unsigned ResultIndex =
1549     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1550
1551   return new (Context) GenericSelectionExpr(
1552       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1553       ContainsUnexpandedParameterPack, ResultIndex);
1554 }
1555
1556 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1557 /// location of the token and the offset of the ud-suffix within it.
1558 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1559                                      unsigned Offset) {
1560   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1561                                         S.getLangOpts());
1562 }
1563
1564 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1565 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1566 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1567                                                  IdentifierInfo *UDSuffix,
1568                                                  SourceLocation UDSuffixLoc,
1569                                                  ArrayRef<Expr*> Args,
1570                                                  SourceLocation LitEndLoc) {
1571   assert(Args.size() <= 2 && "too many arguments for literal operator");
1572
1573   QualType ArgTy[2];
1574   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1575     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1576     if (ArgTy[ArgIdx]->isArrayType())
1577       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1578   }
1579
1580   DeclarationName OpName =
1581     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1582   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1583   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1584
1585   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1586   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1587                               /*AllowRaw*/false, /*AllowTemplate*/false,
1588                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1589     return ExprError();
1590
1591   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1592 }
1593
1594 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1595 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1596 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1597 /// multiple tokens.  However, the common case is that StringToks points to one
1598 /// string.
1599 ///
1600 ExprResult
1601 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1602   assert(!StringToks.empty() && "Must have at least one string!");
1603
1604   StringLiteralParser Literal(StringToks, PP);
1605   if (Literal.hadError)
1606     return ExprError();
1607
1608   SmallVector<SourceLocation, 4> StringTokLocs;
1609   for (const Token &Tok : StringToks)
1610     StringTokLocs.push_back(Tok.getLocation());
1611
1612   QualType CharTy = Context.CharTy;
1613   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1614   if (Literal.isWide()) {
1615     CharTy = Context.getWideCharType();
1616     Kind = StringLiteral::Wide;
1617   } else if (Literal.isUTF8()) {
1618     Kind = StringLiteral::UTF8;
1619   } else if (Literal.isUTF16()) {
1620     CharTy = Context.Char16Ty;
1621     Kind = StringLiteral::UTF16;
1622   } else if (Literal.isUTF32()) {
1623     CharTy = Context.Char32Ty;
1624     Kind = StringLiteral::UTF32;
1625   } else if (Literal.isPascal()) {
1626     CharTy = Context.UnsignedCharTy;
1627   }
1628
1629   QualType CharTyConst = CharTy;
1630   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1631   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1632     CharTyConst.addConst();
1633
1634   // Get an array type for the string, according to C99 6.4.5.  This includes
1635   // the nul terminator character as well as the string length for pascal
1636   // strings.
1637   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1638                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1639                                  ArrayType::Normal, 0);
1640
1641   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1642   if (getLangOpts().OpenCL) {
1643     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1644   }
1645
1646   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1647   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1648                                              Kind, Literal.Pascal, StrTy,
1649                                              &StringTokLocs[0],
1650                                              StringTokLocs.size());
1651   if (Literal.getUDSuffix().empty())
1652     return Lit;
1653
1654   // We're building a user-defined literal.
1655   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1656   SourceLocation UDSuffixLoc =
1657     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1658                    Literal.getUDSuffixOffset());
1659
1660   // Make sure we're allowed user-defined literals here.
1661   if (!UDLScope)
1662     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1663
1664   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1665   //   operator "" X (str, len)
1666   QualType SizeType = Context.getSizeType();
1667
1668   DeclarationName OpName =
1669     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1670   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1671   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1672
1673   QualType ArgTy[] = {
1674     Context.getArrayDecayedType(StrTy), SizeType
1675   };
1676
1677   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1678   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1679                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1680                                 /*AllowStringTemplate*/true)) {
1681
1682   case LOLR_Cooked: {
1683     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1684     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1685                                                     StringTokLocs[0]);
1686     Expr *Args[] = { Lit, LenArg };
1687
1688     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1689   }
1690
1691   case LOLR_StringTemplate: {
1692     TemplateArgumentListInfo ExplicitArgs;
1693
1694     unsigned CharBits = Context.getIntWidth(CharTy);
1695     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1696     llvm::APSInt Value(CharBits, CharIsUnsigned);
1697
1698     TemplateArgument TypeArg(CharTy);
1699     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1700     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1701
1702     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1703       Value = Lit->getCodeUnit(I);
1704       TemplateArgument Arg(Context, Value, CharTy);
1705       TemplateArgumentLocInfo ArgInfo;
1706       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1707     }
1708     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1709                                     &ExplicitArgs);
1710   }
1711   case LOLR_Raw:
1712   case LOLR_Template:
1713     llvm_unreachable("unexpected literal operator lookup result");
1714   case LOLR_Error:
1715     return ExprError();
1716   }
1717   llvm_unreachable("unexpected literal operator lookup result");
1718 }
1719
1720 ExprResult
1721 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1722                        SourceLocation Loc,
1723                        const CXXScopeSpec *SS) {
1724   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1725   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1726 }
1727
1728 /// BuildDeclRefExpr - Build an expression that references a
1729 /// declaration that does not require a closure capture.
1730 ExprResult
1731 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1732                        const DeclarationNameInfo &NameInfo,
1733                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1734                        const TemplateArgumentListInfo *TemplateArgs) {
1735   bool RefersToCapturedVariable =
1736       isa<VarDecl>(D) &&
1737       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1738
1739   DeclRefExpr *E;
1740   if (isa<VarTemplateSpecializationDecl>(D)) {
1741     VarTemplateSpecializationDecl *VarSpec =
1742         cast<VarTemplateSpecializationDecl>(D);
1743
1744     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1745                                         : NestedNameSpecifierLoc(),
1746                             VarSpec->getTemplateKeywordLoc(), D,
1747                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1748                             FoundD, TemplateArgs);
1749   } else {
1750     assert(!TemplateArgs && "No template arguments for non-variable"
1751                             " template specialization references");
1752     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1753                                         : NestedNameSpecifierLoc(),
1754                             SourceLocation(), D, RefersToCapturedVariable,
1755                             NameInfo, Ty, VK, FoundD);
1756   }
1757
1758   MarkDeclRefReferenced(E);
1759
1760   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1761       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1762       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1763       recordUseOfEvaluatedWeak(E);
1764
1765   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1766     UnusedPrivateFields.remove(FD);
1767     // Just in case we're building an illegal pointer-to-member.
1768     if (FD->isBitField())
1769       E->setObjectKind(OK_BitField);
1770   }
1771
1772   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1773   // designates a bit-field.
1774   if (auto *BD = dyn_cast<BindingDecl>(D))
1775     if (auto *BE = BD->getBinding())
1776       E->setObjectKind(BE->getObjectKind());
1777
1778   return E;
1779 }
1780
1781 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1782 /// possibly a list of template arguments.
1783 ///
1784 /// If this produces template arguments, it is permitted to call
1785 /// DecomposeTemplateName.
1786 ///
1787 /// This actually loses a lot of source location information for
1788 /// non-standard name kinds; we should consider preserving that in
1789 /// some way.
1790 void
1791 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1792                              TemplateArgumentListInfo &Buffer,
1793                              DeclarationNameInfo &NameInfo,
1794                              const TemplateArgumentListInfo *&TemplateArgs) {
1795   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1796     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1797     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1798
1799     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1800                                        Id.TemplateId->NumArgs);
1801     translateTemplateArguments(TemplateArgsPtr, Buffer);
1802
1803     TemplateName TName = Id.TemplateId->Template.get();
1804     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1805     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1806     TemplateArgs = &Buffer;
1807   } else {
1808     NameInfo = GetNameFromUnqualifiedId(Id);
1809     TemplateArgs = nullptr;
1810   }
1811 }
1812
1813 static void emitEmptyLookupTypoDiagnostic(
1814     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1815     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1816     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1817   DeclContext *Ctx =
1818       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1819   if (!TC) {
1820     // Emit a special diagnostic for failed member lookups.
1821     // FIXME: computing the declaration context might fail here (?)
1822     if (Ctx)
1823       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1824                                                  << SS.getRange();
1825     else
1826       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1827     return;
1828   }
1829
1830   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1831   bool DroppedSpecifier =
1832       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1833   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1834                         ? diag::note_implicit_param_decl
1835                         : diag::note_previous_decl;
1836   if (!Ctx)
1837     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1838                          SemaRef.PDiag(NoteID));
1839   else
1840     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1841                                  << Typo << Ctx << DroppedSpecifier
1842                                  << SS.getRange(),
1843                          SemaRef.PDiag(NoteID));
1844 }
1845
1846 /// Diagnose an empty lookup.
1847 ///
1848 /// \return false if new lookup candidates were found
1849 bool
1850 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1851                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1852                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1853                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1854   DeclarationName Name = R.getLookupName();
1855
1856   unsigned diagnostic = diag::err_undeclared_var_use;
1857   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1858   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1859       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1860       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1861     diagnostic = diag::err_undeclared_use;
1862     diagnostic_suggest = diag::err_undeclared_use_suggest;
1863   }
1864
1865   // If the original lookup was an unqualified lookup, fake an
1866   // unqualified lookup.  This is useful when (for example) the
1867   // original lookup would not have found something because it was a
1868   // dependent name.
1869   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1870   while (DC) {
1871     if (isa<CXXRecordDecl>(DC)) {
1872       LookupQualifiedName(R, DC);
1873
1874       if (!R.empty()) {
1875         // Don't give errors about ambiguities in this lookup.
1876         R.suppressDiagnostics();
1877
1878         // During a default argument instantiation the CurContext points
1879         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1880         // function parameter list, hence add an explicit check.
1881         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1882                               ActiveTemplateInstantiations.back().Kind ==
1883             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1884         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1885         bool isInstance = CurMethod &&
1886                           CurMethod->isInstance() &&
1887                           DC == CurMethod->getParent() && !isDefaultArgument;
1888
1889         // Give a code modification hint to insert 'this->'.
1890         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1891         // Actually quite difficult!
1892         if (getLangOpts().MSVCCompat)
1893           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1894         if (isInstance) {
1895           Diag(R.getNameLoc(), diagnostic) << Name
1896             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1897           CheckCXXThisCapture(R.getNameLoc());
1898         } else {
1899           Diag(R.getNameLoc(), diagnostic) << Name;
1900         }
1901
1902         // Do we really want to note all of these?
1903         for (NamedDecl *D : R)
1904           Diag(D->getLocation(), diag::note_dependent_var_use);
1905
1906         // Return true if we are inside a default argument instantiation
1907         // and the found name refers to an instance member function, otherwise
1908         // the function calling DiagnoseEmptyLookup will try to create an
1909         // implicit member call and this is wrong for default argument.
1910         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1911           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1912           return true;
1913         }
1914
1915         // Tell the callee to try to recover.
1916         return false;
1917       }
1918
1919       R.clear();
1920     }
1921
1922     // In Microsoft mode, if we are performing lookup from within a friend
1923     // function definition declared at class scope then we must set
1924     // DC to the lexical parent to be able to search into the parent
1925     // class.
1926     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1927         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1928         DC->getLexicalParent()->isRecord())
1929       DC = DC->getLexicalParent();
1930     else
1931       DC = DC->getParent();
1932   }
1933
1934   // We didn't find anything, so try to correct for a typo.
1935   TypoCorrection Corrected;
1936   if (S && Out) {
1937     SourceLocation TypoLoc = R.getNameLoc();
1938     assert(!ExplicitTemplateArgs &&
1939            "Diagnosing an empty lookup with explicit template args!");
1940     *Out = CorrectTypoDelayed(
1941         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1942         [=](const TypoCorrection &TC) {
1943           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1944                                         diagnostic, diagnostic_suggest);
1945         },
1946         nullptr, CTK_ErrorRecovery);
1947     if (*Out)
1948       return true;
1949   } else if (S && (Corrected =
1950                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1951                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1952     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1953     bool DroppedSpecifier =
1954         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1955     R.setLookupName(Corrected.getCorrection());
1956
1957     bool AcceptableWithRecovery = false;
1958     bool AcceptableWithoutRecovery = false;
1959     NamedDecl *ND = Corrected.getFoundDecl();
1960     if (ND) {
1961       if (Corrected.isOverloaded()) {
1962         OverloadCandidateSet OCS(R.getNameLoc(),
1963                                  OverloadCandidateSet::CSK_Normal);
1964         OverloadCandidateSet::iterator Best;
1965         for (NamedDecl *CD : Corrected) {
1966           if (FunctionTemplateDecl *FTD =
1967                    dyn_cast<FunctionTemplateDecl>(CD))
1968             AddTemplateOverloadCandidate(
1969                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1970                 Args, OCS);
1971           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1972             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1973               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1974                                    Args, OCS);
1975         }
1976         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1977         case OR_Success:
1978           ND = Best->FoundDecl;
1979           Corrected.setCorrectionDecl(ND);
1980           break;
1981         default:
1982           // FIXME: Arbitrarily pick the first declaration for the note.
1983           Corrected.setCorrectionDecl(ND);
1984           break;
1985         }
1986       }
1987       R.addDecl(ND);
1988       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1989         CXXRecordDecl *Record = nullptr;
1990         if (Corrected.getCorrectionSpecifier()) {
1991           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1992           Record = Ty->getAsCXXRecordDecl();
1993         }
1994         if (!Record)
1995           Record = cast<CXXRecordDecl>(
1996               ND->getDeclContext()->getRedeclContext());
1997         R.setNamingClass(Record);
1998       }
1999
2000       auto *UnderlyingND = ND->getUnderlyingDecl();
2001       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2002                                isa<FunctionTemplateDecl>(UnderlyingND);
2003       // FIXME: If we ended up with a typo for a type name or
2004       // Objective-C class name, we're in trouble because the parser
2005       // is in the wrong place to recover. Suggest the typo
2006       // correction, but don't make it a fix-it since we're not going
2007       // to recover well anyway.
2008       AcceptableWithoutRecovery =
2009           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2010     } else {
2011       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2012       // because we aren't able to recover.
2013       AcceptableWithoutRecovery = true;
2014     }
2015
2016     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2017       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2018                             ? diag::note_implicit_param_decl
2019                             : diag::note_previous_decl;
2020       if (SS.isEmpty())
2021         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2022                      PDiag(NoteID), AcceptableWithRecovery);
2023       else
2024         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2025                                   << Name << computeDeclContext(SS, false)
2026                                   << DroppedSpecifier << SS.getRange(),
2027                      PDiag(NoteID), AcceptableWithRecovery);
2028
2029       // Tell the callee whether to try to recover.
2030       return !AcceptableWithRecovery;
2031     }
2032   }
2033   R.clear();
2034
2035   // Emit a special diagnostic for failed member lookups.
2036   // FIXME: computing the declaration context might fail here (?)
2037   if (!SS.isEmpty()) {
2038     Diag(R.getNameLoc(), diag::err_no_member)
2039       << Name << computeDeclContext(SS, false)
2040       << SS.getRange();
2041     return true;
2042   }
2043
2044   // Give up, we can't recover.
2045   Diag(R.getNameLoc(), diagnostic) << Name;
2046   return true;
2047 }
2048
2049 /// In Microsoft mode, if we are inside a template class whose parent class has
2050 /// dependent base classes, and we can't resolve an unqualified identifier, then
2051 /// assume the identifier is a member of a dependent base class.  We can only
2052 /// recover successfully in static methods, instance methods, and other contexts
2053 /// where 'this' is available.  This doesn't precisely match MSVC's
2054 /// instantiation model, but it's close enough.
2055 static Expr *
2056 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2057                                DeclarationNameInfo &NameInfo,
2058                                SourceLocation TemplateKWLoc,
2059                                const TemplateArgumentListInfo *TemplateArgs) {
2060   // Only try to recover from lookup into dependent bases in static methods or
2061   // contexts where 'this' is available.
2062   QualType ThisType = S.getCurrentThisType();
2063   const CXXRecordDecl *RD = nullptr;
2064   if (!ThisType.isNull())
2065     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2066   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2067     RD = MD->getParent();
2068   if (!RD || !RD->hasAnyDependentBases())
2069     return nullptr;
2070
2071   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2072   // is available, suggest inserting 'this->' as a fixit.
2073   SourceLocation Loc = NameInfo.getLoc();
2074   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2075   DB << NameInfo.getName() << RD;
2076
2077   if (!ThisType.isNull()) {
2078     DB << FixItHint::CreateInsertion(Loc, "this->");
2079     return CXXDependentScopeMemberExpr::Create(
2080         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2081         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2082         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2083   }
2084
2085   // Synthesize a fake NNS that points to the derived class.  This will
2086   // perform name lookup during template instantiation.
2087   CXXScopeSpec SS;
2088   auto *NNS =
2089       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2090   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2091   return DependentScopeDeclRefExpr::Create(
2092       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2093       TemplateArgs);
2094 }
2095
2096 ExprResult
2097 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2098                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2099                         bool HasTrailingLParen, bool IsAddressOfOperand,
2100                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2101                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2102   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2103          "cannot be direct & operand and have a trailing lparen");
2104   if (SS.isInvalid())
2105     return ExprError();
2106
2107   TemplateArgumentListInfo TemplateArgsBuffer;
2108
2109   // Decompose the UnqualifiedId into the following data.
2110   DeclarationNameInfo NameInfo;
2111   const TemplateArgumentListInfo *TemplateArgs;
2112   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2113
2114   DeclarationName Name = NameInfo.getName();
2115   IdentifierInfo *II = Name.getAsIdentifierInfo();
2116   SourceLocation NameLoc = NameInfo.getLoc();
2117
2118   // C++ [temp.dep.expr]p3:
2119   //   An id-expression is type-dependent if it contains:
2120   //     -- an identifier that was declared with a dependent type,
2121   //        (note: handled after lookup)
2122   //     -- a template-id that is dependent,
2123   //        (note: handled in BuildTemplateIdExpr)
2124   //     -- a conversion-function-id that specifies a dependent type,
2125   //     -- a nested-name-specifier that contains a class-name that
2126   //        names a dependent type.
2127   // Determine whether this is a member of an unknown specialization;
2128   // we need to handle these differently.
2129   bool DependentID = false;
2130   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2131       Name.getCXXNameType()->isDependentType()) {
2132     DependentID = true;
2133   } else if (SS.isSet()) {
2134     if (DeclContext *DC = computeDeclContext(SS, false)) {
2135       if (RequireCompleteDeclContext(SS, DC))
2136         return ExprError();
2137     } else {
2138       DependentID = true;
2139     }
2140   }
2141
2142   if (DependentID)
2143     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2144                                       IsAddressOfOperand, TemplateArgs);
2145
2146   // Perform the required lookup.
2147   LookupResult R(*this, NameInfo, 
2148                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2149                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2150   if (TemplateArgs) {
2151     // Lookup the template name again to correctly establish the context in
2152     // which it was found. This is really unfortunate as we already did the
2153     // lookup to determine that it was a template name in the first place. If
2154     // this becomes a performance hit, we can work harder to preserve those
2155     // results until we get here but it's likely not worth it.
2156     bool MemberOfUnknownSpecialization;
2157     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2158                        MemberOfUnknownSpecialization);
2159     
2160     if (MemberOfUnknownSpecialization ||
2161         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2162       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2163                                         IsAddressOfOperand, TemplateArgs);
2164   } else {
2165     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2166     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2167
2168     // If the result might be in a dependent base class, this is a dependent 
2169     // id-expression.
2170     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2171       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2172                                         IsAddressOfOperand, TemplateArgs);
2173
2174     // If this reference is in an Objective-C method, then we need to do
2175     // some special Objective-C lookup, too.
2176     if (IvarLookupFollowUp) {
2177       ExprResult E(LookupInObjCMethod(R, S, II, true));
2178       if (E.isInvalid())
2179         return ExprError();
2180
2181       if (Expr *Ex = E.getAs<Expr>())
2182         return Ex;
2183     }
2184   }
2185
2186   if (R.isAmbiguous())
2187     return ExprError();
2188
2189   // This could be an implicitly declared function reference (legal in C90,
2190   // extension in C99, forbidden in C++).
2191   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2192     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2193     if (D) R.addDecl(D);
2194   }
2195
2196   // Determine whether this name might be a candidate for
2197   // argument-dependent lookup.
2198   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2199
2200   if (R.empty() && !ADL) {
2201     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2202       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2203                                                    TemplateKWLoc, TemplateArgs))
2204         return E;
2205     }
2206
2207     // Don't diagnose an empty lookup for inline assembly.
2208     if (IsInlineAsmIdentifier)
2209       return ExprError();
2210
2211     // If this name wasn't predeclared and if this is not a function
2212     // call, diagnose the problem.
2213     TypoExpr *TE = nullptr;
2214     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2215         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2216     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2217     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2218            "Typo correction callback misconfigured");
2219     if (CCC) {
2220       // Make sure the callback knows what the typo being diagnosed is.
2221       CCC->setTypoName(II);
2222       if (SS.isValid())
2223         CCC->setTypoNNS(SS.getScopeRep());
2224     }
2225     if (DiagnoseEmptyLookup(S, SS, R,
2226                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2227                             nullptr, None, &TE)) {
2228       if (TE && KeywordReplacement) {
2229         auto &State = getTypoExprState(TE);
2230         auto BestTC = State.Consumer->getNextCorrection();
2231         if (BestTC.isKeyword()) {
2232           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2233           if (State.DiagHandler)
2234             State.DiagHandler(BestTC);
2235           KeywordReplacement->startToken();
2236           KeywordReplacement->setKind(II->getTokenID());
2237           KeywordReplacement->setIdentifierInfo(II);
2238           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2239           // Clean up the state associated with the TypoExpr, since it has
2240           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2241           clearDelayedTypo(TE);
2242           // Signal that a correction to a keyword was performed by returning a
2243           // valid-but-null ExprResult.
2244           return (Expr*)nullptr;
2245         }
2246         State.Consumer->resetCorrectionStream();
2247       }
2248       return TE ? TE : ExprError();
2249     }
2250
2251     assert(!R.empty() &&
2252            "DiagnoseEmptyLookup returned false but added no results");
2253
2254     // If we found an Objective-C instance variable, let
2255     // LookupInObjCMethod build the appropriate expression to
2256     // reference the ivar.
2257     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2258       R.clear();
2259       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2260       // In a hopelessly buggy code, Objective-C instance variable
2261       // lookup fails and no expression will be built to reference it.
2262       if (!E.isInvalid() && !E.get())
2263         return ExprError();
2264       return E;
2265     }
2266   }
2267
2268   // This is guaranteed from this point on.
2269   assert(!R.empty() || ADL);
2270
2271   // Check whether this might be a C++ implicit instance member access.
2272   // C++ [class.mfct.non-static]p3:
2273   //   When an id-expression that is not part of a class member access
2274   //   syntax and not used to form a pointer to member is used in the
2275   //   body of a non-static member function of class X, if name lookup
2276   //   resolves the name in the id-expression to a non-static non-type
2277   //   member of some class C, the id-expression is transformed into a
2278   //   class member access expression using (*this) as the
2279   //   postfix-expression to the left of the . operator.
2280   //
2281   // But we don't actually need to do this for '&' operands if R
2282   // resolved to a function or overloaded function set, because the
2283   // expression is ill-formed if it actually works out to be a
2284   // non-static member function:
2285   //
2286   // C++ [expr.ref]p4:
2287   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2288   //   [t]he expression can be used only as the left-hand operand of a
2289   //   member function call.
2290   //
2291   // There are other safeguards against such uses, but it's important
2292   // to get this right here so that we don't end up making a
2293   // spuriously dependent expression if we're inside a dependent
2294   // instance method.
2295   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2296     bool MightBeImplicitMember;
2297     if (!IsAddressOfOperand)
2298       MightBeImplicitMember = true;
2299     else if (!SS.isEmpty())
2300       MightBeImplicitMember = false;
2301     else if (R.isOverloadedResult())
2302       MightBeImplicitMember = false;
2303     else if (R.isUnresolvableResult())
2304       MightBeImplicitMember = true;
2305     else
2306       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2307                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2308                               isa<MSPropertyDecl>(R.getFoundDecl());
2309
2310     if (MightBeImplicitMember)
2311       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2312                                              R, TemplateArgs, S);
2313   }
2314
2315   if (TemplateArgs || TemplateKWLoc.isValid()) {
2316
2317     // In C++1y, if this is a variable template id, then check it
2318     // in BuildTemplateIdExpr().
2319     // The single lookup result must be a variable template declaration.
2320     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2321         Id.TemplateId->Kind == TNK_Var_template) {
2322       assert(R.getAsSingle<VarTemplateDecl>() &&
2323              "There should only be one declaration found.");
2324     }
2325
2326     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2327   }
2328
2329   return BuildDeclarationNameExpr(SS, R, ADL);
2330 }
2331
2332 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2333 /// declaration name, generally during template instantiation.
2334 /// There's a large number of things which don't need to be done along
2335 /// this path.
2336 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2337     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2338     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2339   DeclContext *DC = computeDeclContext(SS, false);
2340   if (!DC)
2341     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2342                                      NameInfo, /*TemplateArgs=*/nullptr);
2343
2344   if (RequireCompleteDeclContext(SS, DC))
2345     return ExprError();
2346
2347   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2348   LookupQualifiedName(R, DC);
2349
2350   if (R.isAmbiguous())
2351     return ExprError();
2352
2353   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2354     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2355                                      NameInfo, /*TemplateArgs=*/nullptr);
2356
2357   if (R.empty()) {
2358     Diag(NameInfo.getLoc(), diag::err_no_member)
2359       << NameInfo.getName() << DC << SS.getRange();
2360     return ExprError();
2361   }
2362
2363   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2364     // Diagnose a missing typename if this resolved unambiguously to a type in
2365     // a dependent context.  If we can recover with a type, downgrade this to
2366     // a warning in Microsoft compatibility mode.
2367     unsigned DiagID = diag::err_typename_missing;
2368     if (RecoveryTSI && getLangOpts().MSVCCompat)
2369       DiagID = diag::ext_typename_missing;
2370     SourceLocation Loc = SS.getBeginLoc();
2371     auto D = Diag(Loc, DiagID);
2372     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2373       << SourceRange(Loc, NameInfo.getEndLoc());
2374
2375     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2376     // context.
2377     if (!RecoveryTSI)
2378       return ExprError();
2379
2380     // Only issue the fixit if we're prepared to recover.
2381     D << FixItHint::CreateInsertion(Loc, "typename ");
2382
2383     // Recover by pretending this was an elaborated type.
2384     QualType Ty = Context.getTypeDeclType(TD);
2385     TypeLocBuilder TLB;
2386     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2387
2388     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2389     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2390     QTL.setElaboratedKeywordLoc(SourceLocation());
2391     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2392
2393     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2394
2395     return ExprEmpty();
2396   }
2397
2398   // Defend against this resolving to an implicit member access. We usually
2399   // won't get here if this might be a legitimate a class member (we end up in
2400   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2401   // a pointer-to-member or in an unevaluated context in C++11.
2402   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2403     return BuildPossibleImplicitMemberExpr(SS,
2404                                            /*TemplateKWLoc=*/SourceLocation(),
2405                                            R, /*TemplateArgs=*/nullptr, S);
2406
2407   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2408 }
2409
2410 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2411 /// detected that we're currently inside an ObjC method.  Perform some
2412 /// additional lookup.
2413 ///
2414 /// Ideally, most of this would be done by lookup, but there's
2415 /// actually quite a lot of extra work involved.
2416 ///
2417 /// Returns a null sentinel to indicate trivial success.
2418 ExprResult
2419 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2420                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2421   SourceLocation Loc = Lookup.getNameLoc();
2422   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2423   
2424   // Check for error condition which is already reported.
2425   if (!CurMethod)
2426     return ExprError();
2427
2428   // There are two cases to handle here.  1) scoped lookup could have failed,
2429   // in which case we should look for an ivar.  2) scoped lookup could have
2430   // found a decl, but that decl is outside the current instance method (i.e.
2431   // a global variable).  In these two cases, we do a lookup for an ivar with
2432   // this name, if the lookup sucedes, we replace it our current decl.
2433
2434   // If we're in a class method, we don't normally want to look for
2435   // ivars.  But if we don't find anything else, and there's an
2436   // ivar, that's an error.
2437   bool IsClassMethod = CurMethod->isClassMethod();
2438
2439   bool LookForIvars;
2440   if (Lookup.empty())
2441     LookForIvars = true;
2442   else if (IsClassMethod)
2443     LookForIvars = false;
2444   else
2445     LookForIvars = (Lookup.isSingleResult() &&
2446                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2447   ObjCInterfaceDecl *IFace = nullptr;
2448   if (LookForIvars) {
2449     IFace = CurMethod->getClassInterface();
2450     ObjCInterfaceDecl *ClassDeclared;
2451     ObjCIvarDecl *IV = nullptr;
2452     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2453       // Diagnose using an ivar in a class method.
2454       if (IsClassMethod)
2455         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2456                          << IV->getDeclName());
2457
2458       // If we're referencing an invalid decl, just return this as a silent
2459       // error node.  The error diagnostic was already emitted on the decl.
2460       if (IV->isInvalidDecl())
2461         return ExprError();
2462
2463       // Check if referencing a field with __attribute__((deprecated)).
2464       if (DiagnoseUseOfDecl(IV, Loc))
2465         return ExprError();
2466
2467       // Diagnose the use of an ivar outside of the declaring class.
2468       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2469           !declaresSameEntity(ClassDeclared, IFace) &&
2470           !getLangOpts().DebuggerSupport)
2471         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2472
2473       // FIXME: This should use a new expr for a direct reference, don't
2474       // turn this into Self->ivar, just return a BareIVarExpr or something.
2475       IdentifierInfo &II = Context.Idents.get("self");
2476       UnqualifiedId SelfName;
2477       SelfName.setIdentifier(&II, SourceLocation());
2478       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2479       CXXScopeSpec SelfScopeSpec;
2480       SourceLocation TemplateKWLoc;
2481       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2482                                               SelfName, false, false);
2483       if (SelfExpr.isInvalid())
2484         return ExprError();
2485
2486       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2487       if (SelfExpr.isInvalid())
2488         return ExprError();
2489
2490       MarkAnyDeclReferenced(Loc, IV, true);
2491
2492       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2493       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2494           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2495         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2496
2497       ObjCIvarRefExpr *Result = new (Context)
2498           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2499                           IV->getLocation(), SelfExpr.get(), true, true);
2500
2501       if (getLangOpts().ObjCAutoRefCount) {
2502         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2503           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2504             recordUseOfEvaluatedWeak(Result);
2505         }
2506         if (CurContext->isClosure())
2507           Diag(Loc, diag::warn_implicitly_retains_self)
2508             << FixItHint::CreateInsertion(Loc, "self->");
2509       }
2510       
2511       return Result;
2512     }
2513   } else if (CurMethod->isInstanceMethod()) {
2514     // We should warn if a local variable hides an ivar.
2515     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2516       ObjCInterfaceDecl *ClassDeclared;
2517       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2518         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2519             declaresSameEntity(IFace, ClassDeclared))
2520           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2521       }
2522     }
2523   } else if (Lookup.isSingleResult() &&
2524              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2525     // If accessing a stand-alone ivar in a class method, this is an error.
2526     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2527       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2528                        << IV->getDeclName());
2529   }
2530
2531   if (Lookup.empty() && II && AllowBuiltinCreation) {
2532     // FIXME. Consolidate this with similar code in LookupName.
2533     if (unsigned BuiltinID = II->getBuiltinID()) {
2534       if (!(getLangOpts().CPlusPlus &&
2535             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2536         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2537                                            S, Lookup.isForRedeclaration(),
2538                                            Lookup.getNameLoc());
2539         if (D) Lookup.addDecl(D);
2540       }
2541     }
2542   }
2543   // Sentinel value saying that we didn't do anything special.
2544   return ExprResult((Expr *)nullptr);
2545 }
2546
2547 /// \brief Cast a base object to a member's actual type.
2548 ///
2549 /// Logically this happens in three phases:
2550 ///
2551 /// * First we cast from the base type to the naming class.
2552 ///   The naming class is the class into which we were looking
2553 ///   when we found the member;  it's the qualifier type if a
2554 ///   qualifier was provided, and otherwise it's the base type.
2555 ///
2556 /// * Next we cast from the naming class to the declaring class.
2557 ///   If the member we found was brought into a class's scope by
2558 ///   a using declaration, this is that class;  otherwise it's
2559 ///   the class declaring the member.
2560 ///
2561 /// * Finally we cast from the declaring class to the "true"
2562 ///   declaring class of the member.  This conversion does not
2563 ///   obey access control.
2564 ExprResult
2565 Sema::PerformObjectMemberConversion(Expr *From,
2566                                     NestedNameSpecifier *Qualifier,
2567                                     NamedDecl *FoundDecl,
2568                                     NamedDecl *Member) {
2569   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2570   if (!RD)
2571     return From;
2572
2573   QualType DestRecordType;
2574   QualType DestType;
2575   QualType FromRecordType;
2576   QualType FromType = From->getType();
2577   bool PointerConversions = false;
2578   if (isa<FieldDecl>(Member)) {
2579     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2580
2581     if (FromType->getAs<PointerType>()) {
2582       DestType = Context.getPointerType(DestRecordType);
2583       FromRecordType = FromType->getPointeeType();
2584       PointerConversions = true;
2585     } else {
2586       DestType = DestRecordType;
2587       FromRecordType = FromType;
2588     }
2589   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2590     if (Method->isStatic())
2591       return From;
2592
2593     DestType = Method->getThisType(Context);
2594     DestRecordType = DestType->getPointeeType();
2595
2596     if (FromType->getAs<PointerType>()) {
2597       FromRecordType = FromType->getPointeeType();
2598       PointerConversions = true;
2599     } else {
2600       FromRecordType = FromType;
2601       DestType = DestRecordType;
2602     }
2603   } else {
2604     // No conversion necessary.
2605     return From;
2606   }
2607
2608   if (DestType->isDependentType() || FromType->isDependentType())
2609     return From;
2610
2611   // If the unqualified types are the same, no conversion is necessary.
2612   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2613     return From;
2614
2615   SourceRange FromRange = From->getSourceRange();
2616   SourceLocation FromLoc = FromRange.getBegin();
2617
2618   ExprValueKind VK = From->getValueKind();
2619
2620   // C++ [class.member.lookup]p8:
2621   //   [...] Ambiguities can often be resolved by qualifying a name with its
2622   //   class name.
2623   //
2624   // If the member was a qualified name and the qualified referred to a
2625   // specific base subobject type, we'll cast to that intermediate type
2626   // first and then to the object in which the member is declared. That allows
2627   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2628   //
2629   //   class Base { public: int x; };
2630   //   class Derived1 : public Base { };
2631   //   class Derived2 : public Base { };
2632   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2633   //
2634   //   void VeryDerived::f() {
2635   //     x = 17; // error: ambiguous base subobjects
2636   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2637   //   }
2638   if (Qualifier && Qualifier->getAsType()) {
2639     QualType QType = QualType(Qualifier->getAsType(), 0);
2640     assert(QType->isRecordType() && "lookup done with non-record type");
2641
2642     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2643
2644     // In C++98, the qualifier type doesn't actually have to be a base
2645     // type of the object type, in which case we just ignore it.
2646     // Otherwise build the appropriate casts.
2647     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2648       CXXCastPath BasePath;
2649       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2650                                        FromLoc, FromRange, &BasePath))
2651         return ExprError();
2652
2653       if (PointerConversions)
2654         QType = Context.getPointerType(QType);
2655       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2656                                VK, &BasePath).get();
2657
2658       FromType = QType;
2659       FromRecordType = QRecordType;
2660
2661       // If the qualifier type was the same as the destination type,
2662       // we're done.
2663       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2664         return From;
2665     }
2666   }
2667
2668   bool IgnoreAccess = false;
2669
2670   // If we actually found the member through a using declaration, cast
2671   // down to the using declaration's type.
2672   //
2673   // Pointer equality is fine here because only one declaration of a
2674   // class ever has member declarations.
2675   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2676     assert(isa<UsingShadowDecl>(FoundDecl));
2677     QualType URecordType = Context.getTypeDeclType(
2678                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2679
2680     // We only need to do this if the naming-class to declaring-class
2681     // conversion is non-trivial.
2682     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2683       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2684       CXXCastPath BasePath;
2685       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2686                                        FromLoc, FromRange, &BasePath))
2687         return ExprError();
2688
2689       QualType UType = URecordType;
2690       if (PointerConversions)
2691         UType = Context.getPointerType(UType);
2692       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2693                                VK, &BasePath).get();
2694       FromType = UType;
2695       FromRecordType = URecordType;
2696     }
2697
2698     // We don't do access control for the conversion from the
2699     // declaring class to the true declaring class.
2700     IgnoreAccess = true;
2701   }
2702
2703   CXXCastPath BasePath;
2704   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2705                                    FromLoc, FromRange, &BasePath,
2706                                    IgnoreAccess))
2707     return ExprError();
2708
2709   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2710                            VK, &BasePath);
2711 }
2712
2713 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2714                                       const LookupResult &R,
2715                                       bool HasTrailingLParen) {
2716   // Only when used directly as the postfix-expression of a call.
2717   if (!HasTrailingLParen)
2718     return false;
2719
2720   // Never if a scope specifier was provided.
2721   if (SS.isSet())
2722     return false;
2723
2724   // Only in C++ or ObjC++.
2725   if (!getLangOpts().CPlusPlus)
2726     return false;
2727
2728   // Turn off ADL when we find certain kinds of declarations during
2729   // normal lookup:
2730   for (NamedDecl *D : R) {
2731     // C++0x [basic.lookup.argdep]p3:
2732     //     -- a declaration of a class member
2733     // Since using decls preserve this property, we check this on the
2734     // original decl.
2735     if (D->isCXXClassMember())
2736       return false;
2737
2738     // C++0x [basic.lookup.argdep]p3:
2739     //     -- a block-scope function declaration that is not a
2740     //        using-declaration
2741     // NOTE: we also trigger this for function templates (in fact, we
2742     // don't check the decl type at all, since all other decl types
2743     // turn off ADL anyway).
2744     if (isa<UsingShadowDecl>(D))
2745       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2746     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2747       return false;
2748
2749     // C++0x [basic.lookup.argdep]p3:
2750     //     -- a declaration that is neither a function or a function
2751     //        template
2752     // And also for builtin functions.
2753     if (isa<FunctionDecl>(D)) {
2754       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2755
2756       // But also builtin functions.
2757       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2758         return false;
2759     } else if (!isa<FunctionTemplateDecl>(D))
2760       return false;
2761   }
2762
2763   return true;
2764 }
2765
2766
2767 /// Diagnoses obvious problems with the use of the given declaration
2768 /// as an expression.  This is only actually called for lookups that
2769 /// were not overloaded, and it doesn't promise that the declaration
2770 /// will in fact be used.
2771 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2772   if (isa<TypedefNameDecl>(D)) {
2773     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2774     return true;
2775   }
2776
2777   if (isa<ObjCInterfaceDecl>(D)) {
2778     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2779     return true;
2780   }
2781
2782   if (isa<NamespaceDecl>(D)) {
2783     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2784     return true;
2785   }
2786
2787   return false;
2788 }
2789
2790 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2791                                           LookupResult &R, bool NeedsADL,
2792                                           bool AcceptInvalidDecl) {
2793   // If this is a single, fully-resolved result and we don't need ADL,
2794   // just build an ordinary singleton decl ref.
2795   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2796     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2797                                     R.getRepresentativeDecl(), nullptr,
2798                                     AcceptInvalidDecl);
2799
2800   // We only need to check the declaration if there's exactly one
2801   // result, because in the overloaded case the results can only be
2802   // functions and function templates.
2803   if (R.isSingleResult() &&
2804       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2805     return ExprError();
2806
2807   // Otherwise, just build an unresolved lookup expression.  Suppress
2808   // any lookup-related diagnostics; we'll hash these out later, when
2809   // we've picked a target.
2810   R.suppressDiagnostics();
2811
2812   UnresolvedLookupExpr *ULE
2813     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2814                                    SS.getWithLocInContext(Context),
2815                                    R.getLookupNameInfo(),
2816                                    NeedsADL, R.isOverloadedResult(),
2817                                    R.begin(), R.end());
2818
2819   return ULE;
2820 }
2821
2822 static void
2823 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2824                                    ValueDecl *var, DeclContext *DC);
2825
2826 /// \brief Complete semantic analysis for a reference to the given declaration.
2827 ExprResult Sema::BuildDeclarationNameExpr(
2828     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2829     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2830     bool AcceptInvalidDecl) {
2831   assert(D && "Cannot refer to a NULL declaration");
2832   assert(!isa<FunctionTemplateDecl>(D) &&
2833          "Cannot refer unambiguously to a function template");
2834
2835   SourceLocation Loc = NameInfo.getLoc();
2836   if (CheckDeclInExpr(*this, Loc, D))
2837     return ExprError();
2838
2839   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2840     // Specifically diagnose references to class templates that are missing
2841     // a template argument list.
2842     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2843                                            << Template << SS.getRange();
2844     Diag(Template->getLocation(), diag::note_template_decl_here);
2845     return ExprError();
2846   }
2847
2848   // Make sure that we're referring to a value.
2849   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2850   if (!VD) {
2851     Diag(Loc, diag::err_ref_non_value)
2852       << D << SS.getRange();
2853     Diag(D->getLocation(), diag::note_declared_at);
2854     return ExprError();
2855   }
2856
2857   // Check whether this declaration can be used. Note that we suppress
2858   // this check when we're going to perform argument-dependent lookup
2859   // on this function name, because this might not be the function
2860   // that overload resolution actually selects.
2861   if (DiagnoseUseOfDecl(VD, Loc))
2862     return ExprError();
2863
2864   // Only create DeclRefExpr's for valid Decl's.
2865   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2866     return ExprError();
2867
2868   // Handle members of anonymous structs and unions.  If we got here,
2869   // and the reference is to a class member indirect field, then this
2870   // must be the subject of a pointer-to-member expression.
2871   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2872     if (!indirectField->isCXXClassMember())
2873       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2874                                                       indirectField);
2875
2876   {
2877     QualType type = VD->getType();
2878     ExprValueKind valueKind = VK_RValue;
2879
2880     switch (D->getKind()) {
2881     // Ignore all the non-ValueDecl kinds.
2882 #define ABSTRACT_DECL(kind)
2883 #define VALUE(type, base)
2884 #define DECL(type, base) \
2885     case Decl::type:
2886 #include "clang/AST/DeclNodes.inc"
2887       llvm_unreachable("invalid value decl kind");
2888
2889     // These shouldn't make it here.
2890     case Decl::ObjCAtDefsField:
2891     case Decl::ObjCIvar:
2892       llvm_unreachable("forming non-member reference to ivar?");
2893
2894     // Enum constants are always r-values and never references.
2895     // Unresolved using declarations are dependent.
2896     case Decl::EnumConstant:
2897     case Decl::UnresolvedUsingValue:
2898     case Decl::OMPDeclareReduction:
2899       valueKind = VK_RValue;
2900       break;
2901
2902     // Fields and indirect fields that got here must be for
2903     // pointer-to-member expressions; we just call them l-values for
2904     // internal consistency, because this subexpression doesn't really
2905     // exist in the high-level semantics.
2906     case Decl::Field:
2907     case Decl::IndirectField:
2908       assert(getLangOpts().CPlusPlus &&
2909              "building reference to field in C?");
2910
2911       // These can't have reference type in well-formed programs, but
2912       // for internal consistency we do this anyway.
2913       type = type.getNonReferenceType();
2914       valueKind = VK_LValue;
2915       break;
2916
2917     // Non-type template parameters are either l-values or r-values
2918     // depending on the type.
2919     case Decl::NonTypeTemplateParm: {
2920       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2921         type = reftype->getPointeeType();
2922         valueKind = VK_LValue; // even if the parameter is an r-value reference
2923         break;
2924       }
2925
2926       // For non-references, we need to strip qualifiers just in case
2927       // the template parameter was declared as 'const int' or whatever.
2928       valueKind = VK_RValue;
2929       type = type.getUnqualifiedType();
2930       break;
2931     }
2932
2933     case Decl::Var:
2934     case Decl::VarTemplateSpecialization:
2935     case Decl::VarTemplatePartialSpecialization:
2936     case Decl::Decomposition:
2937     case Decl::OMPCapturedExpr:
2938       // In C, "extern void blah;" is valid and is an r-value.
2939       if (!getLangOpts().CPlusPlus &&
2940           !type.hasQualifiers() &&
2941           type->isVoidType()) {
2942         valueKind = VK_RValue;
2943         break;
2944       }
2945       // fallthrough
2946
2947     case Decl::ImplicitParam:
2948     case Decl::ParmVar: {
2949       // These are always l-values.
2950       valueKind = VK_LValue;
2951       type = type.getNonReferenceType();
2952
2953       // FIXME: Does the addition of const really only apply in
2954       // potentially-evaluated contexts? Since the variable isn't actually
2955       // captured in an unevaluated context, it seems that the answer is no.
2956       if (!isUnevaluatedContext()) {
2957         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2958         if (!CapturedType.isNull())
2959           type = CapturedType;
2960       }
2961       
2962       break;
2963     }
2964
2965     case Decl::Binding: {
2966       // These are always lvalues.
2967       valueKind = VK_LValue;
2968       type = type.getNonReferenceType();
2969       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2970       // decides how that's supposed to work.
2971       auto *BD = cast<BindingDecl>(VD);
2972       if (BD->getDeclContext()->isFunctionOrMethod() &&
2973           BD->getDeclContext() != CurContext)
2974         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2975       break;
2976     }
2977         
2978     case Decl::Function: {
2979       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2980         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2981           type = Context.BuiltinFnTy;
2982           valueKind = VK_RValue;
2983           break;
2984         }
2985       }
2986
2987       const FunctionType *fty = type->castAs<FunctionType>();
2988
2989       // If we're referring to a function with an __unknown_anytype
2990       // result type, make the entire expression __unknown_anytype.
2991       if (fty->getReturnType() == Context.UnknownAnyTy) {
2992         type = Context.UnknownAnyTy;
2993         valueKind = VK_RValue;
2994         break;
2995       }
2996
2997       // Functions are l-values in C++.
2998       if (getLangOpts().CPlusPlus) {
2999         valueKind = VK_LValue;
3000         break;
3001       }
3002       
3003       // C99 DR 316 says that, if a function type comes from a
3004       // function definition (without a prototype), that type is only
3005       // used for checking compatibility. Therefore, when referencing
3006       // the function, we pretend that we don't have the full function
3007       // type.
3008       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3009           isa<FunctionProtoType>(fty))
3010         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3011                                               fty->getExtInfo());
3012
3013       // Functions are r-values in C.
3014       valueKind = VK_RValue;
3015       break;
3016     }
3017
3018     case Decl::MSProperty:
3019       valueKind = VK_LValue;
3020       break;
3021
3022     case Decl::CXXMethod:
3023       // If we're referring to a method with an __unknown_anytype
3024       // result type, make the entire expression __unknown_anytype.
3025       // This should only be possible with a type written directly.
3026       if (const FunctionProtoType *proto
3027             = dyn_cast<FunctionProtoType>(VD->getType()))
3028         if (proto->getReturnType() == Context.UnknownAnyTy) {
3029           type = Context.UnknownAnyTy;
3030           valueKind = VK_RValue;
3031           break;
3032         }
3033
3034       // C++ methods are l-values if static, r-values if non-static.
3035       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3036         valueKind = VK_LValue;
3037         break;
3038       }
3039       // fallthrough
3040
3041     case Decl::CXXConversion:
3042     case Decl::CXXDestructor:
3043     case Decl::CXXConstructor:
3044       valueKind = VK_RValue;
3045       break;
3046     }
3047
3048     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3049                             TemplateArgs);
3050   }
3051 }
3052
3053 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3054                                     SmallString<32> &Target) {
3055   Target.resize(CharByteWidth * (Source.size() + 1));
3056   char *ResultPtr = &Target[0];
3057   const llvm::UTF8 *ErrorPtr;
3058   bool success =
3059       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3060   (void)success;
3061   assert(success);
3062   Target.resize(ResultPtr - &Target[0]);
3063 }
3064
3065 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3066                                      PredefinedExpr::IdentType IT) {
3067   // Pick the current block, lambda, captured statement or function.
3068   Decl *currentDecl = nullptr;
3069   if (const BlockScopeInfo *BSI = getCurBlock())
3070     currentDecl = BSI->TheDecl;
3071   else if (const LambdaScopeInfo *LSI = getCurLambda())
3072     currentDecl = LSI->CallOperator;
3073   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3074     currentDecl = CSI->TheCapturedDecl;
3075   else
3076     currentDecl = getCurFunctionOrMethodDecl();
3077
3078   if (!currentDecl) {
3079     Diag(Loc, diag::ext_predef_outside_function);
3080     currentDecl = Context.getTranslationUnitDecl();
3081   }
3082
3083   QualType ResTy;
3084   StringLiteral *SL = nullptr;
3085   if (cast<DeclContext>(currentDecl)->isDependentContext())
3086     ResTy = Context.DependentTy;
3087   else {
3088     // Pre-defined identifiers are of type char[x], where x is the length of
3089     // the string.
3090     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3091     unsigned Length = Str.length();
3092
3093     llvm::APInt LengthI(32, Length + 1);
3094     if (IT == PredefinedExpr::LFunction) {
3095       ResTy = Context.WideCharTy.withConst();
3096       SmallString<32> RawChars;
3097       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3098                               Str, RawChars);
3099       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3100                                            /*IndexTypeQuals*/ 0);
3101       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3102                                  /*Pascal*/ false, ResTy, Loc);
3103     } else {
3104       ResTy = Context.CharTy.withConst();
3105       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3106                                            /*IndexTypeQuals*/ 0);
3107       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3108                                  /*Pascal*/ false, ResTy, Loc);
3109     }
3110   }
3111
3112   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3113 }
3114
3115 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3116   PredefinedExpr::IdentType IT;
3117
3118   switch (Kind) {
3119   default: llvm_unreachable("Unknown simple primary expr!");
3120   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3121   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3122   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3123   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3124   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3125   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3126   }
3127
3128   return BuildPredefinedExpr(Loc, IT);
3129 }
3130
3131 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3132   SmallString<16> CharBuffer;
3133   bool Invalid = false;
3134   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3135   if (Invalid)
3136     return ExprError();
3137
3138   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3139                             PP, Tok.getKind());
3140   if (Literal.hadError())
3141     return ExprError();
3142
3143   QualType Ty;
3144   if (Literal.isWide())
3145     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3146   else if (Literal.isUTF16())
3147     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3148   else if (Literal.isUTF32())
3149     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3150   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3151     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3152   else
3153     Ty = Context.CharTy;  // 'x' -> char in C++
3154
3155   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3156   if (Literal.isWide())
3157     Kind = CharacterLiteral::Wide;
3158   else if (Literal.isUTF16())
3159     Kind = CharacterLiteral::UTF16;
3160   else if (Literal.isUTF32())
3161     Kind = CharacterLiteral::UTF32;
3162   else if (Literal.isUTF8())
3163     Kind = CharacterLiteral::UTF8;
3164
3165   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3166                                              Tok.getLocation());
3167
3168   if (Literal.getUDSuffix().empty())
3169     return Lit;
3170
3171   // We're building a user-defined literal.
3172   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3173   SourceLocation UDSuffixLoc =
3174     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3175
3176   // Make sure we're allowed user-defined literals here.
3177   if (!UDLScope)
3178     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3179
3180   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3181   //   operator "" X (ch)
3182   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3183                                         Lit, Tok.getLocation());
3184 }
3185
3186 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3187   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3188   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3189                                 Context.IntTy, Loc);
3190 }
3191
3192 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3193                                   QualType Ty, SourceLocation Loc) {
3194   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3195
3196   using llvm::APFloat;
3197   APFloat Val(Format);
3198
3199   APFloat::opStatus result = Literal.GetFloatValue(Val);
3200
3201   // Overflow is always an error, but underflow is only an error if
3202   // we underflowed to zero (APFloat reports denormals as underflow).
3203   if ((result & APFloat::opOverflow) ||
3204       ((result & APFloat::opUnderflow) && Val.isZero())) {
3205     unsigned diagnostic;
3206     SmallString<20> buffer;
3207     if (result & APFloat::opOverflow) {
3208       diagnostic = diag::warn_float_overflow;
3209       APFloat::getLargest(Format).toString(buffer);
3210     } else {
3211       diagnostic = diag::warn_float_underflow;
3212       APFloat::getSmallest(Format).toString(buffer);
3213     }
3214
3215     S.Diag(Loc, diagnostic)
3216       << Ty
3217       << StringRef(buffer.data(), buffer.size());
3218   }
3219
3220   bool isExact = (result == APFloat::opOK);
3221   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3222 }
3223
3224 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3225   assert(E && "Invalid expression");
3226
3227   if (E->isValueDependent())
3228     return false;
3229
3230   QualType QT = E->getType();
3231   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3232     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3233     return true;
3234   }
3235
3236   llvm::APSInt ValueAPS;
3237   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3238
3239   if (R.isInvalid())
3240     return true;
3241
3242   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3243   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3244     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3245         << ValueAPS.toString(10) << ValueIsPositive;
3246     return true;
3247   }
3248
3249   return false;
3250 }
3251
3252 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3253   // Fast path for a single digit (which is quite common).  A single digit
3254   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3255   if (Tok.getLength() == 1) {
3256     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3257     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3258   }
3259
3260   SmallString<128> SpellingBuffer;
3261   // NumericLiteralParser wants to overread by one character.  Add padding to
3262   // the buffer in case the token is copied to the buffer.  If getSpelling()
3263   // returns a StringRef to the memory buffer, it should have a null char at
3264   // the EOF, so it is also safe.
3265   SpellingBuffer.resize(Tok.getLength() + 1);
3266
3267   // Get the spelling of the token, which eliminates trigraphs, etc.
3268   bool Invalid = false;
3269   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3270   if (Invalid)
3271     return ExprError();
3272
3273   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3274   if (Literal.hadError)
3275     return ExprError();
3276
3277   if (Literal.hasUDSuffix()) {
3278     // We're building a user-defined literal.
3279     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3280     SourceLocation UDSuffixLoc =
3281       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3282
3283     // Make sure we're allowed user-defined literals here.
3284     if (!UDLScope)
3285       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3286
3287     QualType CookedTy;
3288     if (Literal.isFloatingLiteral()) {
3289       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3290       // long double, the literal is treated as a call of the form
3291       //   operator "" X (f L)
3292       CookedTy = Context.LongDoubleTy;
3293     } else {
3294       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3295       // unsigned long long, the literal is treated as a call of the form
3296       //   operator "" X (n ULL)
3297       CookedTy = Context.UnsignedLongLongTy;
3298     }
3299
3300     DeclarationName OpName =
3301       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3302     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3303     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3304
3305     SourceLocation TokLoc = Tok.getLocation();
3306
3307     // Perform literal operator lookup to determine if we're building a raw
3308     // literal or a cooked one.
3309     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3310     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3311                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3312                                   /*AllowStringTemplate*/false)) {
3313     case LOLR_Error:
3314       return ExprError();
3315
3316     case LOLR_Cooked: {
3317       Expr *Lit;
3318       if (Literal.isFloatingLiteral()) {
3319         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3320       } else {
3321         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3322         if (Literal.GetIntegerValue(ResultVal))
3323           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3324               << /* Unsigned */ 1;
3325         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3326                                      Tok.getLocation());
3327       }
3328       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3329     }
3330
3331     case LOLR_Raw: {
3332       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3333       // literal is treated as a call of the form
3334       //   operator "" X ("n")
3335       unsigned Length = Literal.getUDSuffixOffset();
3336       QualType StrTy = Context.getConstantArrayType(
3337           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3338           ArrayType::Normal, 0);
3339       Expr *Lit = StringLiteral::Create(
3340           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3341           /*Pascal*/false, StrTy, &TokLoc, 1);
3342       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3343     }
3344
3345     case LOLR_Template: {
3346       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3347       // template), L is treated as a call fo the form
3348       //   operator "" X <'c1', 'c2', ... 'ck'>()
3349       // where n is the source character sequence c1 c2 ... ck.
3350       TemplateArgumentListInfo ExplicitArgs;
3351       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3352       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3353       llvm::APSInt Value(CharBits, CharIsUnsigned);
3354       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3355         Value = TokSpelling[I];
3356         TemplateArgument Arg(Context, Value, Context.CharTy);
3357         TemplateArgumentLocInfo ArgInfo;
3358         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3359       }
3360       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3361                                       &ExplicitArgs);
3362     }
3363     case LOLR_StringTemplate:
3364       llvm_unreachable("unexpected literal operator lookup result");
3365     }
3366   }
3367
3368   Expr *Res;
3369
3370   if (Literal.isFloatingLiteral()) {
3371     QualType Ty;
3372     if (Literal.isHalf){
3373       if (getOpenCLOptions().cl_khr_fp16)
3374         Ty = Context.HalfTy;
3375       else {
3376         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3377         return ExprError();
3378       }
3379     } else if (Literal.isFloat)
3380       Ty = Context.FloatTy;
3381     else if (Literal.isLong)
3382       Ty = Context.LongDoubleTy;
3383     else if (Literal.isFloat128)
3384       Ty = Context.Float128Ty;
3385     else
3386       Ty = Context.DoubleTy;
3387
3388     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3389
3390     if (Ty == Context.DoubleTy) {
3391       if (getLangOpts().SinglePrecisionConstants) {
3392         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3393       } else if (getLangOpts().OpenCL &&
3394                  !((getLangOpts().OpenCLVersion >= 120) ||
3395                    getOpenCLOptions().cl_khr_fp64)) {
3396         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3397         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3398       }
3399     }
3400   } else if (!Literal.isIntegerLiteral()) {
3401     return ExprError();
3402   } else {
3403     QualType Ty;
3404
3405     // 'long long' is a C99 or C++11 feature.
3406     if (!getLangOpts().C99 && Literal.isLongLong) {
3407       if (getLangOpts().CPlusPlus)
3408         Diag(Tok.getLocation(),
3409              getLangOpts().CPlusPlus11 ?
3410              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3411       else
3412         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3413     }
3414
3415     // Get the value in the widest-possible width.
3416     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3417     llvm::APInt ResultVal(MaxWidth, 0);
3418
3419     if (Literal.GetIntegerValue(ResultVal)) {
3420       // If this value didn't fit into uintmax_t, error and force to ull.
3421       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3422           << /* Unsigned */ 1;
3423       Ty = Context.UnsignedLongLongTy;
3424       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3425              "long long is not intmax_t?");
3426     } else {
3427       // If this value fits into a ULL, try to figure out what else it fits into
3428       // according to the rules of C99 6.4.4.1p5.
3429
3430       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3431       // be an unsigned int.
3432       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3433
3434       // Check from smallest to largest, picking the smallest type we can.
3435       unsigned Width = 0;
3436
3437       // Microsoft specific integer suffixes are explicitly sized.
3438       if (Literal.MicrosoftInteger) {
3439         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3440           Width = 8;
3441           Ty = Context.CharTy;
3442         } else {
3443           Width = Literal.MicrosoftInteger;
3444           Ty = Context.getIntTypeForBitwidth(Width,
3445                                              /*Signed=*/!Literal.isUnsigned);
3446         }
3447       }
3448
3449       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3450         // Are int/unsigned possibilities?
3451         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3452
3453         // Does it fit in a unsigned int?
3454         if (ResultVal.isIntN(IntSize)) {
3455           // Does it fit in a signed int?
3456           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3457             Ty = Context.IntTy;
3458           else if (AllowUnsigned)
3459             Ty = Context.UnsignedIntTy;
3460           Width = IntSize;
3461         }
3462       }
3463
3464       // Are long/unsigned long possibilities?
3465       if (Ty.isNull() && !Literal.isLongLong) {
3466         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3467
3468         // Does it fit in a unsigned long?
3469         if (ResultVal.isIntN(LongSize)) {
3470           // Does it fit in a signed long?
3471           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3472             Ty = Context.LongTy;
3473           else if (AllowUnsigned)
3474             Ty = Context.UnsignedLongTy;
3475           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3476           // is compatible.
3477           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3478             const unsigned LongLongSize =
3479                 Context.getTargetInfo().getLongLongWidth();
3480             Diag(Tok.getLocation(),
3481                  getLangOpts().CPlusPlus
3482                      ? Literal.isLong
3483                            ? diag::warn_old_implicitly_unsigned_long_cxx
3484                            : /*C++98 UB*/ diag::
3485                                  ext_old_implicitly_unsigned_long_cxx
3486                      : diag::warn_old_implicitly_unsigned_long)
3487                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3488                                             : /*will be ill-formed*/ 1);
3489             Ty = Context.UnsignedLongTy;
3490           }
3491           Width = LongSize;
3492         }
3493       }
3494
3495       // Check long long if needed.
3496       if (Ty.isNull()) {
3497         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3498
3499         // Does it fit in a unsigned long long?
3500         if (ResultVal.isIntN(LongLongSize)) {
3501           // Does it fit in a signed long long?
3502           // To be compatible with MSVC, hex integer literals ending with the
3503           // LL or i64 suffix are always signed in Microsoft mode.
3504           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3505               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3506             Ty = Context.LongLongTy;
3507           else if (AllowUnsigned)
3508             Ty = Context.UnsignedLongLongTy;
3509           Width = LongLongSize;
3510         }
3511       }
3512
3513       // If we still couldn't decide a type, we probably have something that
3514       // does not fit in a signed long long, but has no U suffix.
3515       if (Ty.isNull()) {
3516         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3517         Ty = Context.UnsignedLongLongTy;
3518         Width = Context.getTargetInfo().getLongLongWidth();
3519       }
3520
3521       if (ResultVal.getBitWidth() != Width)
3522         ResultVal = ResultVal.trunc(Width);
3523     }
3524     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3525   }
3526
3527   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3528   if (Literal.isImaginary)
3529     Res = new (Context) ImaginaryLiteral(Res,
3530                                         Context.getComplexType(Res->getType()));
3531
3532   return Res;
3533 }
3534
3535 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3536   assert(E && "ActOnParenExpr() missing expr");
3537   return new (Context) ParenExpr(L, R, E);
3538 }
3539
3540 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3541                                          SourceLocation Loc,
3542                                          SourceRange ArgRange) {
3543   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3544   // scalar or vector data type argument..."
3545   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3546   // type (C99 6.2.5p18) or void.
3547   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3548     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3549       << T << ArgRange;
3550     return true;
3551   }
3552
3553   assert((T->isVoidType() || !T->isIncompleteType()) &&
3554          "Scalar types should always be complete");
3555   return false;
3556 }
3557
3558 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3559                                            SourceLocation Loc,
3560                                            SourceRange ArgRange,
3561                                            UnaryExprOrTypeTrait TraitKind) {
3562   // Invalid types must be hard errors for SFINAE in C++.
3563   if (S.LangOpts.CPlusPlus)
3564     return true;
3565
3566   // C99 6.5.3.4p1:
3567   if (T->isFunctionType() &&
3568       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3569     // sizeof(function)/alignof(function) is allowed as an extension.
3570     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3571       << TraitKind << ArgRange;
3572     return false;
3573   }
3574
3575   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3576   // this is an error (OpenCL v1.1 s6.3.k)
3577   if (T->isVoidType()) {
3578     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3579                                         : diag::ext_sizeof_alignof_void_type;
3580     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3581     return false;
3582   }
3583
3584   return true;
3585 }
3586
3587 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3588                                              SourceLocation Loc,
3589                                              SourceRange ArgRange,
3590                                              UnaryExprOrTypeTrait TraitKind) {
3591   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3592   // runtime doesn't allow it.
3593   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3594     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3595       << T << (TraitKind == UETT_SizeOf)
3596       << ArgRange;
3597     return true;
3598   }
3599
3600   return false;
3601 }
3602
3603 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3604 /// pointer type is equal to T) and emit a warning if it is.
3605 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3606                                      Expr *E) {
3607   // Don't warn if the operation changed the type.
3608   if (T != E->getType())
3609     return;
3610
3611   // Now look for array decays.
3612   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3613   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3614     return;
3615
3616   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3617                                              << ICE->getType()
3618                                              << ICE->getSubExpr()->getType();
3619 }
3620
3621 /// \brief Check the constraints on expression operands to unary type expression
3622 /// and type traits.
3623 ///
3624 /// Completes any types necessary and validates the constraints on the operand
3625 /// expression. The logic mostly mirrors the type-based overload, but may modify
3626 /// the expression as it completes the type for that expression through template
3627 /// instantiation, etc.
3628 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3629                                             UnaryExprOrTypeTrait ExprKind) {
3630   QualType ExprTy = E->getType();
3631   assert(!ExprTy->isReferenceType());
3632
3633   if (ExprKind == UETT_VecStep)
3634     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3635                                         E->getSourceRange());
3636
3637   // Whitelist some types as extensions
3638   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3639                                       E->getSourceRange(), ExprKind))
3640     return false;
3641
3642   // 'alignof' applied to an expression only requires the base element type of
3643   // the expression to be complete. 'sizeof' requires the expression's type to
3644   // be complete (and will attempt to complete it if it's an array of unknown
3645   // bound).
3646   if (ExprKind == UETT_AlignOf) {
3647     if (RequireCompleteType(E->getExprLoc(),
3648                             Context.getBaseElementType(E->getType()),
3649                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3650                             E->getSourceRange()))
3651       return true;
3652   } else {
3653     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3654                                 ExprKind, E->getSourceRange()))
3655       return true;
3656   }
3657
3658   // Completing the expression's type may have changed it.
3659   ExprTy = E->getType();
3660   assert(!ExprTy->isReferenceType());
3661
3662   if (ExprTy->isFunctionType()) {
3663     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3664       << ExprKind << E->getSourceRange();
3665     return true;
3666   }
3667
3668   // The operand for sizeof and alignof is in an unevaluated expression context,
3669   // so side effects could result in unintended consequences.
3670   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3671       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3672     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3673
3674   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3675                                        E->getSourceRange(), ExprKind))
3676     return true;
3677
3678   if (ExprKind == UETT_SizeOf) {
3679     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3680       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3681         QualType OType = PVD->getOriginalType();
3682         QualType Type = PVD->getType();
3683         if (Type->isPointerType() && OType->isArrayType()) {
3684           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3685             << Type << OType;
3686           Diag(PVD->getLocation(), diag::note_declared_at);
3687         }
3688       }
3689     }
3690
3691     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3692     // decays into a pointer and returns an unintended result. This is most
3693     // likely a typo for "sizeof(array) op x".
3694     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3695       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3696                                BO->getLHS());
3697       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3698                                BO->getRHS());
3699     }
3700   }
3701
3702   return false;
3703 }
3704
3705 /// \brief Check the constraints on operands to unary expression and type
3706 /// traits.
3707 ///
3708 /// This will complete any types necessary, and validate the various constraints
3709 /// on those operands.
3710 ///
3711 /// The UsualUnaryConversions() function is *not* called by this routine.
3712 /// C99 6.3.2.1p[2-4] all state:
3713 ///   Except when it is the operand of the sizeof operator ...
3714 ///
3715 /// C++ [expr.sizeof]p4
3716 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3717 ///   standard conversions are not applied to the operand of sizeof.
3718 ///
3719 /// This policy is followed for all of the unary trait expressions.
3720 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3721                                             SourceLocation OpLoc,
3722                                             SourceRange ExprRange,
3723                                             UnaryExprOrTypeTrait ExprKind) {
3724   if (ExprType->isDependentType())
3725     return false;
3726
3727   // C++ [expr.sizeof]p2:
3728   //     When applied to a reference or a reference type, the result
3729   //     is the size of the referenced type.
3730   // C++11 [expr.alignof]p3:
3731   //     When alignof is applied to a reference type, the result
3732   //     shall be the alignment of the referenced type.
3733   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3734     ExprType = Ref->getPointeeType();
3735
3736   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3737   //   When alignof or _Alignof is applied to an array type, the result
3738   //   is the alignment of the element type.
3739   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3740     ExprType = Context.getBaseElementType(ExprType);
3741
3742   if (ExprKind == UETT_VecStep)
3743     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3744
3745   // Whitelist some types as extensions
3746   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3747                                       ExprKind))
3748     return false;
3749
3750   if (RequireCompleteType(OpLoc, ExprType,
3751                           diag::err_sizeof_alignof_incomplete_type,
3752                           ExprKind, ExprRange))
3753     return true;
3754
3755   if (ExprType->isFunctionType()) {
3756     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3757       << ExprKind << ExprRange;
3758     return true;
3759   }
3760
3761   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3762                                        ExprKind))
3763     return true;
3764
3765   return false;
3766 }
3767
3768 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3769   E = E->IgnoreParens();
3770
3771   // Cannot know anything else if the expression is dependent.
3772   if (E->isTypeDependent())
3773     return false;
3774
3775   if (E->getObjectKind() == OK_BitField) {
3776     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3777        << 1 << E->getSourceRange();
3778     return true;
3779   }
3780
3781   ValueDecl *D = nullptr;
3782   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3783     D = DRE->getDecl();
3784   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3785     D = ME->getMemberDecl();
3786   }
3787
3788   // If it's a field, require the containing struct to have a
3789   // complete definition so that we can compute the layout.
3790   //
3791   // This can happen in C++11 onwards, either by naming the member
3792   // in a way that is not transformed into a member access expression
3793   // (in an unevaluated operand, for instance), or by naming the member
3794   // in a trailing-return-type.
3795   //
3796   // For the record, since __alignof__ on expressions is a GCC
3797   // extension, GCC seems to permit this but always gives the
3798   // nonsensical answer 0.
3799   //
3800   // We don't really need the layout here --- we could instead just
3801   // directly check for all the appropriate alignment-lowing
3802   // attributes --- but that would require duplicating a lot of
3803   // logic that just isn't worth duplicating for such a marginal
3804   // use-case.
3805   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3806     // Fast path this check, since we at least know the record has a
3807     // definition if we can find a member of it.
3808     if (!FD->getParent()->isCompleteDefinition()) {
3809       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3810         << E->getSourceRange();
3811       return true;
3812     }
3813
3814     // Otherwise, if it's a field, and the field doesn't have
3815     // reference type, then it must have a complete type (or be a
3816     // flexible array member, which we explicitly want to
3817     // white-list anyway), which makes the following checks trivial.
3818     if (!FD->getType()->isReferenceType())
3819       return false;
3820   }
3821
3822   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3823 }
3824
3825 bool Sema::CheckVecStepExpr(Expr *E) {
3826   E = E->IgnoreParens();
3827
3828   // Cannot know anything else if the expression is dependent.
3829   if (E->isTypeDependent())
3830     return false;
3831
3832   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3833 }
3834
3835 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3836                                         CapturingScopeInfo *CSI) {
3837   assert(T->isVariablyModifiedType());
3838   assert(CSI != nullptr);
3839
3840   // We're going to walk down into the type and look for VLA expressions.
3841   do {
3842     const Type *Ty = T.getTypePtr();
3843     switch (Ty->getTypeClass()) {
3844 #define TYPE(Class, Base)
3845 #define ABSTRACT_TYPE(Class, Base)
3846 #define NON_CANONICAL_TYPE(Class, Base)
3847 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3848 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3849 #include "clang/AST/TypeNodes.def"
3850       T = QualType();
3851       break;
3852     // These types are never variably-modified.
3853     case Type::Builtin:
3854     case Type::Complex:
3855     case Type::Vector:
3856     case Type::ExtVector:
3857     case Type::Record:
3858     case Type::Enum:
3859     case Type::Elaborated:
3860     case Type::TemplateSpecialization:
3861     case Type::ObjCObject:
3862     case Type::ObjCInterface:
3863     case Type::ObjCObjectPointer:
3864     case Type::ObjCTypeParam:
3865     case Type::Pipe:
3866       llvm_unreachable("type class is never variably-modified!");
3867     case Type::Adjusted:
3868       T = cast<AdjustedType>(Ty)->getOriginalType();
3869       break;
3870     case Type::Decayed:
3871       T = cast<DecayedType>(Ty)->getPointeeType();
3872       break;
3873     case Type::Pointer:
3874       T = cast<PointerType>(Ty)->getPointeeType();
3875       break;
3876     case Type::BlockPointer:
3877       T = cast<BlockPointerType>(Ty)->getPointeeType();
3878       break;
3879     case Type::LValueReference:
3880     case Type::RValueReference:
3881       T = cast<ReferenceType>(Ty)->getPointeeType();
3882       break;
3883     case Type::MemberPointer:
3884       T = cast<MemberPointerType>(Ty)->getPointeeType();
3885       break;
3886     case Type::ConstantArray:
3887     case Type::IncompleteArray:
3888       // Losing element qualification here is fine.
3889       T = cast<ArrayType>(Ty)->getElementType();
3890       break;
3891     case Type::VariableArray: {
3892       // Losing element qualification here is fine.
3893       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3894
3895       // Unknown size indication requires no size computation.
3896       // Otherwise, evaluate and record it.
3897       if (auto Size = VAT->getSizeExpr()) {
3898         if (!CSI->isVLATypeCaptured(VAT)) {
3899           RecordDecl *CapRecord = nullptr;
3900           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3901             CapRecord = LSI->Lambda;
3902           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3903             CapRecord = CRSI->TheRecordDecl;
3904           }
3905           if (CapRecord) {
3906             auto ExprLoc = Size->getExprLoc();
3907             auto SizeType = Context.getSizeType();
3908             // Build the non-static data member.
3909             auto Field =
3910                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3911                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3912                                   /*BW*/ nullptr, /*Mutable*/ false,
3913                                   /*InitStyle*/ ICIS_NoInit);
3914             Field->setImplicit(true);
3915             Field->setAccess(AS_private);
3916             Field->setCapturedVLAType(VAT);
3917             CapRecord->addDecl(Field);
3918
3919             CSI->addVLATypeCapture(ExprLoc, SizeType);
3920           }
3921         }
3922       }
3923       T = VAT->getElementType();
3924       break;
3925     }
3926     case Type::FunctionProto:
3927     case Type::FunctionNoProto:
3928       T = cast<FunctionType>(Ty)->getReturnType();
3929       break;
3930     case Type::Paren:
3931     case Type::TypeOf:
3932     case Type::UnaryTransform:
3933     case Type::Attributed:
3934     case Type::SubstTemplateTypeParm:
3935     case Type::PackExpansion:
3936       // Keep walking after single level desugaring.
3937       T = T.getSingleStepDesugaredType(Context);
3938       break;
3939     case Type::Typedef:
3940       T = cast<TypedefType>(Ty)->desugar();
3941       break;
3942     case Type::Decltype:
3943       T = cast<DecltypeType>(Ty)->desugar();
3944       break;
3945     case Type::Auto:
3946       T = cast<AutoType>(Ty)->getDeducedType();
3947       break;
3948     case Type::TypeOfExpr:
3949       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3950       break;
3951     case Type::Atomic:
3952       T = cast<AtomicType>(Ty)->getValueType();
3953       break;
3954     }
3955   } while (!T.isNull() && T->isVariablyModifiedType());
3956 }
3957
3958 /// \brief Build a sizeof or alignof expression given a type operand.
3959 ExprResult
3960 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3961                                      SourceLocation OpLoc,
3962                                      UnaryExprOrTypeTrait ExprKind,
3963                                      SourceRange R) {
3964   if (!TInfo)
3965     return ExprError();
3966
3967   QualType T = TInfo->getType();
3968
3969   if (!T->isDependentType() &&
3970       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3971     return ExprError();
3972
3973   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3974     if (auto *TT = T->getAs<TypedefType>()) {
3975       for (auto I = FunctionScopes.rbegin(),
3976                 E = std::prev(FunctionScopes.rend());
3977            I != E; ++I) {
3978         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3979         if (CSI == nullptr)
3980           break;
3981         DeclContext *DC = nullptr;
3982         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3983           DC = LSI->CallOperator;
3984         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3985           DC = CRSI->TheCapturedDecl;
3986         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3987           DC = BSI->TheDecl;
3988         if (DC) {
3989           if (DC->containsDecl(TT->getDecl()))
3990             break;
3991           captureVariablyModifiedType(Context, T, CSI);
3992         }
3993       }
3994     }
3995   }
3996
3997   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3998   return new (Context) UnaryExprOrTypeTraitExpr(
3999       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4000 }
4001
4002 /// \brief Build a sizeof or alignof expression given an expression
4003 /// operand.
4004 ExprResult
4005 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4006                                      UnaryExprOrTypeTrait ExprKind) {
4007   ExprResult PE = CheckPlaceholderExpr(E);
4008   if (PE.isInvalid()) 
4009     return ExprError();
4010
4011   E = PE.get();
4012   
4013   // Verify that the operand is valid.
4014   bool isInvalid = false;
4015   if (E->isTypeDependent()) {
4016     // Delay type-checking for type-dependent expressions.
4017   } else if (ExprKind == UETT_AlignOf) {
4018     isInvalid = CheckAlignOfExpr(*this, E);
4019   } else if (ExprKind == UETT_VecStep) {
4020     isInvalid = CheckVecStepExpr(E);
4021   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4022       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4023       isInvalid = true;
4024   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4025     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4026     isInvalid = true;
4027   } else {
4028     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4029   }
4030
4031   if (isInvalid)
4032     return ExprError();
4033
4034   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4035     PE = TransformToPotentiallyEvaluated(E);
4036     if (PE.isInvalid()) return ExprError();
4037     E = PE.get();
4038   }
4039
4040   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4041   return new (Context) UnaryExprOrTypeTraitExpr(
4042       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4043 }
4044
4045 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4046 /// expr and the same for @c alignof and @c __alignof
4047 /// Note that the ArgRange is invalid if isType is false.
4048 ExprResult
4049 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4050                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4051                                     void *TyOrEx, SourceRange ArgRange) {
4052   // If error parsing type, ignore.
4053   if (!TyOrEx) return ExprError();
4054
4055   if (IsType) {
4056     TypeSourceInfo *TInfo;
4057     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4058     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4059   }
4060
4061   Expr *ArgEx = (Expr *)TyOrEx;
4062   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4063   return Result;
4064 }
4065
4066 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4067                                      bool IsReal) {
4068   if (V.get()->isTypeDependent())
4069     return S.Context.DependentTy;
4070
4071   // _Real and _Imag are only l-values for normal l-values.
4072   if (V.get()->getObjectKind() != OK_Ordinary) {
4073     V = S.DefaultLvalueConversion(V.get());
4074     if (V.isInvalid())
4075       return QualType();
4076   }
4077
4078   // These operators return the element type of a complex type.
4079   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4080     return CT->getElementType();
4081
4082   // Otherwise they pass through real integer and floating point types here.
4083   if (V.get()->getType()->isArithmeticType())
4084     return V.get()->getType();
4085
4086   // Test for placeholders.
4087   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4088   if (PR.isInvalid()) return QualType();
4089   if (PR.get() != V.get()) {
4090     V = PR;
4091     return CheckRealImagOperand(S, V, Loc, IsReal);
4092   }
4093
4094   // Reject anything else.
4095   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4096     << (IsReal ? "__real" : "__imag");
4097   return QualType();
4098 }
4099
4100
4101
4102 ExprResult
4103 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4104                           tok::TokenKind Kind, Expr *Input) {
4105   UnaryOperatorKind Opc;
4106   switch (Kind) {
4107   default: llvm_unreachable("Unknown unary op!");
4108   case tok::plusplus:   Opc = UO_PostInc; break;
4109   case tok::minusminus: Opc = UO_PostDec; break;
4110   }
4111
4112   // Since this might is a postfix expression, get rid of ParenListExprs.
4113   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4114   if (Result.isInvalid()) return ExprError();
4115   Input = Result.get();
4116
4117   return BuildUnaryOp(S, OpLoc, Opc, Input);
4118 }
4119
4120 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4121 ///
4122 /// \return true on error
4123 static bool checkArithmeticOnObjCPointer(Sema &S,
4124                                          SourceLocation opLoc,
4125                                          Expr *op) {
4126   assert(op->getType()->isObjCObjectPointerType());
4127   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4128       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4129     return false;
4130
4131   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4132     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4133     << op->getSourceRange();
4134   return true;
4135 }
4136
4137 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4138   auto *BaseNoParens = Base->IgnoreParens();
4139   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4140     return MSProp->getPropertyDecl()->getType()->isArrayType();
4141   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4142 }
4143
4144 ExprResult
4145 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4146                               Expr *idx, SourceLocation rbLoc) {
4147   if (base && !base->getType().isNull() &&
4148       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4149     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4150                                     /*Length=*/nullptr, rbLoc);
4151
4152   // Since this might be a postfix expression, get rid of ParenListExprs.
4153   if (isa<ParenListExpr>(base)) {
4154     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4155     if (result.isInvalid()) return ExprError();
4156     base = result.get();
4157   }
4158
4159   // Handle any non-overload placeholder types in the base and index
4160   // expressions.  We can't handle overloads here because the other
4161   // operand might be an overloadable type, in which case the overload
4162   // resolution for the operator overload should get the first crack
4163   // at the overload.
4164   bool IsMSPropertySubscript = false;
4165   if (base->getType()->isNonOverloadPlaceholderType()) {
4166     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4167     if (!IsMSPropertySubscript) {
4168       ExprResult result = CheckPlaceholderExpr(base);
4169       if (result.isInvalid())
4170         return ExprError();
4171       base = result.get();
4172     }
4173   }
4174   if (idx->getType()->isNonOverloadPlaceholderType()) {
4175     ExprResult result = CheckPlaceholderExpr(idx);
4176     if (result.isInvalid()) return ExprError();
4177     idx = result.get();
4178   }
4179
4180   // Build an unanalyzed expression if either operand is type-dependent.
4181   if (getLangOpts().CPlusPlus &&
4182       (base->isTypeDependent() || idx->isTypeDependent())) {
4183     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4184                                             VK_LValue, OK_Ordinary, rbLoc);
4185   }
4186
4187   // MSDN, property (C++)
4188   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4189   // This attribute can also be used in the declaration of an empty array in a
4190   // class or structure definition. For example:
4191   // __declspec(property(get=GetX, put=PutX)) int x[];
4192   // The above statement indicates that x[] can be used with one or more array
4193   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4194   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4195   if (IsMSPropertySubscript) {
4196     // Build MS property subscript expression if base is MS property reference
4197     // or MS property subscript.
4198     return new (Context) MSPropertySubscriptExpr(
4199         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4200   }
4201
4202   // Use C++ overloaded-operator rules if either operand has record
4203   // type.  The spec says to do this if either type is *overloadable*,
4204   // but enum types can't declare subscript operators or conversion
4205   // operators, so there's nothing interesting for overload resolution
4206   // to do if there aren't any record types involved.
4207   //
4208   // ObjC pointers have their own subscripting logic that is not tied
4209   // to overload resolution and so should not take this path.
4210   if (getLangOpts().CPlusPlus &&
4211       (base->getType()->isRecordType() ||
4212        (!base->getType()->isObjCObjectPointerType() &&
4213         idx->getType()->isRecordType()))) {
4214     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4215   }
4216
4217   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4218 }
4219
4220 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4221                                           Expr *LowerBound,
4222                                           SourceLocation ColonLoc, Expr *Length,
4223                                           SourceLocation RBLoc) {
4224   if (Base->getType()->isPlaceholderType() &&
4225       !Base->getType()->isSpecificPlaceholderType(
4226           BuiltinType::OMPArraySection)) {
4227     ExprResult Result = CheckPlaceholderExpr(Base);
4228     if (Result.isInvalid())
4229       return ExprError();
4230     Base = Result.get();
4231   }
4232   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4233     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4234     if (Result.isInvalid())
4235       return ExprError();
4236     Result = DefaultLvalueConversion(Result.get());
4237     if (Result.isInvalid())
4238       return ExprError();
4239     LowerBound = Result.get();
4240   }
4241   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4242     ExprResult Result = CheckPlaceholderExpr(Length);
4243     if (Result.isInvalid())
4244       return ExprError();
4245     Result = DefaultLvalueConversion(Result.get());
4246     if (Result.isInvalid())
4247       return ExprError();
4248     Length = Result.get();
4249   }
4250
4251   // Build an unanalyzed expression if either operand is type-dependent.
4252   if (Base->isTypeDependent() ||
4253       (LowerBound &&
4254        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4255       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4256     return new (Context)
4257         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4258                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4259   }
4260
4261   // Perform default conversions.
4262   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4263   QualType ResultTy;
4264   if (OriginalTy->isAnyPointerType()) {
4265     ResultTy = OriginalTy->getPointeeType();
4266   } else if (OriginalTy->isArrayType()) {
4267     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4268   } else {
4269     return ExprError(
4270         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4271         << Base->getSourceRange());
4272   }
4273   // C99 6.5.2.1p1
4274   if (LowerBound) {
4275     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4276                                                       LowerBound);
4277     if (Res.isInvalid())
4278       return ExprError(Diag(LowerBound->getExprLoc(),
4279                             diag::err_omp_typecheck_section_not_integer)
4280                        << 0 << LowerBound->getSourceRange());
4281     LowerBound = Res.get();
4282
4283     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4284         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4285       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4286           << 0 << LowerBound->getSourceRange();
4287   }
4288   if (Length) {
4289     auto Res =
4290         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4291     if (Res.isInvalid())
4292       return ExprError(Diag(Length->getExprLoc(),
4293                             diag::err_omp_typecheck_section_not_integer)
4294                        << 1 << Length->getSourceRange());
4295     Length = Res.get();
4296
4297     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4298         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4299       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4300           << 1 << Length->getSourceRange();
4301   }
4302
4303   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4304   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4305   // type. Note that functions are not objects, and that (in C99 parlance)
4306   // incomplete types are not object types.
4307   if (ResultTy->isFunctionType()) {
4308     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4309         << ResultTy << Base->getSourceRange();
4310     return ExprError();
4311   }
4312
4313   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4314                           diag::err_omp_section_incomplete_type, Base))
4315     return ExprError();
4316
4317   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4318     llvm::APSInt LowerBoundValue;
4319     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4320       // OpenMP 4.5, [2.4 Array Sections]
4321       // The array section must be a subset of the original array.
4322       if (LowerBoundValue.isNegative()) {
4323         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4324             << LowerBound->getSourceRange();
4325         return ExprError();
4326       }
4327     }
4328   }
4329
4330   if (Length) {
4331     llvm::APSInt LengthValue;
4332     if (Length->EvaluateAsInt(LengthValue, Context)) {
4333       // OpenMP 4.5, [2.4 Array Sections]
4334       // The length must evaluate to non-negative integers.
4335       if (LengthValue.isNegative()) {
4336         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4337             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4338             << Length->getSourceRange();
4339         return ExprError();
4340       }
4341     }
4342   } else if (ColonLoc.isValid() &&
4343              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4344                                       !OriginalTy->isVariableArrayType()))) {
4345     // OpenMP 4.5, [2.4 Array Sections]
4346     // When the size of the array dimension is not known, the length must be
4347     // specified explicitly.
4348     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4349         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4350     return ExprError();
4351   }
4352
4353   if (!Base->getType()->isSpecificPlaceholderType(
4354           BuiltinType::OMPArraySection)) {
4355     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4356     if (Result.isInvalid())
4357       return ExprError();
4358     Base = Result.get();
4359   }
4360   return new (Context)
4361       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4362                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4363 }
4364
4365 ExprResult
4366 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4367                                       Expr *Idx, SourceLocation RLoc) {
4368   Expr *LHSExp = Base;
4369   Expr *RHSExp = Idx;
4370
4371   // Perform default conversions.
4372   if (!LHSExp->getType()->getAs<VectorType>()) {
4373     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4374     if (Result.isInvalid())
4375       return ExprError();
4376     LHSExp = Result.get();
4377   }
4378   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4379   if (Result.isInvalid())
4380     return ExprError();
4381   RHSExp = Result.get();
4382
4383   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4384   ExprValueKind VK = VK_LValue;
4385   ExprObjectKind OK = OK_Ordinary;
4386
4387   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4388   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4389   // in the subscript position. As a result, we need to derive the array base
4390   // and index from the expression types.
4391   Expr *BaseExpr, *IndexExpr;
4392   QualType ResultType;
4393   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4394     BaseExpr = LHSExp;
4395     IndexExpr = RHSExp;
4396     ResultType = Context.DependentTy;
4397   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4398     BaseExpr = LHSExp;
4399     IndexExpr = RHSExp;
4400     ResultType = PTy->getPointeeType();
4401   } else if (const ObjCObjectPointerType *PTy =
4402                LHSTy->getAs<ObjCObjectPointerType>()) {
4403     BaseExpr = LHSExp;
4404     IndexExpr = RHSExp;
4405
4406     // Use custom logic if this should be the pseudo-object subscript
4407     // expression.
4408     if (!LangOpts.isSubscriptPointerArithmetic())
4409       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4410                                           nullptr);
4411
4412     ResultType = PTy->getPointeeType();
4413   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4414      // Handle the uncommon case of "123[Ptr]".
4415     BaseExpr = RHSExp;
4416     IndexExpr = LHSExp;
4417     ResultType = PTy->getPointeeType();
4418   } else if (const ObjCObjectPointerType *PTy =
4419                RHSTy->getAs<ObjCObjectPointerType>()) {
4420      // Handle the uncommon case of "123[Ptr]".
4421     BaseExpr = RHSExp;
4422     IndexExpr = LHSExp;
4423     ResultType = PTy->getPointeeType();
4424     if (!LangOpts.isSubscriptPointerArithmetic()) {
4425       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4426         << ResultType << BaseExpr->getSourceRange();
4427       return ExprError();
4428     }
4429   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4430     BaseExpr = LHSExp;    // vectors: V[123]
4431     IndexExpr = RHSExp;
4432     VK = LHSExp->getValueKind();
4433     if (VK != VK_RValue)
4434       OK = OK_VectorComponent;
4435
4436     // FIXME: need to deal with const...
4437     ResultType = VTy->getElementType();
4438   } else if (LHSTy->isArrayType()) {
4439     // If we see an array that wasn't promoted by
4440     // DefaultFunctionArrayLvalueConversion, it must be an array that
4441     // wasn't promoted because of the C90 rule that doesn't
4442     // allow promoting non-lvalue arrays.  Warn, then
4443     // force the promotion here.
4444     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4445         LHSExp->getSourceRange();
4446     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4447                                CK_ArrayToPointerDecay).get();
4448     LHSTy = LHSExp->getType();
4449
4450     BaseExpr = LHSExp;
4451     IndexExpr = RHSExp;
4452     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4453   } else if (RHSTy->isArrayType()) {
4454     // Same as previous, except for 123[f().a] case
4455     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4456         RHSExp->getSourceRange();
4457     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4458                                CK_ArrayToPointerDecay).get();
4459     RHSTy = RHSExp->getType();
4460
4461     BaseExpr = RHSExp;
4462     IndexExpr = LHSExp;
4463     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4464   } else {
4465     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4466        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4467   }
4468   // C99 6.5.2.1p1
4469   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4470     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4471                      << IndexExpr->getSourceRange());
4472
4473   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4474        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4475          && !IndexExpr->isTypeDependent())
4476     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4477
4478   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4479   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4480   // type. Note that Functions are not objects, and that (in C99 parlance)
4481   // incomplete types are not object types.
4482   if (ResultType->isFunctionType()) {
4483     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4484       << ResultType << BaseExpr->getSourceRange();
4485     return ExprError();
4486   }
4487
4488   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4489     // GNU extension: subscripting on pointer to void
4490     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4491       << BaseExpr->getSourceRange();
4492
4493     // C forbids expressions of unqualified void type from being l-values.
4494     // See IsCForbiddenLValueType.
4495     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4496   } else if (!ResultType->isDependentType() &&
4497       RequireCompleteType(LLoc, ResultType,
4498                           diag::err_subscript_incomplete_type, BaseExpr))
4499     return ExprError();
4500
4501   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4502          !ResultType.isCForbiddenLValueType());
4503
4504   return new (Context)
4505       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4506 }
4507
4508 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4509                                         FunctionDecl *FD,
4510                                         ParmVarDecl *Param) {
4511   if (Param->hasUnparsedDefaultArg()) {
4512     Diag(CallLoc,
4513          diag::err_use_of_default_argument_to_function_declared_later) <<
4514       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4515     Diag(UnparsedDefaultArgLocs[Param],
4516          diag::note_default_argument_declared_here);
4517     return ExprError();
4518   }
4519   
4520   if (Param->hasUninstantiatedDefaultArg()) {
4521     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4522
4523     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4524                                                  Param);
4525
4526     // Instantiate the expression.
4527     MultiLevelTemplateArgumentList MutiLevelArgList
4528       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4529
4530     InstantiatingTemplate Inst(*this, CallLoc, Param,
4531                                MutiLevelArgList.getInnermost());
4532     if (Inst.isInvalid())
4533       return ExprError();
4534     if (Inst.isAlreadyInstantiating()) {
4535       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4536       Param->setInvalidDecl();
4537       return ExprError();
4538     }
4539
4540     ExprResult Result;
4541     {
4542       // C++ [dcl.fct.default]p5:
4543       //   The names in the [default argument] expression are bound, and
4544       //   the semantic constraints are checked, at the point where the
4545       //   default argument expression appears.
4546       ContextRAII SavedContext(*this, FD);
4547       LocalInstantiationScope Local(*this);
4548       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4549                                 /*DirectInit*/false);
4550     }
4551     if (Result.isInvalid())
4552       return ExprError();
4553
4554     // Check the expression as an initializer for the parameter.
4555     InitializedEntity Entity
4556       = InitializedEntity::InitializeParameter(Context, Param);
4557     InitializationKind Kind
4558       = InitializationKind::CreateCopy(Param->getLocation(),
4559              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4560     Expr *ResultE = Result.getAs<Expr>();
4561
4562     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4563     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4564     if (Result.isInvalid())
4565       return ExprError();
4566
4567     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4568                                  Param->getOuterLocStart());
4569     if (Result.isInvalid())
4570       return ExprError();
4571
4572     // Remember the instantiated default argument.
4573     Param->setDefaultArg(Result.getAs<Expr>());
4574     if (ASTMutationListener *L = getASTMutationListener()) {
4575       L->DefaultArgumentInstantiated(Param);
4576     }
4577   }
4578
4579   // If the default argument expression is not set yet, we are building it now.
4580   if (!Param->hasInit()) {
4581     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4582     Param->setInvalidDecl();
4583     return ExprError();
4584   }
4585
4586   // If the default expression creates temporaries, we need to
4587   // push them to the current stack of expression temporaries so they'll
4588   // be properly destroyed.
4589   // FIXME: We should really be rebuilding the default argument with new
4590   // bound temporaries; see the comment in PR5810.
4591   // We don't need to do that with block decls, though, because
4592   // blocks in default argument expression can never capture anything.
4593   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4594     // Set the "needs cleanups" bit regardless of whether there are
4595     // any explicit objects.
4596     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4597
4598     // Append all the objects to the cleanup list.  Right now, this
4599     // should always be a no-op, because blocks in default argument
4600     // expressions should never be able to capture anything.
4601     assert(!Init->getNumObjects() &&
4602            "default argument expression has capturing blocks?");
4603   }
4604
4605   // We already type-checked the argument, so we know it works. 
4606   // Just mark all of the declarations in this potentially-evaluated expression
4607   // as being "referenced".
4608   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4609                                    /*SkipLocalVariables=*/true);
4610   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4611 }
4612
4613
4614 Sema::VariadicCallType
4615 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4616                           Expr *Fn) {
4617   if (Proto && Proto->isVariadic()) {
4618     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4619       return VariadicConstructor;
4620     else if (Fn && Fn->getType()->isBlockPointerType())
4621       return VariadicBlock;
4622     else if (FDecl) {
4623       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4624         if (Method->isInstance())
4625           return VariadicMethod;
4626     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4627       return VariadicMethod;
4628     return VariadicFunction;
4629   }
4630   return VariadicDoesNotApply;
4631 }
4632
4633 namespace {
4634 class FunctionCallCCC : public FunctionCallFilterCCC {
4635 public:
4636   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4637                   unsigned NumArgs, MemberExpr *ME)
4638       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4639         FunctionName(FuncName) {}
4640
4641   bool ValidateCandidate(const TypoCorrection &candidate) override {
4642     if (!candidate.getCorrectionSpecifier() ||
4643         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4644       return false;
4645     }
4646
4647     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4648   }
4649
4650 private:
4651   const IdentifierInfo *const FunctionName;
4652 };
4653 }
4654
4655 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4656                                                FunctionDecl *FDecl,
4657                                                ArrayRef<Expr *> Args) {
4658   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4659   DeclarationName FuncName = FDecl->getDeclName();
4660   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4661
4662   if (TypoCorrection Corrected = S.CorrectTypo(
4663           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4664           S.getScopeForContext(S.CurContext), nullptr,
4665           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4666                                              Args.size(), ME),
4667           Sema::CTK_ErrorRecovery)) {
4668     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4669       if (Corrected.isOverloaded()) {
4670         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4671         OverloadCandidateSet::iterator Best;
4672         for (NamedDecl *CD : Corrected) {
4673           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4674             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4675                                    OCS);
4676         }
4677         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4678         case OR_Success:
4679           ND = Best->FoundDecl;
4680           Corrected.setCorrectionDecl(ND);
4681           break;
4682         default:
4683           break;
4684         }
4685       }
4686       ND = ND->getUnderlyingDecl();
4687       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4688         return Corrected;
4689     }
4690   }
4691   return TypoCorrection();
4692 }
4693
4694 /// ConvertArgumentsForCall - Converts the arguments specified in
4695 /// Args/NumArgs to the parameter types of the function FDecl with
4696 /// function prototype Proto. Call is the call expression itself, and
4697 /// Fn is the function expression. For a C++ member function, this
4698 /// routine does not attempt to convert the object argument. Returns
4699 /// true if the call is ill-formed.
4700 bool
4701 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4702                               FunctionDecl *FDecl,
4703                               const FunctionProtoType *Proto,
4704                               ArrayRef<Expr *> Args,
4705                               SourceLocation RParenLoc,
4706                               bool IsExecConfig) {
4707   // Bail out early if calling a builtin with custom typechecking.
4708   if (FDecl)
4709     if (unsigned ID = FDecl->getBuiltinID())
4710       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4711         return false;
4712
4713   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4714   // assignment, to the types of the corresponding parameter, ...
4715   unsigned NumParams = Proto->getNumParams();
4716   bool Invalid = false;
4717   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4718   unsigned FnKind = Fn->getType()->isBlockPointerType()
4719                        ? 1 /* block */
4720                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4721                                        : 0 /* function */);
4722
4723   // If too few arguments are available (and we don't have default
4724   // arguments for the remaining parameters), don't make the call.
4725   if (Args.size() < NumParams) {
4726     if (Args.size() < MinArgs) {
4727       TypoCorrection TC;
4728       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4729         unsigned diag_id =
4730             MinArgs == NumParams && !Proto->isVariadic()
4731                 ? diag::err_typecheck_call_too_few_args_suggest
4732                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4733         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4734                                         << static_cast<unsigned>(Args.size())
4735                                         << TC.getCorrectionRange());
4736       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4737         Diag(RParenLoc,
4738              MinArgs == NumParams && !Proto->isVariadic()
4739                  ? diag::err_typecheck_call_too_few_args_one
4740                  : diag::err_typecheck_call_too_few_args_at_least_one)
4741             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4742       else
4743         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4744                             ? diag::err_typecheck_call_too_few_args
4745                             : diag::err_typecheck_call_too_few_args_at_least)
4746             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4747             << Fn->getSourceRange();
4748
4749       // Emit the location of the prototype.
4750       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4751         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4752           << FDecl;
4753
4754       return true;
4755     }
4756     Call->setNumArgs(Context, NumParams);
4757   }
4758
4759   // If too many are passed and not variadic, error on the extras and drop
4760   // them.
4761   if (Args.size() > NumParams) {
4762     if (!Proto->isVariadic()) {
4763       TypoCorrection TC;
4764       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4765         unsigned diag_id =
4766             MinArgs == NumParams && !Proto->isVariadic()
4767                 ? diag::err_typecheck_call_too_many_args_suggest
4768                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4769         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4770                                         << static_cast<unsigned>(Args.size())
4771                                         << TC.getCorrectionRange());
4772       } else if (NumParams == 1 && FDecl &&
4773                  FDecl->getParamDecl(0)->getDeclName())
4774         Diag(Args[NumParams]->getLocStart(),
4775              MinArgs == NumParams
4776                  ? diag::err_typecheck_call_too_many_args_one
4777                  : diag::err_typecheck_call_too_many_args_at_most_one)
4778             << FnKind << FDecl->getParamDecl(0)
4779             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4780             << SourceRange(Args[NumParams]->getLocStart(),
4781                            Args.back()->getLocEnd());
4782       else
4783         Diag(Args[NumParams]->getLocStart(),
4784              MinArgs == NumParams
4785                  ? diag::err_typecheck_call_too_many_args
4786                  : diag::err_typecheck_call_too_many_args_at_most)
4787             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4788             << Fn->getSourceRange()
4789             << SourceRange(Args[NumParams]->getLocStart(),
4790                            Args.back()->getLocEnd());
4791
4792       // Emit the location of the prototype.
4793       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4794         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4795           << FDecl;
4796       
4797       // This deletes the extra arguments.
4798       Call->setNumArgs(Context, NumParams);
4799       return true;
4800     }
4801   }
4802   SmallVector<Expr *, 8> AllArgs;
4803   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4804   
4805   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4806                                    Proto, 0, Args, AllArgs, CallType);
4807   if (Invalid)
4808     return true;
4809   unsigned TotalNumArgs = AllArgs.size();
4810   for (unsigned i = 0; i < TotalNumArgs; ++i)
4811     Call->setArg(i, AllArgs[i]);
4812
4813   return false;
4814 }
4815
4816 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4817                                   const FunctionProtoType *Proto,
4818                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4819                                   SmallVectorImpl<Expr *> &AllArgs,
4820                                   VariadicCallType CallType, bool AllowExplicit,
4821                                   bool IsListInitialization) {
4822   unsigned NumParams = Proto->getNumParams();
4823   bool Invalid = false;
4824   size_t ArgIx = 0;
4825   // Continue to check argument types (even if we have too few/many args).
4826   for (unsigned i = FirstParam; i < NumParams; i++) {
4827     QualType ProtoArgType = Proto->getParamType(i);
4828
4829     Expr *Arg;
4830     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4831     if (ArgIx < Args.size()) {
4832       Arg = Args[ArgIx++];
4833
4834       if (RequireCompleteType(Arg->getLocStart(),
4835                               ProtoArgType,
4836                               diag::err_call_incomplete_argument, Arg))
4837         return true;
4838
4839       // Strip the unbridged-cast placeholder expression off, if applicable.
4840       bool CFAudited = false;
4841       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4842           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4843           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4844         Arg = stripARCUnbridgedCast(Arg);
4845       else if (getLangOpts().ObjCAutoRefCount &&
4846                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4847                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4848         CFAudited = true;
4849
4850       InitializedEntity Entity =
4851           Param ? InitializedEntity::InitializeParameter(Context, Param,
4852                                                          ProtoArgType)
4853                 : InitializedEntity::InitializeParameter(
4854                       Context, ProtoArgType, Proto->isParamConsumed(i));
4855
4856       // Remember that parameter belongs to a CF audited API.
4857       if (CFAudited)
4858         Entity.setParameterCFAudited();
4859
4860       ExprResult ArgE = PerformCopyInitialization(
4861           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4862       if (ArgE.isInvalid())
4863         return true;
4864
4865       Arg = ArgE.getAs<Expr>();
4866     } else {
4867       assert(Param && "can't use default arguments without a known callee");
4868
4869       ExprResult ArgExpr =
4870         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4871       if (ArgExpr.isInvalid())
4872         return true;
4873
4874       Arg = ArgExpr.getAs<Expr>();
4875     }
4876
4877     // Check for array bounds violations for each argument to the call. This
4878     // check only triggers warnings when the argument isn't a more complex Expr
4879     // with its own checking, such as a BinaryOperator.
4880     CheckArrayAccess(Arg);
4881
4882     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4883     CheckStaticArrayArgument(CallLoc, Param, Arg);
4884
4885     AllArgs.push_back(Arg);
4886   }
4887
4888   // If this is a variadic call, handle args passed through "...".
4889   if (CallType != VariadicDoesNotApply) {
4890     // Assume that extern "C" functions with variadic arguments that
4891     // return __unknown_anytype aren't *really* variadic.
4892     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4893         FDecl->isExternC()) {
4894       for (Expr *A : Args.slice(ArgIx)) {
4895         QualType paramType; // ignored
4896         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4897         Invalid |= arg.isInvalid();
4898         AllArgs.push_back(arg.get());
4899       }
4900
4901     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4902     } else {
4903       for (Expr *A : Args.slice(ArgIx)) {
4904         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4905         Invalid |= Arg.isInvalid();
4906         AllArgs.push_back(Arg.get());
4907       }
4908     }
4909
4910     // Check for array bounds violations.
4911     for (Expr *A : Args.slice(ArgIx))
4912       CheckArrayAccess(A);
4913   }
4914   return Invalid;
4915 }
4916
4917 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4918   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4919   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4920     TL = DTL.getOriginalLoc();
4921   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4922     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4923       << ATL.getLocalSourceRange();
4924 }
4925
4926 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4927 /// array parameter, check that it is non-null, and that if it is formed by
4928 /// array-to-pointer decay, the underlying array is sufficiently large.
4929 ///
4930 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4931 /// array type derivation, then for each call to the function, the value of the
4932 /// corresponding actual argument shall provide access to the first element of
4933 /// an array with at least as many elements as specified by the size expression.
4934 void
4935 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4936                                ParmVarDecl *Param,
4937                                const Expr *ArgExpr) {
4938   // Static array parameters are not supported in C++.
4939   if (!Param || getLangOpts().CPlusPlus)
4940     return;
4941
4942   QualType OrigTy = Param->getOriginalType();
4943
4944   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4945   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4946     return;
4947
4948   if (ArgExpr->isNullPointerConstant(Context,
4949                                      Expr::NPC_NeverValueDependent)) {
4950     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4951     DiagnoseCalleeStaticArrayParam(*this, Param);
4952     return;
4953   }
4954
4955   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4956   if (!CAT)
4957     return;
4958
4959   const ConstantArrayType *ArgCAT =
4960     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4961   if (!ArgCAT)
4962     return;
4963
4964   if (ArgCAT->getSize().ult(CAT->getSize())) {
4965     Diag(CallLoc, diag::warn_static_array_too_small)
4966       << ArgExpr->getSourceRange()
4967       << (unsigned) ArgCAT->getSize().getZExtValue()
4968       << (unsigned) CAT->getSize().getZExtValue();
4969     DiagnoseCalleeStaticArrayParam(*this, Param);
4970   }
4971 }
4972
4973 /// Given a function expression of unknown-any type, try to rebuild it
4974 /// to have a function type.
4975 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4976
4977 /// Is the given type a placeholder that we need to lower out
4978 /// immediately during argument processing?
4979 static bool isPlaceholderToRemoveAsArg(QualType type) {
4980   // Placeholders are never sugared.
4981   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4982   if (!placeholder) return false;
4983
4984   switch (placeholder->getKind()) {
4985   // Ignore all the non-placeholder types.
4986 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4987   case BuiltinType::Id:
4988 #include "clang/Basic/OpenCLImageTypes.def"
4989 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4990 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4991 #include "clang/AST/BuiltinTypes.def"
4992     return false;
4993
4994   // We cannot lower out overload sets; they might validly be resolved
4995   // by the call machinery.
4996   case BuiltinType::Overload:
4997     return false;
4998
4999   // Unbridged casts in ARC can be handled in some call positions and
5000   // should be left in place.
5001   case BuiltinType::ARCUnbridgedCast:
5002     return false;
5003
5004   // Pseudo-objects should be converted as soon as possible.
5005   case BuiltinType::PseudoObject:
5006     return true;
5007
5008   // The debugger mode could theoretically but currently does not try
5009   // to resolve unknown-typed arguments based on known parameter types.
5010   case BuiltinType::UnknownAny:
5011     return true;
5012
5013   // These are always invalid as call arguments and should be reported.
5014   case BuiltinType::BoundMember:
5015   case BuiltinType::BuiltinFn:
5016   case BuiltinType::OMPArraySection:
5017     return true;
5018
5019   }
5020   llvm_unreachable("bad builtin type kind");
5021 }
5022
5023 /// Check an argument list for placeholders that we won't try to
5024 /// handle later.
5025 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5026   // Apply this processing to all the arguments at once instead of
5027   // dying at the first failure.
5028   bool hasInvalid = false;
5029   for (size_t i = 0, e = args.size(); i != e; i++) {
5030     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5031       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5032       if (result.isInvalid()) hasInvalid = true;
5033       else args[i] = result.get();
5034     } else if (hasInvalid) {
5035       (void)S.CorrectDelayedTyposInExpr(args[i]);
5036     }
5037   }
5038   return hasInvalid;
5039 }
5040
5041 /// If a builtin function has a pointer argument with no explicit address
5042 /// space, then it should be able to accept a pointer to any address
5043 /// space as input.  In order to do this, we need to replace the
5044 /// standard builtin declaration with one that uses the same address space
5045 /// as the call.
5046 ///
5047 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5048 ///                  it does not contain any pointer arguments without
5049 ///                  an address space qualifer.  Otherwise the rewritten
5050 ///                  FunctionDecl is returned.
5051 /// TODO: Handle pointer return types.
5052 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5053                                                 const FunctionDecl *FDecl,
5054                                                 MultiExprArg ArgExprs) {
5055
5056   QualType DeclType = FDecl->getType();
5057   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5058
5059   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5060       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5061     return nullptr;
5062
5063   bool NeedsNewDecl = false;
5064   unsigned i = 0;
5065   SmallVector<QualType, 8> OverloadParams;
5066
5067   for (QualType ParamType : FT->param_types()) {
5068
5069     // Convert array arguments to pointer to simplify type lookup.
5070     ExprResult ArgRes =
5071         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5072     if (ArgRes.isInvalid())
5073       return nullptr;
5074     Expr *Arg = ArgRes.get();
5075     QualType ArgType = Arg->getType();
5076     if (!ParamType->isPointerType() ||
5077         ParamType.getQualifiers().hasAddressSpace() ||
5078         !ArgType->isPointerType() ||
5079         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5080       OverloadParams.push_back(ParamType);
5081       continue;
5082     }
5083
5084     NeedsNewDecl = true;
5085     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5086
5087     QualType PointeeType = ParamType->getPointeeType();
5088     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5089     OverloadParams.push_back(Context.getPointerType(PointeeType));
5090   }
5091
5092   if (!NeedsNewDecl)
5093     return nullptr;
5094
5095   FunctionProtoType::ExtProtoInfo EPI;
5096   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5097                                                 OverloadParams, EPI);
5098   DeclContext *Parent = Context.getTranslationUnitDecl();
5099   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5100                                                     FDecl->getLocation(),
5101                                                     FDecl->getLocation(),
5102                                                     FDecl->getIdentifier(),
5103                                                     OverloadTy,
5104                                                     /*TInfo=*/nullptr,
5105                                                     SC_Extern, false,
5106                                                     /*hasPrototype=*/true);
5107   SmallVector<ParmVarDecl*, 16> Params;
5108   FT = cast<FunctionProtoType>(OverloadTy);
5109   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5110     QualType ParamType = FT->getParamType(i);
5111     ParmVarDecl *Parm =
5112         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5113                                 SourceLocation(), nullptr, ParamType,
5114                                 /*TInfo=*/nullptr, SC_None, nullptr);
5115     Parm->setScopeInfo(0, i);
5116     Params.push_back(Parm);
5117   }
5118   OverloadDecl->setParams(Params);
5119   return OverloadDecl;
5120 }
5121
5122 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5123                                        std::size_t NumArgs) {
5124   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5125                          /*PartialOverloading=*/false))
5126     return Callee->isVariadic();
5127   return Callee->getMinRequiredArguments() <= NumArgs;
5128 }
5129
5130 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5131 /// This provides the location of the left/right parens and a list of comma
5132 /// locations.
5133 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5134                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5135                                Expr *ExecConfig, bool IsExecConfig) {
5136   // Since this might be a postfix expression, get rid of ParenListExprs.
5137   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5138   if (Result.isInvalid()) return ExprError();
5139   Fn = Result.get();
5140
5141   if (checkArgsForPlaceholders(*this, ArgExprs))
5142     return ExprError();
5143
5144   if (getLangOpts().CPlusPlus) {
5145     // If this is a pseudo-destructor expression, build the call immediately.
5146     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5147       if (!ArgExprs.empty()) {
5148         // Pseudo-destructor calls should not have any arguments.
5149         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5150             << FixItHint::CreateRemoval(
5151                    SourceRange(ArgExprs.front()->getLocStart(),
5152                                ArgExprs.back()->getLocEnd()));
5153       }
5154
5155       return new (Context)
5156           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5157     }
5158     if (Fn->getType() == Context.PseudoObjectTy) {
5159       ExprResult result = CheckPlaceholderExpr(Fn);
5160       if (result.isInvalid()) return ExprError();
5161       Fn = result.get();
5162     }
5163
5164     // Determine whether this is a dependent call inside a C++ template,
5165     // in which case we won't do any semantic analysis now.
5166     bool Dependent = false;
5167     if (Fn->isTypeDependent())
5168       Dependent = true;
5169     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5170       Dependent = true;
5171
5172     if (Dependent) {
5173       if (ExecConfig) {
5174         return new (Context) CUDAKernelCallExpr(
5175             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5176             Context.DependentTy, VK_RValue, RParenLoc);
5177       } else {
5178         return new (Context) CallExpr(
5179             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5180       }
5181     }
5182
5183     // Determine whether this is a call to an object (C++ [over.call.object]).
5184     if (Fn->getType()->isRecordType())
5185       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5186                                           RParenLoc);
5187
5188     if (Fn->getType() == Context.UnknownAnyTy) {
5189       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5190       if (result.isInvalid()) return ExprError();
5191       Fn = result.get();
5192     }
5193
5194     if (Fn->getType() == Context.BoundMemberTy) {
5195       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5196                                        RParenLoc);
5197     }
5198   }
5199
5200   // Check for overloaded calls.  This can happen even in C due to extensions.
5201   if (Fn->getType() == Context.OverloadTy) {
5202     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5203
5204     // We aren't supposed to apply this logic for if there'Scope an '&'
5205     // involved.
5206     if (!find.HasFormOfMemberPointer) {
5207       OverloadExpr *ovl = find.Expression;
5208       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5209         return BuildOverloadedCallExpr(
5210             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5211             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5212       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5213                                        RParenLoc);
5214     }
5215   }
5216
5217   // If we're directly calling a function, get the appropriate declaration.
5218   if (Fn->getType() == Context.UnknownAnyTy) {
5219     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5220     if (result.isInvalid()) return ExprError();
5221     Fn = result.get();
5222   }
5223
5224   Expr *NakedFn = Fn->IgnoreParens();
5225
5226   bool CallingNDeclIndirectly = false;
5227   NamedDecl *NDecl = nullptr;
5228   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5229     if (UnOp->getOpcode() == UO_AddrOf) {
5230       CallingNDeclIndirectly = true;
5231       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5232     }
5233   }
5234
5235   if (isa<DeclRefExpr>(NakedFn)) {
5236     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5237
5238     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5239     if (FDecl && FDecl->getBuiltinID()) {
5240       // Rewrite the function decl for this builtin by replacing parameters
5241       // with no explicit address space with the address space of the arguments
5242       // in ArgExprs.
5243       if ((FDecl =
5244                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5245         NDecl = FDecl;
5246         Fn = DeclRefExpr::Create(
5247             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5248             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5249       }
5250     }
5251   } else if (isa<MemberExpr>(NakedFn))
5252     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5253
5254   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5255     if (CallingNDeclIndirectly &&
5256         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5257                                            Fn->getLocStart()))
5258       return ExprError();
5259
5260     // CheckEnableIf assumes that the we're passing in a sane number of args for
5261     // FD, but that doesn't always hold true here. This is because, in some
5262     // cases, we'll emit a diag about an ill-formed function call, but then
5263     // we'll continue on as if the function call wasn't ill-formed. So, if the
5264     // number of args looks incorrect, don't do enable_if checks; we should've
5265     // already emitted an error about the bad call.
5266     if (FD->hasAttr<EnableIfAttr>() &&
5267         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5268       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5269         Diag(Fn->getLocStart(),
5270              isa<CXXMethodDecl>(FD)
5271                  ? diag::err_ovl_no_viable_member_function_in_call
5272                  : diag::err_ovl_no_viable_function_in_call)
5273             << FD << FD->getSourceRange();
5274         Diag(FD->getLocation(),
5275              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5276             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5277       }
5278     }
5279   }
5280
5281   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5282                                ExecConfig, IsExecConfig);
5283 }
5284
5285 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5286 ///
5287 /// __builtin_astype( value, dst type )
5288 ///
5289 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5290                                  SourceLocation BuiltinLoc,
5291                                  SourceLocation RParenLoc) {
5292   ExprValueKind VK = VK_RValue;
5293   ExprObjectKind OK = OK_Ordinary;
5294   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5295   QualType SrcTy = E->getType();
5296   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5297     return ExprError(Diag(BuiltinLoc,
5298                           diag::err_invalid_astype_of_different_size)
5299                      << DstTy
5300                      << SrcTy
5301                      << E->getSourceRange());
5302   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5303 }
5304
5305 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5306 /// provided arguments.
5307 ///
5308 /// __builtin_convertvector( value, dst type )
5309 ///
5310 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5311                                         SourceLocation BuiltinLoc,
5312                                         SourceLocation RParenLoc) {
5313   TypeSourceInfo *TInfo;
5314   GetTypeFromParser(ParsedDestTy, &TInfo);
5315   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5316 }
5317
5318 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5319 /// i.e. an expression not of \p OverloadTy.  The expression should
5320 /// unary-convert to an expression of function-pointer or
5321 /// block-pointer type.
5322 ///
5323 /// \param NDecl the declaration being called, if available
5324 ExprResult
5325 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5326                             SourceLocation LParenLoc,
5327                             ArrayRef<Expr *> Args,
5328                             SourceLocation RParenLoc,
5329                             Expr *Config, bool IsExecConfig) {
5330   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5331   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5332
5333   // Functions with 'interrupt' attribute cannot be called directly.
5334   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5335     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5336     return ExprError();
5337   }
5338
5339   // Promote the function operand.
5340   // We special-case function promotion here because we only allow promoting
5341   // builtin functions to function pointers in the callee of a call.
5342   ExprResult Result;
5343   if (BuiltinID &&
5344       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5345     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5346                                CK_BuiltinFnToFnPtr).get();
5347   } else {
5348     Result = CallExprUnaryConversions(Fn);
5349   }
5350   if (Result.isInvalid())
5351     return ExprError();
5352   Fn = Result.get();
5353
5354   // Make the call expr early, before semantic checks.  This guarantees cleanup
5355   // of arguments and function on error.
5356   CallExpr *TheCall;
5357   if (Config)
5358     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5359                                                cast<CallExpr>(Config), Args,
5360                                                Context.BoolTy, VK_RValue,
5361                                                RParenLoc);
5362   else
5363     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5364                                      VK_RValue, RParenLoc);
5365
5366   if (!getLangOpts().CPlusPlus) {
5367     // C cannot always handle TypoExpr nodes in builtin calls and direct
5368     // function calls as their argument checking don't necessarily handle
5369     // dependent types properly, so make sure any TypoExprs have been
5370     // dealt with.
5371     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5372     if (!Result.isUsable()) return ExprError();
5373     TheCall = dyn_cast<CallExpr>(Result.get());
5374     if (!TheCall) return Result;
5375     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5376   }
5377
5378   // Bail out early if calling a builtin with custom typechecking.
5379   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5380     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5381
5382  retry:
5383   const FunctionType *FuncT;
5384   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5385     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5386     // have type pointer to function".
5387     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5388     if (!FuncT)
5389       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5390                          << Fn->getType() << Fn->getSourceRange());
5391   } else if (const BlockPointerType *BPT =
5392                Fn->getType()->getAs<BlockPointerType>()) {
5393     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5394   } else {
5395     // Handle calls to expressions of unknown-any type.
5396     if (Fn->getType() == Context.UnknownAnyTy) {
5397       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5398       if (rewrite.isInvalid()) return ExprError();
5399       Fn = rewrite.get();
5400       TheCall->setCallee(Fn);
5401       goto retry;
5402     }
5403
5404     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5405       << Fn->getType() << Fn->getSourceRange());
5406   }
5407
5408   if (getLangOpts().CUDA) {
5409     if (Config) {
5410       // CUDA: Kernel calls must be to global functions
5411       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5412         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5413             << FDecl->getName() << Fn->getSourceRange());
5414
5415       // CUDA: Kernel function must have 'void' return type
5416       if (!FuncT->getReturnType()->isVoidType())
5417         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5418             << Fn->getType() << Fn->getSourceRange());
5419     } else {
5420       // CUDA: Calls to global functions must be configured
5421       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5422         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5423             << FDecl->getName() << Fn->getSourceRange());
5424     }
5425   }
5426
5427   // Check for a valid return type
5428   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5429                           FDecl))
5430     return ExprError();
5431
5432   // We know the result type of the call, set it.
5433   TheCall->setType(FuncT->getCallResultType(Context));
5434   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5435
5436   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5437   if (Proto) {
5438     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5439                                 IsExecConfig))
5440       return ExprError();
5441   } else {
5442     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5443
5444     if (FDecl) {
5445       // Check if we have too few/too many template arguments, based
5446       // on our knowledge of the function definition.
5447       const FunctionDecl *Def = nullptr;
5448       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5449         Proto = Def->getType()->getAs<FunctionProtoType>();
5450        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5451           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5452           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5453       }
5454       
5455       // If the function we're calling isn't a function prototype, but we have
5456       // a function prototype from a prior declaratiom, use that prototype.
5457       if (!FDecl->hasPrototype())
5458         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5459     }
5460
5461     // Promote the arguments (C99 6.5.2.2p6).
5462     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5463       Expr *Arg = Args[i];
5464
5465       if (Proto && i < Proto->getNumParams()) {
5466         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5467             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5468         ExprResult ArgE =
5469             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5470         if (ArgE.isInvalid())
5471           return true;
5472         
5473         Arg = ArgE.getAs<Expr>();
5474
5475       } else {
5476         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5477
5478         if (ArgE.isInvalid())
5479           return true;
5480
5481         Arg = ArgE.getAs<Expr>();
5482       }
5483       
5484       if (RequireCompleteType(Arg->getLocStart(),
5485                               Arg->getType(),
5486                               diag::err_call_incomplete_argument, Arg))
5487         return ExprError();
5488
5489       TheCall->setArg(i, Arg);
5490     }
5491   }
5492
5493   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5494     if (!Method->isStatic())
5495       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5496         << Fn->getSourceRange());
5497
5498   // Check for sentinels
5499   if (NDecl)
5500     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5501
5502   // Do special checking on direct calls to functions.
5503   if (FDecl) {
5504     if (CheckFunctionCall(FDecl, TheCall, Proto))
5505       return ExprError();
5506
5507     if (BuiltinID)
5508       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5509   } else if (NDecl) {
5510     if (CheckPointerCall(NDecl, TheCall, Proto))
5511       return ExprError();
5512   } else {
5513     if (CheckOtherCall(TheCall, Proto))
5514       return ExprError();
5515   }
5516
5517   return MaybeBindToTemporary(TheCall);
5518 }
5519
5520 ExprResult
5521 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5522                            SourceLocation RParenLoc, Expr *InitExpr) {
5523   assert(Ty && "ActOnCompoundLiteral(): missing type");
5524   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5525
5526   TypeSourceInfo *TInfo;
5527   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5528   if (!TInfo)
5529     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5530
5531   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5532 }
5533
5534 ExprResult
5535 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5536                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5537   QualType literalType = TInfo->getType();
5538
5539   if (literalType->isArrayType()) {
5540     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5541           diag::err_illegal_decl_array_incomplete_type,
5542           SourceRange(LParenLoc,
5543                       LiteralExpr->getSourceRange().getEnd())))
5544       return ExprError();
5545     if (literalType->isVariableArrayType())
5546       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5547         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5548   } else if (!literalType->isDependentType() &&
5549              RequireCompleteType(LParenLoc, literalType,
5550                diag::err_typecheck_decl_incomplete_type,
5551                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5552     return ExprError();
5553
5554   InitializedEntity Entity
5555     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5556   InitializationKind Kind
5557     = InitializationKind::CreateCStyleCast(LParenLoc, 
5558                                            SourceRange(LParenLoc, RParenLoc),
5559                                            /*InitList=*/true);
5560   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5561   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5562                                       &literalType);
5563   if (Result.isInvalid())
5564     return ExprError();
5565   LiteralExpr = Result.get();
5566
5567   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5568   if (isFileScope &&
5569       !LiteralExpr->isTypeDependent() &&
5570       !LiteralExpr->isValueDependent() &&
5571       !literalType->isDependentType()) { // 6.5.2.5p3
5572     if (CheckForConstantInitializer(LiteralExpr, literalType))
5573       return ExprError();
5574   }
5575
5576   // In C, compound literals are l-values for some reason.
5577   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5578
5579   return MaybeBindToTemporary(
5580            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5581                                              VK, LiteralExpr, isFileScope));
5582 }
5583
5584 ExprResult
5585 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5586                     SourceLocation RBraceLoc) {
5587   // Immediately handle non-overload placeholders.  Overloads can be
5588   // resolved contextually, but everything else here can't.
5589   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5590     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5591       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5592
5593       // Ignore failures; dropping the entire initializer list because
5594       // of one failure would be terrible for indexing/etc.
5595       if (result.isInvalid()) continue;
5596
5597       InitArgList[I] = result.get();
5598     }
5599   }
5600
5601   // Semantic analysis for initializers is done by ActOnDeclarator() and
5602   // CheckInitializer() - it requires knowledge of the object being intialized.
5603
5604   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5605                                                RBraceLoc);
5606   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5607   return E;
5608 }
5609
5610 /// Do an explicit extend of the given block pointer if we're in ARC.
5611 void Sema::maybeExtendBlockObject(ExprResult &E) {
5612   assert(E.get()->getType()->isBlockPointerType());
5613   assert(E.get()->isRValue());
5614
5615   // Only do this in an r-value context.
5616   if (!getLangOpts().ObjCAutoRefCount) return;
5617
5618   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5619                                CK_ARCExtendBlockObject, E.get(),
5620                                /*base path*/ nullptr, VK_RValue);
5621   Cleanup.setExprNeedsCleanups(true);
5622 }
5623
5624 /// Prepare a conversion of the given expression to an ObjC object
5625 /// pointer type.
5626 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5627   QualType type = E.get()->getType();
5628   if (type->isObjCObjectPointerType()) {
5629     return CK_BitCast;
5630   } else if (type->isBlockPointerType()) {
5631     maybeExtendBlockObject(E);
5632     return CK_BlockPointerToObjCPointerCast;
5633   } else {
5634     assert(type->isPointerType());
5635     return CK_CPointerToObjCPointerCast;
5636   }
5637 }
5638
5639 /// Prepares for a scalar cast, performing all the necessary stages
5640 /// except the final cast and returning the kind required.
5641 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5642   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5643   // Also, callers should have filtered out the invalid cases with
5644   // pointers.  Everything else should be possible.
5645
5646   QualType SrcTy = Src.get()->getType();
5647   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5648     return CK_NoOp;
5649
5650   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5651   case Type::STK_MemberPointer:
5652     llvm_unreachable("member pointer type in C");
5653
5654   case Type::STK_CPointer:
5655   case Type::STK_BlockPointer:
5656   case Type::STK_ObjCObjectPointer:
5657     switch (DestTy->getScalarTypeKind()) {
5658     case Type::STK_CPointer: {
5659       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5660       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5661       if (SrcAS != DestAS)
5662         return CK_AddressSpaceConversion;
5663       return CK_BitCast;
5664     }
5665     case Type::STK_BlockPointer:
5666       return (SrcKind == Type::STK_BlockPointer
5667                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5668     case Type::STK_ObjCObjectPointer:
5669       if (SrcKind == Type::STK_ObjCObjectPointer)
5670         return CK_BitCast;
5671       if (SrcKind == Type::STK_CPointer)
5672         return CK_CPointerToObjCPointerCast;
5673       maybeExtendBlockObject(Src);
5674       return CK_BlockPointerToObjCPointerCast;
5675     case Type::STK_Bool:
5676       return CK_PointerToBoolean;
5677     case Type::STK_Integral:
5678       return CK_PointerToIntegral;
5679     case Type::STK_Floating:
5680     case Type::STK_FloatingComplex:
5681     case Type::STK_IntegralComplex:
5682     case Type::STK_MemberPointer:
5683       llvm_unreachable("illegal cast from pointer");
5684     }
5685     llvm_unreachable("Should have returned before this");
5686
5687   case Type::STK_Bool: // casting from bool is like casting from an integer
5688   case Type::STK_Integral:
5689     switch (DestTy->getScalarTypeKind()) {
5690     case Type::STK_CPointer:
5691     case Type::STK_ObjCObjectPointer:
5692     case Type::STK_BlockPointer:
5693       if (Src.get()->isNullPointerConstant(Context,
5694                                            Expr::NPC_ValueDependentIsNull))
5695         return CK_NullToPointer;
5696       return CK_IntegralToPointer;
5697     case Type::STK_Bool:
5698       return CK_IntegralToBoolean;
5699     case Type::STK_Integral:
5700       return CK_IntegralCast;
5701     case Type::STK_Floating:
5702       return CK_IntegralToFloating;
5703     case Type::STK_IntegralComplex:
5704       Src = ImpCastExprToType(Src.get(),
5705                       DestTy->castAs<ComplexType>()->getElementType(),
5706                       CK_IntegralCast);
5707       return CK_IntegralRealToComplex;
5708     case Type::STK_FloatingComplex:
5709       Src = ImpCastExprToType(Src.get(),
5710                       DestTy->castAs<ComplexType>()->getElementType(),
5711                       CK_IntegralToFloating);
5712       return CK_FloatingRealToComplex;
5713     case Type::STK_MemberPointer:
5714       llvm_unreachable("member pointer type in C");
5715     }
5716     llvm_unreachable("Should have returned before this");
5717
5718   case Type::STK_Floating:
5719     switch (DestTy->getScalarTypeKind()) {
5720     case Type::STK_Floating:
5721       return CK_FloatingCast;
5722     case Type::STK_Bool:
5723       return CK_FloatingToBoolean;
5724     case Type::STK_Integral:
5725       return CK_FloatingToIntegral;
5726     case Type::STK_FloatingComplex:
5727       Src = ImpCastExprToType(Src.get(),
5728                               DestTy->castAs<ComplexType>()->getElementType(),
5729                               CK_FloatingCast);
5730       return CK_FloatingRealToComplex;
5731     case Type::STK_IntegralComplex:
5732       Src = ImpCastExprToType(Src.get(),
5733                               DestTy->castAs<ComplexType>()->getElementType(),
5734                               CK_FloatingToIntegral);
5735       return CK_IntegralRealToComplex;
5736     case Type::STK_CPointer:
5737     case Type::STK_ObjCObjectPointer:
5738     case Type::STK_BlockPointer:
5739       llvm_unreachable("valid float->pointer cast?");
5740     case Type::STK_MemberPointer:
5741       llvm_unreachable("member pointer type in C");
5742     }
5743     llvm_unreachable("Should have returned before this");
5744
5745   case Type::STK_FloatingComplex:
5746     switch (DestTy->getScalarTypeKind()) {
5747     case Type::STK_FloatingComplex:
5748       return CK_FloatingComplexCast;
5749     case Type::STK_IntegralComplex:
5750       return CK_FloatingComplexToIntegralComplex;
5751     case Type::STK_Floating: {
5752       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5753       if (Context.hasSameType(ET, DestTy))
5754         return CK_FloatingComplexToReal;
5755       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5756       return CK_FloatingCast;
5757     }
5758     case Type::STK_Bool:
5759       return CK_FloatingComplexToBoolean;
5760     case Type::STK_Integral:
5761       Src = ImpCastExprToType(Src.get(),
5762                               SrcTy->castAs<ComplexType>()->getElementType(),
5763                               CK_FloatingComplexToReal);
5764       return CK_FloatingToIntegral;
5765     case Type::STK_CPointer:
5766     case Type::STK_ObjCObjectPointer:
5767     case Type::STK_BlockPointer:
5768       llvm_unreachable("valid complex float->pointer cast?");
5769     case Type::STK_MemberPointer:
5770       llvm_unreachable("member pointer type in C");
5771     }
5772     llvm_unreachable("Should have returned before this");
5773
5774   case Type::STK_IntegralComplex:
5775     switch (DestTy->getScalarTypeKind()) {
5776     case Type::STK_FloatingComplex:
5777       return CK_IntegralComplexToFloatingComplex;
5778     case Type::STK_IntegralComplex:
5779       return CK_IntegralComplexCast;
5780     case Type::STK_Integral: {
5781       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5782       if (Context.hasSameType(ET, DestTy))
5783         return CK_IntegralComplexToReal;
5784       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5785       return CK_IntegralCast;
5786     }
5787     case Type::STK_Bool:
5788       return CK_IntegralComplexToBoolean;
5789     case Type::STK_Floating:
5790       Src = ImpCastExprToType(Src.get(),
5791                               SrcTy->castAs<ComplexType>()->getElementType(),
5792                               CK_IntegralComplexToReal);
5793       return CK_IntegralToFloating;
5794     case Type::STK_CPointer:
5795     case Type::STK_ObjCObjectPointer:
5796     case Type::STK_BlockPointer:
5797       llvm_unreachable("valid complex int->pointer cast?");
5798     case Type::STK_MemberPointer:
5799       llvm_unreachable("member pointer type in C");
5800     }
5801     llvm_unreachable("Should have returned before this");
5802   }
5803
5804   llvm_unreachable("Unhandled scalar cast");
5805 }
5806
5807 static bool breakDownVectorType(QualType type, uint64_t &len,
5808                                 QualType &eltType) {
5809   // Vectors are simple.
5810   if (const VectorType *vecType = type->getAs<VectorType>()) {
5811     len = vecType->getNumElements();
5812     eltType = vecType->getElementType();
5813     assert(eltType->isScalarType());
5814     return true;
5815   }
5816   
5817   // We allow lax conversion to and from non-vector types, but only if
5818   // they're real types (i.e. non-complex, non-pointer scalar types).
5819   if (!type->isRealType()) return false;
5820   
5821   len = 1;
5822   eltType = type;
5823   return true;
5824 }
5825
5826 /// Are the two types lax-compatible vector types?  That is, given
5827 /// that one of them is a vector, do they have equal storage sizes,
5828 /// where the storage size is the number of elements times the element
5829 /// size?
5830 ///
5831 /// This will also return false if either of the types is neither a
5832 /// vector nor a real type.
5833 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5834   assert(destTy->isVectorType() || srcTy->isVectorType());
5835   
5836   // Disallow lax conversions between scalars and ExtVectors (these
5837   // conversions are allowed for other vector types because common headers
5838   // depend on them).  Most scalar OP ExtVector cases are handled by the
5839   // splat path anyway, which does what we want (convert, not bitcast).
5840   // What this rules out for ExtVectors is crazy things like char4*float.
5841   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5842   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5843
5844   uint64_t srcLen, destLen;
5845   QualType srcEltTy, destEltTy;
5846   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5847   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5848   
5849   // ASTContext::getTypeSize will return the size rounded up to a
5850   // power of 2, so instead of using that, we need to use the raw
5851   // element size multiplied by the element count.
5852   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5853   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5854   
5855   return (srcLen * srcEltSize == destLen * destEltSize);
5856 }
5857
5858 /// Is this a legal conversion between two types, one of which is
5859 /// known to be a vector type?
5860 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5861   assert(destTy->isVectorType() || srcTy->isVectorType());
5862   
5863   if (!Context.getLangOpts().LaxVectorConversions)
5864     return false;
5865   return areLaxCompatibleVectorTypes(srcTy, destTy);
5866 }
5867
5868 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5869                            CastKind &Kind) {
5870   assert(VectorTy->isVectorType() && "Not a vector type!");
5871
5872   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5873     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5874       return Diag(R.getBegin(),
5875                   Ty->isVectorType() ?
5876                   diag::err_invalid_conversion_between_vectors :
5877                   diag::err_invalid_conversion_between_vector_and_integer)
5878         << VectorTy << Ty << R;
5879   } else
5880     return Diag(R.getBegin(),
5881                 diag::err_invalid_conversion_between_vector_and_scalar)
5882       << VectorTy << Ty << R;
5883
5884   Kind = CK_BitCast;
5885   return false;
5886 }
5887
5888 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5889   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5890
5891   if (DestElemTy == SplattedExpr->getType())
5892     return SplattedExpr;
5893
5894   assert(DestElemTy->isFloatingType() ||
5895          DestElemTy->isIntegralOrEnumerationType());
5896
5897   CastKind CK;
5898   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5899     // OpenCL requires that we convert `true` boolean expressions to -1, but
5900     // only when splatting vectors.
5901     if (DestElemTy->isFloatingType()) {
5902       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5903       // in two steps: boolean to signed integral, then to floating.
5904       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5905                                                  CK_BooleanToSignedIntegral);
5906       SplattedExpr = CastExprRes.get();
5907       CK = CK_IntegralToFloating;
5908     } else {
5909       CK = CK_BooleanToSignedIntegral;
5910     }
5911   } else {
5912     ExprResult CastExprRes = SplattedExpr;
5913     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5914     if (CastExprRes.isInvalid())
5915       return ExprError();
5916     SplattedExpr = CastExprRes.get();
5917   }
5918   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5919 }
5920
5921 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5922                                     Expr *CastExpr, CastKind &Kind) {
5923   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5924
5925   QualType SrcTy = CastExpr->getType();
5926
5927   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5928   // an ExtVectorType.
5929   // In OpenCL, casts between vectors of different types are not allowed.
5930   // (See OpenCL 6.2).
5931   if (SrcTy->isVectorType()) {
5932     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5933         || (getLangOpts().OpenCL &&
5934             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5935       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5936         << DestTy << SrcTy << R;
5937       return ExprError();
5938     }
5939     Kind = CK_BitCast;
5940     return CastExpr;
5941   }
5942
5943   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5944   // conversion will take place first from scalar to elt type, and then
5945   // splat from elt type to vector.
5946   if (SrcTy->isPointerType())
5947     return Diag(R.getBegin(),
5948                 diag::err_invalid_conversion_between_vector_and_scalar)
5949       << DestTy << SrcTy << R;
5950
5951   Kind = CK_VectorSplat;
5952   return prepareVectorSplat(DestTy, CastExpr);
5953 }
5954
5955 ExprResult
5956 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5957                     Declarator &D, ParsedType &Ty,
5958                     SourceLocation RParenLoc, Expr *CastExpr) {
5959   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5960          "ActOnCastExpr(): missing type or expr");
5961
5962   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5963   if (D.isInvalidType())
5964     return ExprError();
5965
5966   if (getLangOpts().CPlusPlus) {
5967     // Check that there are no default arguments (C++ only).
5968     CheckExtraCXXDefaultArguments(D);
5969   } else {
5970     // Make sure any TypoExprs have been dealt with.
5971     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5972     if (!Res.isUsable())
5973       return ExprError();
5974     CastExpr = Res.get();
5975   }
5976
5977   checkUnusedDeclAttributes(D);
5978
5979   QualType castType = castTInfo->getType();
5980   Ty = CreateParsedType(castType, castTInfo);
5981
5982   bool isVectorLiteral = false;
5983
5984   // Check for an altivec or OpenCL literal,
5985   // i.e. all the elements are integer constants.
5986   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5987   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5988   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5989        && castType->isVectorType() && (PE || PLE)) {
5990     if (PLE && PLE->getNumExprs() == 0) {
5991       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5992       return ExprError();
5993     }
5994     if (PE || PLE->getNumExprs() == 1) {
5995       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5996       if (!E->getType()->isVectorType())
5997         isVectorLiteral = true;
5998     }
5999     else
6000       isVectorLiteral = true;
6001   }
6002
6003   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6004   // then handle it as such.
6005   if (isVectorLiteral)
6006     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6007
6008   // If the Expr being casted is a ParenListExpr, handle it specially.
6009   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6010   // sequence of BinOp comma operators.
6011   if (isa<ParenListExpr>(CastExpr)) {
6012     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6013     if (Result.isInvalid()) return ExprError();
6014     CastExpr = Result.get();
6015   }
6016
6017   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6018       !getSourceManager().isInSystemMacro(LParenLoc))
6019     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6020   
6021   CheckTollFreeBridgeCast(castType, CastExpr);
6022   
6023   CheckObjCBridgeRelatedCast(castType, CastExpr);
6024
6025   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6026
6027   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6028 }
6029
6030 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6031                                     SourceLocation RParenLoc, Expr *E,
6032                                     TypeSourceInfo *TInfo) {
6033   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6034          "Expected paren or paren list expression");
6035
6036   Expr **exprs;
6037   unsigned numExprs;
6038   Expr *subExpr;
6039   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6040   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6041     LiteralLParenLoc = PE->getLParenLoc();
6042     LiteralRParenLoc = PE->getRParenLoc();
6043     exprs = PE->getExprs();
6044     numExprs = PE->getNumExprs();
6045   } else { // isa<ParenExpr> by assertion at function entrance
6046     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6047     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6048     subExpr = cast<ParenExpr>(E)->getSubExpr();
6049     exprs = &subExpr;
6050     numExprs = 1;
6051   }
6052
6053   QualType Ty = TInfo->getType();
6054   assert(Ty->isVectorType() && "Expected vector type");
6055
6056   SmallVector<Expr *, 8> initExprs;
6057   const VectorType *VTy = Ty->getAs<VectorType>();
6058   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6059   
6060   // '(...)' form of vector initialization in AltiVec: the number of
6061   // initializers must be one or must match the size of the vector.
6062   // If a single value is specified in the initializer then it will be
6063   // replicated to all the components of the vector
6064   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6065     // The number of initializers must be one or must match the size of the
6066     // vector. If a single value is specified in the initializer then it will
6067     // be replicated to all the components of the vector
6068     if (numExprs == 1) {
6069       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6070       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6071       if (Literal.isInvalid())
6072         return ExprError();
6073       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6074                                   PrepareScalarCast(Literal, ElemTy));
6075       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6076     }
6077     else if (numExprs < numElems) {
6078       Diag(E->getExprLoc(),
6079            diag::err_incorrect_number_of_vector_initializers);
6080       return ExprError();
6081     }
6082     else
6083       initExprs.append(exprs, exprs + numExprs);
6084   }
6085   else {
6086     // For OpenCL, when the number of initializers is a single value,
6087     // it will be replicated to all components of the vector.
6088     if (getLangOpts().OpenCL &&
6089         VTy->getVectorKind() == VectorType::GenericVector &&
6090         numExprs == 1) {
6091         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6092         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6093         if (Literal.isInvalid())
6094           return ExprError();
6095         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6096                                     PrepareScalarCast(Literal, ElemTy));
6097         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6098     }
6099     
6100     initExprs.append(exprs, exprs + numExprs);
6101   }
6102   // FIXME: This means that pretty-printing the final AST will produce curly
6103   // braces instead of the original commas.
6104   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6105                                                    initExprs, LiteralRParenLoc);
6106   initE->setType(Ty);
6107   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6108 }
6109
6110 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6111 /// the ParenListExpr into a sequence of comma binary operators.
6112 ExprResult
6113 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6114   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6115   if (!E)
6116     return OrigExpr;
6117
6118   ExprResult Result(E->getExpr(0));
6119
6120   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6121     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6122                         E->getExpr(i));
6123
6124   if (Result.isInvalid()) return ExprError();
6125
6126   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6127 }
6128
6129 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6130                                     SourceLocation R,
6131                                     MultiExprArg Val) {
6132   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6133   return expr;
6134 }
6135
6136 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6137 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6138 /// emitted.
6139 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6140                                       SourceLocation QuestionLoc) {
6141   Expr *NullExpr = LHSExpr;
6142   Expr *NonPointerExpr = RHSExpr;
6143   Expr::NullPointerConstantKind NullKind =
6144       NullExpr->isNullPointerConstant(Context,
6145                                       Expr::NPC_ValueDependentIsNotNull);
6146
6147   if (NullKind == Expr::NPCK_NotNull) {
6148     NullExpr = RHSExpr;
6149     NonPointerExpr = LHSExpr;
6150     NullKind =
6151         NullExpr->isNullPointerConstant(Context,
6152                                         Expr::NPC_ValueDependentIsNotNull);
6153   }
6154
6155   if (NullKind == Expr::NPCK_NotNull)
6156     return false;
6157
6158   if (NullKind == Expr::NPCK_ZeroExpression)
6159     return false;
6160
6161   if (NullKind == Expr::NPCK_ZeroLiteral) {
6162     // In this case, check to make sure that we got here from a "NULL"
6163     // string in the source code.
6164     NullExpr = NullExpr->IgnoreParenImpCasts();
6165     SourceLocation loc = NullExpr->getExprLoc();
6166     if (!findMacroSpelling(loc, "NULL"))
6167       return false;
6168   }
6169
6170   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6171   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6172       << NonPointerExpr->getType() << DiagType
6173       << NonPointerExpr->getSourceRange();
6174   return true;
6175 }
6176
6177 /// \brief Return false if the condition expression is valid, true otherwise.
6178 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6179   QualType CondTy = Cond->getType();
6180
6181   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6182   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6183     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6184       << CondTy << Cond->getSourceRange();
6185     return true;
6186   }
6187
6188   // C99 6.5.15p2
6189   if (CondTy->isScalarType()) return false;
6190
6191   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6192     << CondTy << Cond->getSourceRange();
6193   return true;
6194 }
6195
6196 /// \brief Handle when one or both operands are void type.
6197 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6198                                          ExprResult &RHS) {
6199     Expr *LHSExpr = LHS.get();
6200     Expr *RHSExpr = RHS.get();
6201
6202     if (!LHSExpr->getType()->isVoidType())
6203       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6204         << RHSExpr->getSourceRange();
6205     if (!RHSExpr->getType()->isVoidType())
6206       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6207         << LHSExpr->getSourceRange();
6208     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6209     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6210     return S.Context.VoidTy;
6211 }
6212
6213 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6214 /// true otherwise.
6215 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6216                                         QualType PointerTy) {
6217   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6218       !NullExpr.get()->isNullPointerConstant(S.Context,
6219                                             Expr::NPC_ValueDependentIsNull))
6220     return true;
6221
6222   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6223   return false;
6224 }
6225
6226 /// \brief Checks compatibility between two pointers and return the resulting
6227 /// type.
6228 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6229                                                      ExprResult &RHS,
6230                                                      SourceLocation Loc) {
6231   QualType LHSTy = LHS.get()->getType();
6232   QualType RHSTy = RHS.get()->getType();
6233
6234   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6235     // Two identical pointers types are always compatible.
6236     return LHSTy;
6237   }
6238
6239   QualType lhptee, rhptee;
6240
6241   // Get the pointee types.
6242   bool IsBlockPointer = false;
6243   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6244     lhptee = LHSBTy->getPointeeType();
6245     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6246     IsBlockPointer = true;
6247   } else {
6248     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6249     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6250   }
6251
6252   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6253   // differently qualified versions of compatible types, the result type is
6254   // a pointer to an appropriately qualified version of the composite
6255   // type.
6256
6257   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6258   // clause doesn't make sense for our extensions. E.g. address space 2 should
6259   // be incompatible with address space 3: they may live on different devices or
6260   // anything.
6261   Qualifiers lhQual = lhptee.getQualifiers();
6262   Qualifiers rhQual = rhptee.getQualifiers();
6263
6264   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6265   lhQual.removeCVRQualifiers();
6266   rhQual.removeCVRQualifiers();
6267
6268   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6269   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6270
6271   // For OpenCL:
6272   // 1. If LHS and RHS types match exactly and:
6273   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6274   //  (b) AS overlap => generate addrspacecast
6275   //  (c) AS don't overlap => give an error
6276   // 2. if LHS and RHS types don't match:
6277   //  (a) AS match => use standard C rules, generate bitcast
6278   //  (b) AS overlap => generate addrspacecast instead of bitcast
6279   //  (c) AS don't overlap => give an error
6280
6281   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6282   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6283
6284   // OpenCL cases 1c, 2a, 2b, and 2c.
6285   if (CompositeTy.isNull()) {
6286     // In this situation, we assume void* type. No especially good
6287     // reason, but this is what gcc does, and we do have to pick
6288     // to get a consistent AST.
6289     QualType incompatTy;
6290     if (S.getLangOpts().OpenCL) {
6291       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6292       // spaces is disallowed.
6293       unsigned ResultAddrSpace;
6294       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6295         // Cases 2a and 2b.
6296         ResultAddrSpace = lhQual.getAddressSpace();
6297       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6298         // Cases 2a and 2b.
6299         ResultAddrSpace = rhQual.getAddressSpace();
6300       } else {
6301         // Cases 1c and 2c.
6302         S.Diag(Loc,
6303                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6304             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6305             << RHS.get()->getSourceRange();
6306         return QualType();
6307       }
6308
6309       // Continue handling cases 2a and 2b.
6310       incompatTy = S.Context.getPointerType(
6311           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6312       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6313                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6314                                     ? CK_AddressSpaceConversion /* 2b */
6315                                     : CK_BitCast /* 2a */);
6316       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6317                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6318                                     ? CK_AddressSpaceConversion /* 2b */
6319                                     : CK_BitCast /* 2a */);
6320     } else {
6321       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6322           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6323           << RHS.get()->getSourceRange();
6324       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6325       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6326       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6327     }
6328     return incompatTy;
6329   }
6330
6331   // The pointer types are compatible.
6332   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6333   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6334   if (IsBlockPointer)
6335     ResultTy = S.Context.getBlockPointerType(ResultTy);
6336   else {
6337     // Cases 1a and 1b for OpenCL.
6338     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6339     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6340                       ? CK_BitCast /* 1a */
6341                       : CK_AddressSpaceConversion /* 1b */;
6342     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6343                       ? CK_BitCast /* 1a */
6344                       : CK_AddressSpaceConversion /* 1b */;
6345     ResultTy = S.Context.getPointerType(ResultTy);
6346   }
6347
6348   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6349   // if the target type does not change.
6350   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6351   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6352   return ResultTy;
6353 }
6354
6355 /// \brief Return the resulting type when the operands are both block pointers.
6356 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6357                                                           ExprResult &LHS,
6358                                                           ExprResult &RHS,
6359                                                           SourceLocation Loc) {
6360   QualType LHSTy = LHS.get()->getType();
6361   QualType RHSTy = RHS.get()->getType();
6362
6363   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6364     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6365       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6366       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6367       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6368       return destType;
6369     }
6370     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6371       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6372       << RHS.get()->getSourceRange();
6373     return QualType();
6374   }
6375
6376   // We have 2 block pointer types.
6377   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6378 }
6379
6380 /// \brief Return the resulting type when the operands are both pointers.
6381 static QualType
6382 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6383                                             ExprResult &RHS,
6384                                             SourceLocation Loc) {
6385   // get the pointer types
6386   QualType LHSTy = LHS.get()->getType();
6387   QualType RHSTy = RHS.get()->getType();
6388
6389   // get the "pointed to" types
6390   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6391   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6392
6393   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6394   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6395     // Figure out necessary qualifiers (C99 6.5.15p6)
6396     QualType destPointee
6397       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6398     QualType destType = S.Context.getPointerType(destPointee);
6399     // Add qualifiers if necessary.
6400     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6401     // Promote to void*.
6402     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6403     return destType;
6404   }
6405   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6406     QualType destPointee
6407       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6408     QualType destType = S.Context.getPointerType(destPointee);
6409     // Add qualifiers if necessary.
6410     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6411     // Promote to void*.
6412     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6413     return destType;
6414   }
6415
6416   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6417 }
6418
6419 /// \brief Return false if the first expression is not an integer and the second
6420 /// expression is not a pointer, true otherwise.
6421 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6422                                         Expr* PointerExpr, SourceLocation Loc,
6423                                         bool IsIntFirstExpr) {
6424   if (!PointerExpr->getType()->isPointerType() ||
6425       !Int.get()->getType()->isIntegerType())
6426     return false;
6427
6428   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6429   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6430
6431   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6432     << Expr1->getType() << Expr2->getType()
6433     << Expr1->getSourceRange() << Expr2->getSourceRange();
6434   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6435                             CK_IntegralToPointer);
6436   return true;
6437 }
6438
6439 /// \brief Simple conversion between integer and floating point types.
6440 ///
6441 /// Used when handling the OpenCL conditional operator where the
6442 /// condition is a vector while the other operands are scalar.
6443 ///
6444 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6445 /// types are either integer or floating type. Between the two
6446 /// operands, the type with the higher rank is defined as the "result
6447 /// type". The other operand needs to be promoted to the same type. No
6448 /// other type promotion is allowed. We cannot use
6449 /// UsualArithmeticConversions() for this purpose, since it always
6450 /// promotes promotable types.
6451 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6452                                             ExprResult &RHS,
6453                                             SourceLocation QuestionLoc) {
6454   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6455   if (LHS.isInvalid())
6456     return QualType();
6457   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6458   if (RHS.isInvalid())
6459     return QualType();
6460
6461   // For conversion purposes, we ignore any qualifiers.
6462   // For example, "const float" and "float" are equivalent.
6463   QualType LHSType =
6464     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6465   QualType RHSType =
6466     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6467
6468   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6469     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6470       << LHSType << LHS.get()->getSourceRange();
6471     return QualType();
6472   }
6473
6474   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6475     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6476       << RHSType << RHS.get()->getSourceRange();
6477     return QualType();
6478   }
6479
6480   // If both types are identical, no conversion is needed.
6481   if (LHSType == RHSType)
6482     return LHSType;
6483
6484   // Now handle "real" floating types (i.e. float, double, long double).
6485   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6486     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6487                                  /*IsCompAssign = */ false);
6488
6489   // Finally, we have two differing integer types.
6490   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6491   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6492 }
6493
6494 /// \brief Convert scalar operands to a vector that matches the
6495 ///        condition in length.
6496 ///
6497 /// Used when handling the OpenCL conditional operator where the
6498 /// condition is a vector while the other operands are scalar.
6499 ///
6500 /// We first compute the "result type" for the scalar operands
6501 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6502 /// into a vector of that type where the length matches the condition
6503 /// vector type. s6.11.6 requires that the element types of the result
6504 /// and the condition must have the same number of bits.
6505 static QualType
6506 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6507                               QualType CondTy, SourceLocation QuestionLoc) {
6508   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6509   if (ResTy.isNull()) return QualType();
6510
6511   const VectorType *CV = CondTy->getAs<VectorType>();
6512   assert(CV);
6513
6514   // Determine the vector result type
6515   unsigned NumElements = CV->getNumElements();
6516   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6517
6518   // Ensure that all types have the same number of bits
6519   if (S.Context.getTypeSize(CV->getElementType())
6520       != S.Context.getTypeSize(ResTy)) {
6521     // Since VectorTy is created internally, it does not pretty print
6522     // with an OpenCL name. Instead, we just print a description.
6523     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6524     SmallString<64> Str;
6525     llvm::raw_svector_ostream OS(Str);
6526     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6527     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6528       << CondTy << OS.str();
6529     return QualType();
6530   }
6531
6532   // Convert operands to the vector result type
6533   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6534   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6535
6536   return VectorTy;
6537 }
6538
6539 /// \brief Return false if this is a valid OpenCL condition vector
6540 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6541                                        SourceLocation QuestionLoc) {
6542   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6543   // integral type.
6544   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6545   assert(CondTy);
6546   QualType EleTy = CondTy->getElementType();
6547   if (EleTy->isIntegerType()) return false;
6548
6549   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6550     << Cond->getType() << Cond->getSourceRange();
6551   return true;
6552 }
6553
6554 /// \brief Return false if the vector condition type and the vector
6555 ///        result type are compatible.
6556 ///
6557 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6558 /// number of elements, and their element types have the same number
6559 /// of bits.
6560 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6561                               SourceLocation QuestionLoc) {
6562   const VectorType *CV = CondTy->getAs<VectorType>();
6563   const VectorType *RV = VecResTy->getAs<VectorType>();
6564   assert(CV && RV);
6565
6566   if (CV->getNumElements() != RV->getNumElements()) {
6567     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6568       << CondTy << VecResTy;
6569     return true;
6570   }
6571
6572   QualType CVE = CV->getElementType();
6573   QualType RVE = RV->getElementType();
6574
6575   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6576     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6577       << CondTy << VecResTy;
6578     return true;
6579   }
6580
6581   return false;
6582 }
6583
6584 /// \brief Return the resulting type for the conditional operator in
6585 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6586 ///        s6.3.i) when the condition is a vector type.
6587 static QualType
6588 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6589                              ExprResult &LHS, ExprResult &RHS,
6590                              SourceLocation QuestionLoc) {
6591   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6592   if (Cond.isInvalid())
6593     return QualType();
6594   QualType CondTy = Cond.get()->getType();
6595
6596   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6597     return QualType();
6598
6599   // If either operand is a vector then find the vector type of the
6600   // result as specified in OpenCL v1.1 s6.3.i.
6601   if (LHS.get()->getType()->isVectorType() ||
6602       RHS.get()->getType()->isVectorType()) {
6603     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6604                                               /*isCompAssign*/false,
6605                                               /*AllowBothBool*/true,
6606                                               /*AllowBoolConversions*/false);
6607     if (VecResTy.isNull()) return QualType();
6608     // The result type must match the condition type as specified in
6609     // OpenCL v1.1 s6.11.6.
6610     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6611       return QualType();
6612     return VecResTy;
6613   }
6614
6615   // Both operands are scalar.
6616   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6617 }
6618
6619 /// \brief Return true if the Expr is block type
6620 static bool checkBlockType(Sema &S, const Expr *E) {
6621   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6622     QualType Ty = CE->getCallee()->getType();
6623     if (Ty->isBlockPointerType()) {
6624       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6625       return true;
6626     }
6627   }
6628   return false;
6629 }
6630
6631 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6632 /// In that case, LHS = cond.
6633 /// C99 6.5.15
6634 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6635                                         ExprResult &RHS, ExprValueKind &VK,
6636                                         ExprObjectKind &OK,
6637                                         SourceLocation QuestionLoc) {
6638
6639   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6640   if (!LHSResult.isUsable()) return QualType();
6641   LHS = LHSResult;
6642
6643   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6644   if (!RHSResult.isUsable()) return QualType();
6645   RHS = RHSResult;
6646
6647   // C++ is sufficiently different to merit its own checker.
6648   if (getLangOpts().CPlusPlus)
6649     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6650
6651   VK = VK_RValue;
6652   OK = OK_Ordinary;
6653
6654   // The OpenCL operator with a vector condition is sufficiently
6655   // different to merit its own checker.
6656   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6657     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6658
6659   // First, check the condition.
6660   Cond = UsualUnaryConversions(Cond.get());
6661   if (Cond.isInvalid())
6662     return QualType();
6663   if (checkCondition(*this, Cond.get(), QuestionLoc))
6664     return QualType();
6665
6666   // Now check the two expressions.
6667   if (LHS.get()->getType()->isVectorType() ||
6668       RHS.get()->getType()->isVectorType())
6669     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6670                                /*AllowBothBool*/true,
6671                                /*AllowBoolConversions*/false);
6672
6673   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6674   if (LHS.isInvalid() || RHS.isInvalid())
6675     return QualType();
6676
6677   QualType LHSTy = LHS.get()->getType();
6678   QualType RHSTy = RHS.get()->getType();
6679
6680   // Diagnose attempts to convert between __float128 and long double where
6681   // such conversions currently can't be handled.
6682   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6683     Diag(QuestionLoc,
6684          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6685       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6686     return QualType();
6687   }
6688
6689   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6690   // selection operator (?:).
6691   if (getLangOpts().OpenCL &&
6692       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6693     return QualType();
6694   }
6695
6696   // If both operands have arithmetic type, do the usual arithmetic conversions
6697   // to find a common type: C99 6.5.15p3,5.
6698   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6699     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6700     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6701
6702     return ResTy;
6703   }
6704
6705   // If both operands are the same structure or union type, the result is that
6706   // type.
6707   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6708     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6709       if (LHSRT->getDecl() == RHSRT->getDecl())
6710         // "If both the operands have structure or union type, the result has
6711         // that type."  This implies that CV qualifiers are dropped.
6712         return LHSTy.getUnqualifiedType();
6713     // FIXME: Type of conditional expression must be complete in C mode.
6714   }
6715
6716   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6717   // The following || allows only one side to be void (a GCC-ism).
6718   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6719     return checkConditionalVoidType(*this, LHS, RHS);
6720   }
6721
6722   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6723   // the type of the other operand."
6724   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6725   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6726
6727   // All objective-c pointer type analysis is done here.
6728   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6729                                                         QuestionLoc);
6730   if (LHS.isInvalid() || RHS.isInvalid())
6731     return QualType();
6732   if (!compositeType.isNull())
6733     return compositeType;
6734
6735
6736   // Handle block pointer types.
6737   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6738     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6739                                                      QuestionLoc);
6740
6741   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6742   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6743     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6744                                                        QuestionLoc);
6745
6746   // GCC compatibility: soften pointer/integer mismatch.  Note that
6747   // null pointers have been filtered out by this point.
6748   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6749       /*isIntFirstExpr=*/true))
6750     return RHSTy;
6751   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6752       /*isIntFirstExpr=*/false))
6753     return LHSTy;
6754
6755   // Emit a better diagnostic if one of the expressions is a null pointer
6756   // constant and the other is not a pointer type. In this case, the user most
6757   // likely forgot to take the address of the other expression.
6758   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6759     return QualType();
6760
6761   // Otherwise, the operands are not compatible.
6762   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6763     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6764     << RHS.get()->getSourceRange();
6765   return QualType();
6766 }
6767
6768 /// FindCompositeObjCPointerType - Helper method to find composite type of
6769 /// two objective-c pointer types of the two input expressions.
6770 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6771                                             SourceLocation QuestionLoc) {
6772   QualType LHSTy = LHS.get()->getType();
6773   QualType RHSTy = RHS.get()->getType();
6774
6775   // Handle things like Class and struct objc_class*.  Here we case the result
6776   // to the pseudo-builtin, because that will be implicitly cast back to the
6777   // redefinition type if an attempt is made to access its fields.
6778   if (LHSTy->isObjCClassType() &&
6779       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6780     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6781     return LHSTy;
6782   }
6783   if (RHSTy->isObjCClassType() &&
6784       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6785     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6786     return RHSTy;
6787   }
6788   // And the same for struct objc_object* / id
6789   if (LHSTy->isObjCIdType() &&
6790       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6791     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6792     return LHSTy;
6793   }
6794   if (RHSTy->isObjCIdType() &&
6795       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6796     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6797     return RHSTy;
6798   }
6799   // And the same for struct objc_selector* / SEL
6800   if (Context.isObjCSelType(LHSTy) &&
6801       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6802     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6803     return LHSTy;
6804   }
6805   if (Context.isObjCSelType(RHSTy) &&
6806       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6807     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6808     return RHSTy;
6809   }
6810   // Check constraints for Objective-C object pointers types.
6811   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6812
6813     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6814       // Two identical object pointer types are always compatible.
6815       return LHSTy;
6816     }
6817     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6818     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6819     QualType compositeType = LHSTy;
6820
6821     // If both operands are interfaces and either operand can be
6822     // assigned to the other, use that type as the composite
6823     // type. This allows
6824     //   xxx ? (A*) a : (B*) b
6825     // where B is a subclass of A.
6826     //
6827     // Additionally, as for assignment, if either type is 'id'
6828     // allow silent coercion. Finally, if the types are
6829     // incompatible then make sure to use 'id' as the composite
6830     // type so the result is acceptable for sending messages to.
6831
6832     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6833     // It could return the composite type.
6834     if (!(compositeType =
6835           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6836       // Nothing more to do.
6837     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6838       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6839     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6840       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6841     } else if ((LHSTy->isObjCQualifiedIdType() ||
6842                 RHSTy->isObjCQualifiedIdType()) &&
6843                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6844       // Need to handle "id<xx>" explicitly.
6845       // GCC allows qualified id and any Objective-C type to devolve to
6846       // id. Currently localizing to here until clear this should be
6847       // part of ObjCQualifiedIdTypesAreCompatible.
6848       compositeType = Context.getObjCIdType();
6849     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6850       compositeType = Context.getObjCIdType();
6851     } else {
6852       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6853       << LHSTy << RHSTy
6854       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6855       QualType incompatTy = Context.getObjCIdType();
6856       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6857       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6858       return incompatTy;
6859     }
6860     // The object pointer types are compatible.
6861     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6862     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6863     return compositeType;
6864   }
6865   // Check Objective-C object pointer types and 'void *'
6866   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6867     if (getLangOpts().ObjCAutoRefCount) {
6868       // ARC forbids the implicit conversion of object pointers to 'void *',
6869       // so these types are not compatible.
6870       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6871           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6872       LHS = RHS = true;
6873       return QualType();
6874     }
6875     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6876     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6877     QualType destPointee
6878     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6879     QualType destType = Context.getPointerType(destPointee);
6880     // Add qualifiers if necessary.
6881     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6882     // Promote to void*.
6883     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6884     return destType;
6885   }
6886   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6887     if (getLangOpts().ObjCAutoRefCount) {
6888       // ARC forbids the implicit conversion of object pointers to 'void *',
6889       // so these types are not compatible.
6890       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6891           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6892       LHS = RHS = true;
6893       return QualType();
6894     }
6895     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6896     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6897     QualType destPointee
6898     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6899     QualType destType = Context.getPointerType(destPointee);
6900     // Add qualifiers if necessary.
6901     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6902     // Promote to void*.
6903     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6904     return destType;
6905   }
6906   return QualType();
6907 }
6908
6909 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6910 /// ParenRange in parentheses.
6911 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6912                                const PartialDiagnostic &Note,
6913                                SourceRange ParenRange) {
6914   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6915   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6916       EndLoc.isValid()) {
6917     Self.Diag(Loc, Note)
6918       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6919       << FixItHint::CreateInsertion(EndLoc, ")");
6920   } else {
6921     // We can't display the parentheses, so just show the bare note.
6922     Self.Diag(Loc, Note) << ParenRange;
6923   }
6924 }
6925
6926 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6927   return BinaryOperator::isAdditiveOp(Opc) ||
6928          BinaryOperator::isMultiplicativeOp(Opc) ||
6929          BinaryOperator::isShiftOp(Opc);
6930 }
6931
6932 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6933 /// expression, either using a built-in or overloaded operator,
6934 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6935 /// expression.
6936 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6937                                    Expr **RHSExprs) {
6938   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6939   E = E->IgnoreImpCasts();
6940   E = E->IgnoreConversionOperator();
6941   E = E->IgnoreImpCasts();
6942
6943   // Built-in binary operator.
6944   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6945     if (IsArithmeticOp(OP->getOpcode())) {
6946       *Opcode = OP->getOpcode();
6947       *RHSExprs = OP->getRHS();
6948       return true;
6949     }
6950   }
6951
6952   // Overloaded operator.
6953   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6954     if (Call->getNumArgs() != 2)
6955       return false;
6956
6957     // Make sure this is really a binary operator that is safe to pass into
6958     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6959     OverloadedOperatorKind OO = Call->getOperator();
6960     if (OO < OO_Plus || OO > OO_Arrow ||
6961         OO == OO_PlusPlus || OO == OO_MinusMinus)
6962       return false;
6963
6964     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6965     if (IsArithmeticOp(OpKind)) {
6966       *Opcode = OpKind;
6967       *RHSExprs = Call->getArg(1);
6968       return true;
6969     }
6970   }
6971
6972   return false;
6973 }
6974
6975 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6976 /// or is a logical expression such as (x==y) which has int type, but is
6977 /// commonly interpreted as boolean.
6978 static bool ExprLooksBoolean(Expr *E) {
6979   E = E->IgnoreParenImpCasts();
6980
6981   if (E->getType()->isBooleanType())
6982     return true;
6983   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6984     return OP->isComparisonOp() || OP->isLogicalOp();
6985   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6986     return OP->getOpcode() == UO_LNot;
6987   if (E->getType()->isPointerType())
6988     return true;
6989
6990   return false;
6991 }
6992
6993 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6994 /// and binary operator are mixed in a way that suggests the programmer assumed
6995 /// the conditional operator has higher precedence, for example:
6996 /// "int x = a + someBinaryCondition ? 1 : 2".
6997 static void DiagnoseConditionalPrecedence(Sema &Self,
6998                                           SourceLocation OpLoc,
6999                                           Expr *Condition,
7000                                           Expr *LHSExpr,
7001                                           Expr *RHSExpr) {
7002   BinaryOperatorKind CondOpcode;
7003   Expr *CondRHS;
7004
7005   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7006     return;
7007   if (!ExprLooksBoolean(CondRHS))
7008     return;
7009
7010   // The condition is an arithmetic binary expression, with a right-
7011   // hand side that looks boolean, so warn.
7012
7013   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7014       << Condition->getSourceRange()
7015       << BinaryOperator::getOpcodeStr(CondOpcode);
7016
7017   SuggestParentheses(Self, OpLoc,
7018     Self.PDiag(diag::note_precedence_silence)
7019       << BinaryOperator::getOpcodeStr(CondOpcode),
7020     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7021
7022   SuggestParentheses(Self, OpLoc,
7023     Self.PDiag(diag::note_precedence_conditional_first),
7024     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7025 }
7026
7027 /// Compute the nullability of a conditional expression.
7028 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7029                                               QualType LHSTy, QualType RHSTy,
7030                                               ASTContext &Ctx) {
7031   if (!ResTy->isAnyPointerType())
7032     return ResTy;
7033
7034   auto GetNullability = [&Ctx](QualType Ty) {
7035     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7036     if (Kind)
7037       return *Kind;
7038     return NullabilityKind::Unspecified;
7039   };
7040
7041   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7042   NullabilityKind MergedKind;
7043
7044   // Compute nullability of a binary conditional expression.
7045   if (IsBin) {
7046     if (LHSKind == NullabilityKind::NonNull)
7047       MergedKind = NullabilityKind::NonNull;
7048     else
7049       MergedKind = RHSKind;
7050   // Compute nullability of a normal conditional expression.
7051   } else {
7052     if (LHSKind == NullabilityKind::Nullable ||
7053         RHSKind == NullabilityKind::Nullable)
7054       MergedKind = NullabilityKind::Nullable;
7055     else if (LHSKind == NullabilityKind::NonNull)
7056       MergedKind = RHSKind;
7057     else if (RHSKind == NullabilityKind::NonNull)
7058       MergedKind = LHSKind;
7059     else
7060       MergedKind = NullabilityKind::Unspecified;
7061   }
7062
7063   // Return if ResTy already has the correct nullability.
7064   if (GetNullability(ResTy) == MergedKind)
7065     return ResTy;
7066
7067   // Strip all nullability from ResTy.
7068   while (ResTy->getNullability(Ctx))
7069     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7070
7071   // Create a new AttributedType with the new nullability kind.
7072   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7073   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7074 }
7075
7076 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7077 /// in the case of a the GNU conditional expr extension.
7078 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7079                                     SourceLocation ColonLoc,
7080                                     Expr *CondExpr, Expr *LHSExpr,
7081                                     Expr *RHSExpr) {
7082   if (!getLangOpts().CPlusPlus) {
7083     // C cannot handle TypoExpr nodes in the condition because it
7084     // doesn't handle dependent types properly, so make sure any TypoExprs have
7085     // been dealt with before checking the operands.
7086     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7087     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7088     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7089
7090     if (!CondResult.isUsable())
7091       return ExprError();
7092
7093     if (LHSExpr) {
7094       if (!LHSResult.isUsable())
7095         return ExprError();
7096     }
7097
7098     if (!RHSResult.isUsable())
7099       return ExprError();
7100
7101     CondExpr = CondResult.get();
7102     LHSExpr = LHSResult.get();
7103     RHSExpr = RHSResult.get();
7104   }
7105
7106   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7107   // was the condition.
7108   OpaqueValueExpr *opaqueValue = nullptr;
7109   Expr *commonExpr = nullptr;
7110   if (!LHSExpr) {
7111     commonExpr = CondExpr;
7112     // Lower out placeholder types first.  This is important so that we don't
7113     // try to capture a placeholder. This happens in few cases in C++; such
7114     // as Objective-C++'s dictionary subscripting syntax.
7115     if (commonExpr->hasPlaceholderType()) {
7116       ExprResult result = CheckPlaceholderExpr(commonExpr);
7117       if (!result.isUsable()) return ExprError();
7118       commonExpr = result.get();
7119     }
7120     // We usually want to apply unary conversions *before* saving, except
7121     // in the special case of a C++ l-value conditional.
7122     if (!(getLangOpts().CPlusPlus
7123           && !commonExpr->isTypeDependent()
7124           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7125           && commonExpr->isGLValue()
7126           && commonExpr->isOrdinaryOrBitFieldObject()
7127           && RHSExpr->isOrdinaryOrBitFieldObject()
7128           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7129       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7130       if (commonRes.isInvalid())
7131         return ExprError();
7132       commonExpr = commonRes.get();
7133     }
7134
7135     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7136                                                 commonExpr->getType(),
7137                                                 commonExpr->getValueKind(),
7138                                                 commonExpr->getObjectKind(),
7139                                                 commonExpr);
7140     LHSExpr = CondExpr = opaqueValue;
7141   }
7142
7143   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7144   ExprValueKind VK = VK_RValue;
7145   ExprObjectKind OK = OK_Ordinary;
7146   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7147   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
7148                                              VK, OK, QuestionLoc);
7149   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7150       RHS.isInvalid())
7151     return ExprError();
7152
7153   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7154                                 RHS.get());
7155
7156   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7157
7158   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7159                                          Context);
7160
7161   if (!commonExpr)
7162     return new (Context)
7163         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7164                             RHS.get(), result, VK, OK);
7165
7166   return new (Context) BinaryConditionalOperator(
7167       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7168       ColonLoc, result, VK, OK);
7169 }
7170
7171 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7172 // being closely modeled after the C99 spec:-). The odd characteristic of this
7173 // routine is it effectively iqnores the qualifiers on the top level pointee.
7174 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7175 // FIXME: add a couple examples in this comment.
7176 static Sema::AssignConvertType
7177 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7178   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7179   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7180
7181   // get the "pointed to" type (ignoring qualifiers at the top level)
7182   const Type *lhptee, *rhptee;
7183   Qualifiers lhq, rhq;
7184   std::tie(lhptee, lhq) =
7185       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7186   std::tie(rhptee, rhq) =
7187       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7188
7189   Sema::AssignConvertType ConvTy = Sema::Compatible;
7190
7191   // C99 6.5.16.1p1: This following citation is common to constraints
7192   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7193   // qualifiers of the type *pointed to* by the right;
7194
7195   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7196   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7197       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7198     // Ignore lifetime for further calculation.
7199     lhq.removeObjCLifetime();
7200     rhq.removeObjCLifetime();
7201   }
7202
7203   if (!lhq.compatiblyIncludes(rhq)) {
7204     // Treat address-space mismatches as fatal.  TODO: address subspaces
7205     if (!lhq.isAddressSpaceSupersetOf(rhq))
7206       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7207
7208     // It's okay to add or remove GC or lifetime qualifiers when converting to
7209     // and from void*.
7210     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7211                         .compatiblyIncludes(
7212                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7213              && (lhptee->isVoidType() || rhptee->isVoidType()))
7214       ; // keep old
7215
7216     // Treat lifetime mismatches as fatal.
7217     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7218       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7219     
7220     // For GCC/MS compatibility, other qualifier mismatches are treated
7221     // as still compatible in C.
7222     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7223   }
7224
7225   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7226   // incomplete type and the other is a pointer to a qualified or unqualified
7227   // version of void...
7228   if (lhptee->isVoidType()) {
7229     if (rhptee->isIncompleteOrObjectType())
7230       return ConvTy;
7231
7232     // As an extension, we allow cast to/from void* to function pointer.
7233     assert(rhptee->isFunctionType());
7234     return Sema::FunctionVoidPointer;
7235   }
7236
7237   if (rhptee->isVoidType()) {
7238     if (lhptee->isIncompleteOrObjectType())
7239       return ConvTy;
7240
7241     // As an extension, we allow cast to/from void* to function pointer.
7242     assert(lhptee->isFunctionType());
7243     return Sema::FunctionVoidPointer;
7244   }
7245
7246   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7247   // unqualified versions of compatible types, ...
7248   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7249   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7250     // Check if the pointee types are compatible ignoring the sign.
7251     // We explicitly check for char so that we catch "char" vs
7252     // "unsigned char" on systems where "char" is unsigned.
7253     if (lhptee->isCharType())
7254       ltrans = S.Context.UnsignedCharTy;
7255     else if (lhptee->hasSignedIntegerRepresentation())
7256       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7257
7258     if (rhptee->isCharType())
7259       rtrans = S.Context.UnsignedCharTy;
7260     else if (rhptee->hasSignedIntegerRepresentation())
7261       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7262
7263     if (ltrans == rtrans) {
7264       // Types are compatible ignoring the sign. Qualifier incompatibility
7265       // takes priority over sign incompatibility because the sign
7266       // warning can be disabled.
7267       if (ConvTy != Sema::Compatible)
7268         return ConvTy;
7269
7270       return Sema::IncompatiblePointerSign;
7271     }
7272
7273     // If we are a multi-level pointer, it's possible that our issue is simply
7274     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7275     // the eventual target type is the same and the pointers have the same
7276     // level of indirection, this must be the issue.
7277     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7278       do {
7279         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7280         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7281       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7282
7283       if (lhptee == rhptee)
7284         return Sema::IncompatibleNestedPointerQualifiers;
7285     }
7286
7287     // General pointer incompatibility takes priority over qualifiers.
7288     return Sema::IncompatiblePointer;
7289   }
7290   if (!S.getLangOpts().CPlusPlus &&
7291       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7292     return Sema::IncompatiblePointer;
7293   return ConvTy;
7294 }
7295
7296 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7297 /// block pointer types are compatible or whether a block and normal pointer
7298 /// are compatible. It is more restrict than comparing two function pointer
7299 // types.
7300 static Sema::AssignConvertType
7301 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7302                                     QualType RHSType) {
7303   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7304   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7305
7306   QualType lhptee, rhptee;
7307
7308   // get the "pointed to" type (ignoring qualifiers at the top level)
7309   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7310   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7311
7312   // In C++, the types have to match exactly.
7313   if (S.getLangOpts().CPlusPlus)
7314     return Sema::IncompatibleBlockPointer;
7315
7316   Sema::AssignConvertType ConvTy = Sema::Compatible;
7317
7318   // For blocks we enforce that qualifiers are identical.
7319   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7320     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7321
7322   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7323     return Sema::IncompatibleBlockPointer;
7324
7325   return ConvTy;
7326 }
7327
7328 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7329 /// for assignment compatibility.
7330 static Sema::AssignConvertType
7331 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7332                                    QualType RHSType) {
7333   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7334   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7335
7336   if (LHSType->isObjCBuiltinType()) {
7337     // Class is not compatible with ObjC object pointers.
7338     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7339         !RHSType->isObjCQualifiedClassType())
7340       return Sema::IncompatiblePointer;
7341     return Sema::Compatible;
7342   }
7343   if (RHSType->isObjCBuiltinType()) {
7344     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7345         !LHSType->isObjCQualifiedClassType())
7346       return Sema::IncompatiblePointer;
7347     return Sema::Compatible;
7348   }
7349   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7350   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7351
7352   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7353       // make an exception for id<P>
7354       !LHSType->isObjCQualifiedIdType())
7355     return Sema::CompatiblePointerDiscardsQualifiers;
7356
7357   if (S.Context.typesAreCompatible(LHSType, RHSType))
7358     return Sema::Compatible;
7359   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7360     return Sema::IncompatibleObjCQualifiedId;
7361   return Sema::IncompatiblePointer;
7362 }
7363
7364 Sema::AssignConvertType
7365 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7366                                  QualType LHSType, QualType RHSType) {
7367   // Fake up an opaque expression.  We don't actually care about what
7368   // cast operations are required, so if CheckAssignmentConstraints
7369   // adds casts to this they'll be wasted, but fortunately that doesn't
7370   // usually happen on valid code.
7371   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7372   ExprResult RHSPtr = &RHSExpr;
7373   CastKind K = CK_Invalid;
7374
7375   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7376 }
7377
7378 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7379 /// has code to accommodate several GCC extensions when type checking
7380 /// pointers. Here are some objectionable examples that GCC considers warnings:
7381 ///
7382 ///  int a, *pint;
7383 ///  short *pshort;
7384 ///  struct foo *pfoo;
7385 ///
7386 ///  pint = pshort; // warning: assignment from incompatible pointer type
7387 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7388 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7389 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7390 ///
7391 /// As a result, the code for dealing with pointers is more complex than the
7392 /// C99 spec dictates.
7393 ///
7394 /// Sets 'Kind' for any result kind except Incompatible.
7395 Sema::AssignConvertType
7396 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7397                                  CastKind &Kind, bool ConvertRHS) {
7398   QualType RHSType = RHS.get()->getType();
7399   QualType OrigLHSType = LHSType;
7400
7401   // Get canonical types.  We're not formatting these types, just comparing
7402   // them.
7403   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7404   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7405
7406   // Common case: no conversion required.
7407   if (LHSType == RHSType) {
7408     Kind = CK_NoOp;
7409     return Compatible;
7410   }
7411
7412   // If we have an atomic type, try a non-atomic assignment, then just add an
7413   // atomic qualification step.
7414   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7415     Sema::AssignConvertType result =
7416       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7417     if (result != Compatible)
7418       return result;
7419     if (Kind != CK_NoOp && ConvertRHS)
7420       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7421     Kind = CK_NonAtomicToAtomic;
7422     return Compatible;
7423   }
7424
7425   // If the left-hand side is a reference type, then we are in a
7426   // (rare!) case where we've allowed the use of references in C,
7427   // e.g., as a parameter type in a built-in function. In this case,
7428   // just make sure that the type referenced is compatible with the
7429   // right-hand side type. The caller is responsible for adjusting
7430   // LHSType so that the resulting expression does not have reference
7431   // type.
7432   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7433     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7434       Kind = CK_LValueBitCast;
7435       return Compatible;
7436     }
7437     return Incompatible;
7438   }
7439
7440   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7441   // to the same ExtVector type.
7442   if (LHSType->isExtVectorType()) {
7443     if (RHSType->isExtVectorType())
7444       return Incompatible;
7445     if (RHSType->isArithmeticType()) {
7446       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7447       if (ConvertRHS)
7448         RHS = prepareVectorSplat(LHSType, RHS.get());
7449       Kind = CK_VectorSplat;
7450       return Compatible;
7451     }
7452   }
7453
7454   // Conversions to or from vector type.
7455   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7456     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7457       // Allow assignments of an AltiVec vector type to an equivalent GCC
7458       // vector type and vice versa
7459       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7460         Kind = CK_BitCast;
7461         return Compatible;
7462       }
7463
7464       // If we are allowing lax vector conversions, and LHS and RHS are both
7465       // vectors, the total size only needs to be the same. This is a bitcast;
7466       // no bits are changed but the result type is different.
7467       if (isLaxVectorConversion(RHSType, LHSType)) {
7468         Kind = CK_BitCast;
7469         return IncompatibleVectors;
7470       }
7471     }
7472
7473     // When the RHS comes from another lax conversion (e.g. binops between
7474     // scalars and vectors) the result is canonicalized as a vector. When the
7475     // LHS is also a vector, the lax is allowed by the condition above. Handle
7476     // the case where LHS is a scalar.
7477     if (LHSType->isScalarType()) {
7478       const VectorType *VecType = RHSType->getAs<VectorType>();
7479       if (VecType && VecType->getNumElements() == 1 &&
7480           isLaxVectorConversion(RHSType, LHSType)) {
7481         ExprResult *VecExpr = &RHS;
7482         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7483         Kind = CK_BitCast;
7484         return Compatible;
7485       }
7486     }
7487
7488     return Incompatible;
7489   }
7490
7491   // Diagnose attempts to convert between __float128 and long double where
7492   // such conversions currently can't be handled.
7493   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7494     return Incompatible;
7495
7496   // Arithmetic conversions.
7497   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7498       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7499     if (ConvertRHS)
7500       Kind = PrepareScalarCast(RHS, LHSType);
7501     return Compatible;
7502   }
7503
7504   // Conversions to normal pointers.
7505   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7506     // U* -> T*
7507     if (isa<PointerType>(RHSType)) {
7508       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7509       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7510       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7511       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7512     }
7513
7514     // int -> T*
7515     if (RHSType->isIntegerType()) {
7516       Kind = CK_IntegralToPointer; // FIXME: null?
7517       return IntToPointer;
7518     }
7519
7520     // C pointers are not compatible with ObjC object pointers,
7521     // with two exceptions:
7522     if (isa<ObjCObjectPointerType>(RHSType)) {
7523       //  - conversions to void*
7524       if (LHSPointer->getPointeeType()->isVoidType()) {
7525         Kind = CK_BitCast;
7526         return Compatible;
7527       }
7528
7529       //  - conversions from 'Class' to the redefinition type
7530       if (RHSType->isObjCClassType() &&
7531           Context.hasSameType(LHSType, 
7532                               Context.getObjCClassRedefinitionType())) {
7533         Kind = CK_BitCast;
7534         return Compatible;
7535       }
7536
7537       Kind = CK_BitCast;
7538       return IncompatiblePointer;
7539     }
7540
7541     // U^ -> void*
7542     if (RHSType->getAs<BlockPointerType>()) {
7543       if (LHSPointer->getPointeeType()->isVoidType()) {
7544         Kind = CK_BitCast;
7545         return Compatible;
7546       }
7547     }
7548
7549     return Incompatible;
7550   }
7551
7552   // Conversions to block pointers.
7553   if (isa<BlockPointerType>(LHSType)) {
7554     // U^ -> T^
7555     if (RHSType->isBlockPointerType()) {
7556       Kind = CK_BitCast;
7557       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7558     }
7559
7560     // int or null -> T^
7561     if (RHSType->isIntegerType()) {
7562       Kind = CK_IntegralToPointer; // FIXME: null
7563       return IntToBlockPointer;
7564     }
7565
7566     // id -> T^
7567     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7568       Kind = CK_AnyPointerToBlockPointerCast;
7569       return Compatible;
7570     }
7571
7572     // void* -> T^
7573     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7574       if (RHSPT->getPointeeType()->isVoidType()) {
7575         Kind = CK_AnyPointerToBlockPointerCast;
7576         return Compatible;
7577       }
7578
7579     return Incompatible;
7580   }
7581
7582   // Conversions to Objective-C pointers.
7583   if (isa<ObjCObjectPointerType>(LHSType)) {
7584     // A* -> B*
7585     if (RHSType->isObjCObjectPointerType()) {
7586       Kind = CK_BitCast;
7587       Sema::AssignConvertType result = 
7588         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7589       if (getLangOpts().ObjCAutoRefCount &&
7590           result == Compatible && 
7591           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7592         result = IncompatibleObjCWeakRef;
7593       return result;
7594     }
7595
7596     // int or null -> A*
7597     if (RHSType->isIntegerType()) {
7598       Kind = CK_IntegralToPointer; // FIXME: null
7599       return IntToPointer;
7600     }
7601
7602     // In general, C pointers are not compatible with ObjC object pointers,
7603     // with two exceptions:
7604     if (isa<PointerType>(RHSType)) {
7605       Kind = CK_CPointerToObjCPointerCast;
7606
7607       //  - conversions from 'void*'
7608       if (RHSType->isVoidPointerType()) {
7609         return Compatible;
7610       }
7611
7612       //  - conversions to 'Class' from its redefinition type
7613       if (LHSType->isObjCClassType() &&
7614           Context.hasSameType(RHSType, 
7615                               Context.getObjCClassRedefinitionType())) {
7616         return Compatible;
7617       }
7618
7619       return IncompatiblePointer;
7620     }
7621
7622     // Only under strict condition T^ is compatible with an Objective-C pointer.
7623     if (RHSType->isBlockPointerType() && 
7624         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7625       if (ConvertRHS)
7626         maybeExtendBlockObject(RHS);
7627       Kind = CK_BlockPointerToObjCPointerCast;
7628       return Compatible;
7629     }
7630
7631     return Incompatible;
7632   }
7633
7634   // Conversions from pointers that are not covered by the above.
7635   if (isa<PointerType>(RHSType)) {
7636     // T* -> _Bool
7637     if (LHSType == Context.BoolTy) {
7638       Kind = CK_PointerToBoolean;
7639       return Compatible;
7640     }
7641
7642     // T* -> int
7643     if (LHSType->isIntegerType()) {
7644       Kind = CK_PointerToIntegral;
7645       return PointerToInt;
7646     }
7647
7648     return Incompatible;
7649   }
7650
7651   // Conversions from Objective-C pointers that are not covered by the above.
7652   if (isa<ObjCObjectPointerType>(RHSType)) {
7653     // T* -> _Bool
7654     if (LHSType == Context.BoolTy) {
7655       Kind = CK_PointerToBoolean;
7656       return Compatible;
7657     }
7658
7659     // T* -> int
7660     if (LHSType->isIntegerType()) {
7661       Kind = CK_PointerToIntegral;
7662       return PointerToInt;
7663     }
7664
7665     return Incompatible;
7666   }
7667
7668   // struct A -> struct B
7669   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7670     if (Context.typesAreCompatible(LHSType, RHSType)) {
7671       Kind = CK_NoOp;
7672       return Compatible;
7673     }
7674   }
7675
7676   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7677     Kind = CK_IntToOCLSampler;
7678     return Compatible;
7679   }
7680
7681   return Incompatible;
7682 }
7683
7684 /// \brief Constructs a transparent union from an expression that is
7685 /// used to initialize the transparent union.
7686 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7687                                       ExprResult &EResult, QualType UnionType,
7688                                       FieldDecl *Field) {
7689   // Build an initializer list that designates the appropriate member
7690   // of the transparent union.
7691   Expr *E = EResult.get();
7692   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7693                                                    E, SourceLocation());
7694   Initializer->setType(UnionType);
7695   Initializer->setInitializedFieldInUnion(Field);
7696
7697   // Build a compound literal constructing a value of the transparent
7698   // union type from this initializer list.
7699   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7700   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7701                                         VK_RValue, Initializer, false);
7702 }
7703
7704 Sema::AssignConvertType
7705 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7706                                                ExprResult &RHS) {
7707   QualType RHSType = RHS.get()->getType();
7708
7709   // If the ArgType is a Union type, we want to handle a potential
7710   // transparent_union GCC extension.
7711   const RecordType *UT = ArgType->getAsUnionType();
7712   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7713     return Incompatible;
7714
7715   // The field to initialize within the transparent union.
7716   RecordDecl *UD = UT->getDecl();
7717   FieldDecl *InitField = nullptr;
7718   // It's compatible if the expression matches any of the fields.
7719   for (auto *it : UD->fields()) {
7720     if (it->getType()->isPointerType()) {
7721       // If the transparent union contains a pointer type, we allow:
7722       // 1) void pointer
7723       // 2) null pointer constant
7724       if (RHSType->isPointerType())
7725         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7726           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7727           InitField = it;
7728           break;
7729         }
7730
7731       if (RHS.get()->isNullPointerConstant(Context,
7732                                            Expr::NPC_ValueDependentIsNull)) {
7733         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7734                                 CK_NullToPointer);
7735         InitField = it;
7736         break;
7737       }
7738     }
7739
7740     CastKind Kind = CK_Invalid;
7741     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7742           == Compatible) {
7743       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7744       InitField = it;
7745       break;
7746     }
7747   }
7748
7749   if (!InitField)
7750     return Incompatible;
7751
7752   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7753   return Compatible;
7754 }
7755
7756 Sema::AssignConvertType
7757 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7758                                        bool Diagnose,
7759                                        bool DiagnoseCFAudited,
7760                                        bool ConvertRHS) {
7761   // We need to be able to tell the caller whether we diagnosed a problem, if
7762   // they ask us to issue diagnostics.
7763   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7764
7765   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7766   // we can't avoid *all* modifications at the moment, so we need some somewhere
7767   // to put the updated value.
7768   ExprResult LocalRHS = CallerRHS;
7769   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7770
7771   if (getLangOpts().CPlusPlus) {
7772     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7773       // C++ 5.17p3: If the left operand is not of class type, the
7774       // expression is implicitly converted (C++ 4) to the
7775       // cv-unqualified type of the left operand.
7776       QualType RHSType = RHS.get()->getType();
7777       if (Diagnose) {
7778         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7779                                         AA_Assigning);
7780       } else {
7781         ImplicitConversionSequence ICS =
7782             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7783                                   /*SuppressUserConversions=*/false,
7784                                   /*AllowExplicit=*/false,
7785                                   /*InOverloadResolution=*/false,
7786                                   /*CStyle=*/false,
7787                                   /*AllowObjCWritebackConversion=*/false);
7788         if (ICS.isFailure())
7789           return Incompatible;
7790         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7791                                         ICS, AA_Assigning);
7792       }
7793       if (RHS.isInvalid())
7794         return Incompatible;
7795       Sema::AssignConvertType result = Compatible;
7796       if (getLangOpts().ObjCAutoRefCount &&
7797           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7798         result = IncompatibleObjCWeakRef;
7799       return result;
7800     }
7801
7802     // FIXME: Currently, we fall through and treat C++ classes like C
7803     // structures.
7804     // FIXME: We also fall through for atomics; not sure what should
7805     // happen there, though.
7806   } else if (RHS.get()->getType() == Context.OverloadTy) {
7807     // As a set of extensions to C, we support overloading on functions. These
7808     // functions need to be resolved here.
7809     DeclAccessPair DAP;
7810     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7811             RHS.get(), LHSType, /*Complain=*/false, DAP))
7812       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7813     else
7814       return Incompatible;
7815   }
7816
7817   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7818   // a null pointer constant.
7819   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7820        LHSType->isBlockPointerType()) &&
7821       RHS.get()->isNullPointerConstant(Context,
7822                                        Expr::NPC_ValueDependentIsNull)) {
7823     if (Diagnose || ConvertRHS) {
7824       CastKind Kind;
7825       CXXCastPath Path;
7826       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7827                              /*IgnoreBaseAccess=*/false, Diagnose);
7828       if (ConvertRHS)
7829         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7830     }
7831     return Compatible;
7832   }
7833
7834   // This check seems unnatural, however it is necessary to ensure the proper
7835   // conversion of functions/arrays. If the conversion were done for all
7836   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7837   // expressions that suppress this implicit conversion (&, sizeof).
7838   //
7839   // Suppress this for references: C++ 8.5.3p5.
7840   if (!LHSType->isReferenceType()) {
7841     // FIXME: We potentially allocate here even if ConvertRHS is false.
7842     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7843     if (RHS.isInvalid())
7844       return Incompatible;
7845   }
7846
7847   Expr *PRE = RHS.get()->IgnoreParenCasts();
7848   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7849     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7850     if (PDecl && !PDecl->hasDefinition()) {
7851       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7852       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7853     }
7854   }
7855   
7856   CastKind Kind = CK_Invalid;
7857   Sema::AssignConvertType result =
7858     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7859
7860   // C99 6.5.16.1p2: The value of the right operand is converted to the
7861   // type of the assignment expression.
7862   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7863   // so that we can use references in built-in functions even in C.
7864   // The getNonReferenceType() call makes sure that the resulting expression
7865   // does not have reference type.
7866   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7867     QualType Ty = LHSType.getNonLValueExprType(Context);
7868     Expr *E = RHS.get();
7869
7870     // Check for various Objective-C errors. If we are not reporting
7871     // diagnostics and just checking for errors, e.g., during overload
7872     // resolution, return Incompatible to indicate the failure.
7873     if (getLangOpts().ObjCAutoRefCount &&
7874         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7875                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7876       if (!Diagnose)
7877         return Incompatible;
7878     }
7879     if (getLangOpts().ObjC1 &&
7880         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7881                                            E->getType(), E, Diagnose) ||
7882          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7883       if (!Diagnose)
7884         return Incompatible;
7885       // Replace the expression with a corrected version and continue so we
7886       // can find further errors.
7887       RHS = E;
7888       return Compatible;
7889     }
7890     
7891     if (ConvertRHS)
7892       RHS = ImpCastExprToType(E, Ty, Kind);
7893   }
7894   return result;
7895 }
7896
7897 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7898                                ExprResult &RHS) {
7899   Diag(Loc, diag::err_typecheck_invalid_operands)
7900     << LHS.get()->getType() << RHS.get()->getType()
7901     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7902   return QualType();
7903 }
7904
7905 /// Try to convert a value of non-vector type to a vector type by converting
7906 /// the type to the element type of the vector and then performing a splat.
7907 /// If the language is OpenCL, we only use conversions that promote scalar
7908 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7909 /// for float->int.
7910 ///
7911 /// \param scalar - if non-null, actually perform the conversions
7912 /// \return true if the operation fails (but without diagnosing the failure)
7913 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7914                                      QualType scalarTy,
7915                                      QualType vectorEltTy,
7916                                      QualType vectorTy) {
7917   // The conversion to apply to the scalar before splatting it,
7918   // if necessary.
7919   CastKind scalarCast = CK_Invalid;
7920   
7921   if (vectorEltTy->isIntegralType(S.Context)) {
7922     if (!scalarTy->isIntegralType(S.Context))
7923       return true;
7924     if (S.getLangOpts().OpenCL &&
7925         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7926       return true;
7927     scalarCast = CK_IntegralCast;
7928   } else if (vectorEltTy->isRealFloatingType()) {
7929     if (scalarTy->isRealFloatingType()) {
7930       if (S.getLangOpts().OpenCL &&
7931           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7932         return true;
7933       scalarCast = CK_FloatingCast;
7934     }
7935     else if (scalarTy->isIntegralType(S.Context))
7936       scalarCast = CK_IntegralToFloating;
7937     else
7938       return true;
7939   } else {
7940     return true;
7941   }
7942
7943   // Adjust scalar if desired.
7944   if (scalar) {
7945     if (scalarCast != CK_Invalid)
7946       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7947     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7948   }
7949   return false;
7950 }
7951
7952 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7953                                    SourceLocation Loc, bool IsCompAssign,
7954                                    bool AllowBothBool,
7955                                    bool AllowBoolConversions) {
7956   if (!IsCompAssign) {
7957     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7958     if (LHS.isInvalid())
7959       return QualType();
7960   }
7961   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7962   if (RHS.isInvalid())
7963     return QualType();
7964
7965   // For conversion purposes, we ignore any qualifiers.
7966   // For example, "const float" and "float" are equivalent.
7967   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7968   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7969
7970   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7971   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7972   assert(LHSVecType || RHSVecType);
7973
7974   // AltiVec-style "vector bool op vector bool" combinations are allowed
7975   // for some operators but not others.
7976   if (!AllowBothBool &&
7977       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7978       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7979     return InvalidOperands(Loc, LHS, RHS);
7980
7981   // If the vector types are identical, return.
7982   if (Context.hasSameType(LHSType, RHSType))
7983     return LHSType;
7984
7985   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7986   if (LHSVecType && RHSVecType &&
7987       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7988     if (isa<ExtVectorType>(LHSVecType)) {
7989       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7990       return LHSType;
7991     }
7992
7993     if (!IsCompAssign)
7994       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7995     return RHSType;
7996   }
7997
7998   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7999   // can be mixed, with the result being the non-bool type.  The non-bool
8000   // operand must have integer element type.
8001   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8002       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8003       (Context.getTypeSize(LHSVecType->getElementType()) ==
8004        Context.getTypeSize(RHSVecType->getElementType()))) {
8005     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8006         LHSVecType->getElementType()->isIntegerType() &&
8007         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8008       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8009       return LHSType;
8010     }
8011     if (!IsCompAssign &&
8012         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8013         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8014         RHSVecType->getElementType()->isIntegerType()) {
8015       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8016       return RHSType;
8017     }
8018   }
8019
8020   // If there's an ext-vector type and a scalar, try to convert the scalar to
8021   // the vector element type and splat.
8022   // FIXME: this should also work for regular vector types as supported in GCC.
8023   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8024     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8025                                   LHSVecType->getElementType(), LHSType))
8026       return LHSType;
8027   }
8028   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8029     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8030                                   LHSType, RHSVecType->getElementType(),
8031                                   RHSType))
8032       return RHSType;
8033   }
8034
8035   // FIXME: The code below also handles convertion between vectors and
8036   // non-scalars, we should break this down into fine grained specific checks
8037   // and emit proper diagnostics.
8038   QualType VecType = LHSVecType ? LHSType : RHSType;
8039   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8040   QualType OtherType = LHSVecType ? RHSType : LHSType;
8041   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8042   if (isLaxVectorConversion(OtherType, VecType)) {
8043     // If we're allowing lax vector conversions, only the total (data) size
8044     // needs to be the same. For non compound assignment, if one of the types is
8045     // scalar, the result is always the vector type.
8046     if (!IsCompAssign) {
8047       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8048       return VecType;
8049     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8050     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8051     // type. Note that this is already done by non-compound assignments in
8052     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8053     // <1 x T> -> T. The result is also a vector type.
8054     } else if (OtherType->isExtVectorType() ||
8055                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8056       ExprResult *RHSExpr = &RHS;
8057       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8058       return VecType;
8059     }
8060   }
8061
8062   // Okay, the expression is invalid.
8063
8064   // If there's a non-vector, non-real operand, diagnose that.
8065   if ((!RHSVecType && !RHSType->isRealType()) ||
8066       (!LHSVecType && !LHSType->isRealType())) {
8067     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8068       << LHSType << RHSType
8069       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8070     return QualType();
8071   }
8072
8073   // OpenCL V1.1 6.2.6.p1:
8074   // If the operands are of more than one vector type, then an error shall
8075   // occur. Implicit conversions between vector types are not permitted, per
8076   // section 6.2.1.
8077   if (getLangOpts().OpenCL &&
8078       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8079       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8080     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8081                                                            << RHSType;
8082     return QualType();
8083   }
8084
8085   // Otherwise, use the generic diagnostic.
8086   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8087     << LHSType << RHSType
8088     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8089   return QualType();
8090 }
8091
8092 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8093 // expression.  These are mainly cases where the null pointer is used as an
8094 // integer instead of a pointer.
8095 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8096                                 SourceLocation Loc, bool IsCompare) {
8097   // The canonical way to check for a GNU null is with isNullPointerConstant,
8098   // but we use a bit of a hack here for speed; this is a relatively
8099   // hot path, and isNullPointerConstant is slow.
8100   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8101   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8102
8103   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8104
8105   // Avoid analyzing cases where the result will either be invalid (and
8106   // diagnosed as such) or entirely valid and not something to warn about.
8107   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8108       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8109     return;
8110
8111   // Comparison operations would not make sense with a null pointer no matter
8112   // what the other expression is.
8113   if (!IsCompare) {
8114     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8115         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8116         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8117     return;
8118   }
8119
8120   // The rest of the operations only make sense with a null pointer
8121   // if the other expression is a pointer.
8122   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8123       NonNullType->canDecayToPointerType())
8124     return;
8125
8126   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8127       << LHSNull /* LHS is NULL */ << NonNullType
8128       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8129 }
8130
8131 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8132                                                ExprResult &RHS,
8133                                                SourceLocation Loc, bool IsDiv) {
8134   // Check for division/remainder by zero.
8135   llvm::APSInt RHSValue;
8136   if (!RHS.get()->isValueDependent() &&
8137       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8138     S.DiagRuntimeBehavior(Loc, RHS.get(),
8139                           S.PDiag(diag::warn_remainder_division_by_zero)
8140                             << IsDiv << RHS.get()->getSourceRange());
8141 }
8142
8143 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8144                                            SourceLocation Loc,
8145                                            bool IsCompAssign, bool IsDiv) {
8146   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8147
8148   if (LHS.get()->getType()->isVectorType() ||
8149       RHS.get()->getType()->isVectorType())
8150     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8151                                /*AllowBothBool*/getLangOpts().AltiVec,
8152                                /*AllowBoolConversions*/false);
8153
8154   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8155   if (LHS.isInvalid() || RHS.isInvalid())
8156     return QualType();
8157
8158
8159   if (compType.isNull() || !compType->isArithmeticType())
8160     return InvalidOperands(Loc, LHS, RHS);
8161   if (IsDiv)
8162     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8163   return compType;
8164 }
8165
8166 QualType Sema::CheckRemainderOperands(
8167   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8168   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8169
8170   if (LHS.get()->getType()->isVectorType() ||
8171       RHS.get()->getType()->isVectorType()) {
8172     if (LHS.get()->getType()->hasIntegerRepresentation() && 
8173         RHS.get()->getType()->hasIntegerRepresentation())
8174       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8175                                  /*AllowBothBool*/getLangOpts().AltiVec,
8176                                  /*AllowBoolConversions*/false);
8177     return InvalidOperands(Loc, LHS, RHS);
8178   }
8179
8180   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8181   if (LHS.isInvalid() || RHS.isInvalid())
8182     return QualType();
8183
8184   if (compType.isNull() || !compType->isIntegerType())
8185     return InvalidOperands(Loc, LHS, RHS);
8186   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8187   return compType;
8188 }
8189
8190 /// \brief Diagnose invalid arithmetic on two void pointers.
8191 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8192                                                 Expr *LHSExpr, Expr *RHSExpr) {
8193   S.Diag(Loc, S.getLangOpts().CPlusPlus
8194                 ? diag::err_typecheck_pointer_arith_void_type
8195                 : diag::ext_gnu_void_ptr)
8196     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8197                             << RHSExpr->getSourceRange();
8198 }
8199
8200 /// \brief Diagnose invalid arithmetic on a void pointer.
8201 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8202                                             Expr *Pointer) {
8203   S.Diag(Loc, S.getLangOpts().CPlusPlus
8204                 ? diag::err_typecheck_pointer_arith_void_type
8205                 : diag::ext_gnu_void_ptr)
8206     << 0 /* one pointer */ << Pointer->getSourceRange();
8207 }
8208
8209 /// \brief Diagnose invalid arithmetic on two function pointers.
8210 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8211                                                     Expr *LHS, Expr *RHS) {
8212   assert(LHS->getType()->isAnyPointerType());
8213   assert(RHS->getType()->isAnyPointerType());
8214   S.Diag(Loc, S.getLangOpts().CPlusPlus
8215                 ? diag::err_typecheck_pointer_arith_function_type
8216                 : diag::ext_gnu_ptr_func_arith)
8217     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8218     // We only show the second type if it differs from the first.
8219     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8220                                                    RHS->getType())
8221     << RHS->getType()->getPointeeType()
8222     << LHS->getSourceRange() << RHS->getSourceRange();
8223 }
8224
8225 /// \brief Diagnose invalid arithmetic on a function pointer.
8226 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8227                                                 Expr *Pointer) {
8228   assert(Pointer->getType()->isAnyPointerType());
8229   S.Diag(Loc, S.getLangOpts().CPlusPlus
8230                 ? diag::err_typecheck_pointer_arith_function_type
8231                 : diag::ext_gnu_ptr_func_arith)
8232     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8233     << 0 /* one pointer, so only one type */
8234     << Pointer->getSourceRange();
8235 }
8236
8237 /// \brief Emit error if Operand is incomplete pointer type
8238 ///
8239 /// \returns True if pointer has incomplete type
8240 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8241                                                  Expr *Operand) {
8242   QualType ResType = Operand->getType();
8243   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8244     ResType = ResAtomicType->getValueType();
8245
8246   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8247   QualType PointeeTy = ResType->getPointeeType();
8248   return S.RequireCompleteType(Loc, PointeeTy,
8249                                diag::err_typecheck_arithmetic_incomplete_type,
8250                                PointeeTy, Operand->getSourceRange());
8251 }
8252
8253 /// \brief Check the validity of an arithmetic pointer operand.
8254 ///
8255 /// If the operand has pointer type, this code will check for pointer types
8256 /// which are invalid in arithmetic operations. These will be diagnosed
8257 /// appropriately, including whether or not the use is supported as an
8258 /// extension.
8259 ///
8260 /// \returns True when the operand is valid to use (even if as an extension).
8261 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8262                                             Expr *Operand) {
8263   QualType ResType = Operand->getType();
8264   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8265     ResType = ResAtomicType->getValueType();
8266
8267   if (!ResType->isAnyPointerType()) return true;
8268
8269   QualType PointeeTy = ResType->getPointeeType();
8270   if (PointeeTy->isVoidType()) {
8271     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8272     return !S.getLangOpts().CPlusPlus;
8273   }
8274   if (PointeeTy->isFunctionType()) {
8275     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8276     return !S.getLangOpts().CPlusPlus;
8277   }
8278
8279   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8280
8281   return true;
8282 }
8283
8284 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8285 /// operands.
8286 ///
8287 /// This routine will diagnose any invalid arithmetic on pointer operands much
8288 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8289 /// for emitting a single diagnostic even for operations where both LHS and RHS
8290 /// are (potentially problematic) pointers.
8291 ///
8292 /// \returns True when the operand is valid to use (even if as an extension).
8293 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8294                                                 Expr *LHSExpr, Expr *RHSExpr) {
8295   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8296   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8297   if (!isLHSPointer && !isRHSPointer) return true;
8298
8299   QualType LHSPointeeTy, RHSPointeeTy;
8300   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8301   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8302
8303   // if both are pointers check if operation is valid wrt address spaces
8304   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8305     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8306     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8307     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8308       S.Diag(Loc,
8309              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8310           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8311           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8312       return false;
8313     }
8314   }
8315
8316   // Check for arithmetic on pointers to incomplete types.
8317   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8318   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8319   if (isLHSVoidPtr || isRHSVoidPtr) {
8320     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8321     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8322     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8323
8324     return !S.getLangOpts().CPlusPlus;
8325   }
8326
8327   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8328   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8329   if (isLHSFuncPtr || isRHSFuncPtr) {
8330     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8331     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8332                                                                 RHSExpr);
8333     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8334
8335     return !S.getLangOpts().CPlusPlus;
8336   }
8337
8338   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8339     return false;
8340   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8341     return false;
8342
8343   return true;
8344 }
8345
8346 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8347 /// literal.
8348 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8349                                   Expr *LHSExpr, Expr *RHSExpr) {
8350   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8351   Expr* IndexExpr = RHSExpr;
8352   if (!StrExpr) {
8353     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8354     IndexExpr = LHSExpr;
8355   }
8356
8357   bool IsStringPlusInt = StrExpr &&
8358       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8359   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8360     return;
8361
8362   llvm::APSInt index;
8363   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8364     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8365     if (index.isNonNegative() &&
8366         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8367                               index.isUnsigned()))
8368       return;
8369   }
8370
8371   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8372   Self.Diag(OpLoc, diag::warn_string_plus_int)
8373       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8374
8375   // Only print a fixit for "str" + int, not for int + "str".
8376   if (IndexExpr == RHSExpr) {
8377     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8378     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8379         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8380         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8381         << FixItHint::CreateInsertion(EndLoc, "]");
8382   } else
8383     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8384 }
8385
8386 /// \brief Emit a warning when adding a char literal to a string.
8387 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8388                                    Expr *LHSExpr, Expr *RHSExpr) {
8389   const Expr *StringRefExpr = LHSExpr;
8390   const CharacterLiteral *CharExpr =
8391       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8392
8393   if (!CharExpr) {
8394     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8395     StringRefExpr = RHSExpr;
8396   }
8397
8398   if (!CharExpr || !StringRefExpr)
8399     return;
8400
8401   const QualType StringType = StringRefExpr->getType();
8402
8403   // Return if not a PointerType.
8404   if (!StringType->isAnyPointerType())
8405     return;
8406
8407   // Return if not a CharacterType.
8408   if (!StringType->getPointeeType()->isAnyCharacterType())
8409     return;
8410
8411   ASTContext &Ctx = Self.getASTContext();
8412   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8413
8414   const QualType CharType = CharExpr->getType();
8415   if (!CharType->isAnyCharacterType() &&
8416       CharType->isIntegerType() &&
8417       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8418     Self.Diag(OpLoc, diag::warn_string_plus_char)
8419         << DiagRange << Ctx.CharTy;
8420   } else {
8421     Self.Diag(OpLoc, diag::warn_string_plus_char)
8422         << DiagRange << CharExpr->getType();
8423   }
8424
8425   // Only print a fixit for str + char, not for char + str.
8426   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8427     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8428     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8429         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8430         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8431         << FixItHint::CreateInsertion(EndLoc, "]");
8432   } else {
8433     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8434   }
8435 }
8436
8437 /// \brief Emit error when two pointers are incompatible.
8438 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8439                                            Expr *LHSExpr, Expr *RHSExpr) {
8440   assert(LHSExpr->getType()->isAnyPointerType());
8441   assert(RHSExpr->getType()->isAnyPointerType());
8442   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8443     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8444     << RHSExpr->getSourceRange();
8445 }
8446
8447 // C99 6.5.6
8448 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8449                                      SourceLocation Loc, BinaryOperatorKind Opc,
8450                                      QualType* CompLHSTy) {
8451   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8452
8453   if (LHS.get()->getType()->isVectorType() ||
8454       RHS.get()->getType()->isVectorType()) {
8455     QualType compType = CheckVectorOperands(
8456         LHS, RHS, Loc, CompLHSTy,
8457         /*AllowBothBool*/getLangOpts().AltiVec,
8458         /*AllowBoolConversions*/getLangOpts().ZVector);
8459     if (CompLHSTy) *CompLHSTy = compType;
8460     return compType;
8461   }
8462
8463   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8464   if (LHS.isInvalid() || RHS.isInvalid())
8465     return QualType();
8466
8467   // Diagnose "string literal" '+' int and string '+' "char literal".
8468   if (Opc == BO_Add) {
8469     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8470     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8471   }
8472
8473   // handle the common case first (both operands are arithmetic).
8474   if (!compType.isNull() && compType->isArithmeticType()) {
8475     if (CompLHSTy) *CompLHSTy = compType;
8476     return compType;
8477   }
8478
8479   // Type-checking.  Ultimately the pointer's going to be in PExp;
8480   // note that we bias towards the LHS being the pointer.
8481   Expr *PExp = LHS.get(), *IExp = RHS.get();
8482
8483   bool isObjCPointer;
8484   if (PExp->getType()->isPointerType()) {
8485     isObjCPointer = false;
8486   } else if (PExp->getType()->isObjCObjectPointerType()) {
8487     isObjCPointer = true;
8488   } else {
8489     std::swap(PExp, IExp);
8490     if (PExp->getType()->isPointerType()) {
8491       isObjCPointer = false;
8492     } else if (PExp->getType()->isObjCObjectPointerType()) {
8493       isObjCPointer = true;
8494     } else {
8495       return InvalidOperands(Loc, LHS, RHS);
8496     }
8497   }
8498   assert(PExp->getType()->isAnyPointerType());
8499
8500   if (!IExp->getType()->isIntegerType())
8501     return InvalidOperands(Loc, LHS, RHS);
8502
8503   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8504     return QualType();
8505
8506   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8507     return QualType();
8508
8509   // Check array bounds for pointer arithemtic
8510   CheckArrayAccess(PExp, IExp);
8511
8512   if (CompLHSTy) {
8513     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8514     if (LHSTy.isNull()) {
8515       LHSTy = LHS.get()->getType();
8516       if (LHSTy->isPromotableIntegerType())
8517         LHSTy = Context.getPromotedIntegerType(LHSTy);
8518     }
8519     *CompLHSTy = LHSTy;
8520   }
8521
8522   return PExp->getType();
8523 }
8524
8525 // C99 6.5.6
8526 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8527                                         SourceLocation Loc,
8528                                         QualType* CompLHSTy) {
8529   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8530
8531   if (LHS.get()->getType()->isVectorType() ||
8532       RHS.get()->getType()->isVectorType()) {
8533     QualType compType = CheckVectorOperands(
8534         LHS, RHS, Loc, CompLHSTy,
8535         /*AllowBothBool*/getLangOpts().AltiVec,
8536         /*AllowBoolConversions*/getLangOpts().ZVector);
8537     if (CompLHSTy) *CompLHSTy = compType;
8538     return compType;
8539   }
8540
8541   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8542   if (LHS.isInvalid() || RHS.isInvalid())
8543     return QualType();
8544
8545   // Enforce type constraints: C99 6.5.6p3.
8546
8547   // Handle the common case first (both operands are arithmetic).
8548   if (!compType.isNull() && compType->isArithmeticType()) {
8549     if (CompLHSTy) *CompLHSTy = compType;
8550     return compType;
8551   }
8552
8553   // Either ptr - int   or   ptr - ptr.
8554   if (LHS.get()->getType()->isAnyPointerType()) {
8555     QualType lpointee = LHS.get()->getType()->getPointeeType();
8556
8557     // Diagnose bad cases where we step over interface counts.
8558     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8559         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8560       return QualType();
8561
8562     // The result type of a pointer-int computation is the pointer type.
8563     if (RHS.get()->getType()->isIntegerType()) {
8564       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8565         return QualType();
8566
8567       // Check array bounds for pointer arithemtic
8568       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8569                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8570
8571       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8572       return LHS.get()->getType();
8573     }
8574
8575     // Handle pointer-pointer subtractions.
8576     if (const PointerType *RHSPTy
8577           = RHS.get()->getType()->getAs<PointerType>()) {
8578       QualType rpointee = RHSPTy->getPointeeType();
8579
8580       if (getLangOpts().CPlusPlus) {
8581         // Pointee types must be the same: C++ [expr.add]
8582         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8583           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8584         }
8585       } else {
8586         // Pointee types must be compatible C99 6.5.6p3
8587         if (!Context.typesAreCompatible(
8588                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8589                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8590           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8591           return QualType();
8592         }
8593       }
8594
8595       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8596                                                LHS.get(), RHS.get()))
8597         return QualType();
8598
8599       // The pointee type may have zero size.  As an extension, a structure or
8600       // union may have zero size or an array may have zero length.  In this
8601       // case subtraction does not make sense.
8602       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8603         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8604         if (ElementSize.isZero()) {
8605           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8606             << rpointee.getUnqualifiedType()
8607             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8608         }
8609       }
8610
8611       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8612       return Context.getPointerDiffType();
8613     }
8614   }
8615
8616   return InvalidOperands(Loc, LHS, RHS);
8617 }
8618
8619 static bool isScopedEnumerationType(QualType T) {
8620   if (const EnumType *ET = T->getAs<EnumType>())
8621     return ET->getDecl()->isScoped();
8622   return false;
8623 }
8624
8625 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8626                                    SourceLocation Loc, BinaryOperatorKind Opc,
8627                                    QualType LHSType) {
8628   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8629   // so skip remaining warnings as we don't want to modify values within Sema.
8630   if (S.getLangOpts().OpenCL)
8631     return;
8632
8633   llvm::APSInt Right;
8634   // Check right/shifter operand
8635   if (RHS.get()->isValueDependent() ||
8636       !RHS.get()->EvaluateAsInt(Right, S.Context))
8637     return;
8638
8639   if (Right.isNegative()) {
8640     S.DiagRuntimeBehavior(Loc, RHS.get(),
8641                           S.PDiag(diag::warn_shift_negative)
8642                             << RHS.get()->getSourceRange());
8643     return;
8644   }
8645   llvm::APInt LeftBits(Right.getBitWidth(),
8646                        S.Context.getTypeSize(LHS.get()->getType()));
8647   if (Right.uge(LeftBits)) {
8648     S.DiagRuntimeBehavior(Loc, RHS.get(),
8649                           S.PDiag(diag::warn_shift_gt_typewidth)
8650                             << RHS.get()->getSourceRange());
8651     return;
8652   }
8653   if (Opc != BO_Shl)
8654     return;
8655
8656   // When left shifting an ICE which is signed, we can check for overflow which
8657   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8658   // integers have defined behavior modulo one more than the maximum value
8659   // representable in the result type, so never warn for those.
8660   llvm::APSInt Left;
8661   if (LHS.get()->isValueDependent() ||
8662       LHSType->hasUnsignedIntegerRepresentation() ||
8663       !LHS.get()->EvaluateAsInt(Left, S.Context))
8664     return;
8665
8666   // If LHS does not have a signed type and non-negative value
8667   // then, the behavior is undefined. Warn about it.
8668   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8669     S.DiagRuntimeBehavior(Loc, LHS.get(),
8670                           S.PDiag(diag::warn_shift_lhs_negative)
8671                             << LHS.get()->getSourceRange());
8672     return;
8673   }
8674
8675   llvm::APInt ResultBits =
8676       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8677   if (LeftBits.uge(ResultBits))
8678     return;
8679   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8680   Result = Result.shl(Right);
8681
8682   // Print the bit representation of the signed integer as an unsigned
8683   // hexadecimal number.
8684   SmallString<40> HexResult;
8685   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8686
8687   // If we are only missing a sign bit, this is less likely to result in actual
8688   // bugs -- if the result is cast back to an unsigned type, it will have the
8689   // expected value. Thus we place this behind a different warning that can be
8690   // turned off separately if needed.
8691   if (LeftBits == ResultBits - 1) {
8692     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8693         << HexResult << LHSType
8694         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8695     return;
8696   }
8697
8698   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8699     << HexResult.str() << Result.getMinSignedBits() << LHSType
8700     << Left.getBitWidth() << LHS.get()->getSourceRange()
8701     << RHS.get()->getSourceRange();
8702 }
8703
8704 /// \brief Return the resulting type when a vector is shifted
8705 ///        by a scalar or vector shift amount.
8706 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8707                                  SourceLocation Loc, bool IsCompAssign) {
8708   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8709   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8710       !LHS.get()->getType()->isVectorType()) {
8711     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8712       << RHS.get()->getType() << LHS.get()->getType()
8713       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8714     return QualType();
8715   }
8716
8717   if (!IsCompAssign) {
8718     LHS = S.UsualUnaryConversions(LHS.get());
8719     if (LHS.isInvalid()) return QualType();
8720   }
8721
8722   RHS = S.UsualUnaryConversions(RHS.get());
8723   if (RHS.isInvalid()) return QualType();
8724
8725   QualType LHSType = LHS.get()->getType();
8726   // Note that LHS might be a scalar because the routine calls not only in
8727   // OpenCL case.
8728   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8729   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8730
8731   // Note that RHS might not be a vector.
8732   QualType RHSType = RHS.get()->getType();
8733   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8734   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8735
8736   // The operands need to be integers.
8737   if (!LHSEleType->isIntegerType()) {
8738     S.Diag(Loc, diag::err_typecheck_expect_int)
8739       << LHS.get()->getType() << LHS.get()->getSourceRange();
8740     return QualType();
8741   }
8742
8743   if (!RHSEleType->isIntegerType()) {
8744     S.Diag(Loc, diag::err_typecheck_expect_int)
8745       << RHS.get()->getType() << RHS.get()->getSourceRange();
8746     return QualType();
8747   }
8748
8749   if (!LHSVecTy) {
8750     assert(RHSVecTy);
8751     if (IsCompAssign)
8752       return RHSType;
8753     if (LHSEleType != RHSEleType) {
8754       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8755       LHSEleType = RHSEleType;
8756     }
8757     QualType VecTy =
8758         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8759     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8760     LHSType = VecTy;
8761   } else if (RHSVecTy) {
8762     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8763     // are applied component-wise. So if RHS is a vector, then ensure
8764     // that the number of elements is the same as LHS...
8765     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8766       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8767         << LHS.get()->getType() << RHS.get()->getType()
8768         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8769       return QualType();
8770     }
8771   } else {
8772     // ...else expand RHS to match the number of elements in LHS.
8773     QualType VecTy =
8774       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8775     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8776   }
8777
8778   return LHSType;
8779 }
8780
8781 // C99 6.5.7
8782 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8783                                   SourceLocation Loc, BinaryOperatorKind Opc,
8784                                   bool IsCompAssign) {
8785   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8786
8787   // Vector shifts promote their scalar inputs to vector type.
8788   if (LHS.get()->getType()->isVectorType() ||
8789       RHS.get()->getType()->isVectorType()) {
8790     if (LangOpts.ZVector) {
8791       // The shift operators for the z vector extensions work basically
8792       // like general shifts, except that neither the LHS nor the RHS is
8793       // allowed to be a "vector bool".
8794       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8795         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8796           return InvalidOperands(Loc, LHS, RHS);
8797       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8798         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8799           return InvalidOperands(Loc, LHS, RHS);
8800     }
8801     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8802   }
8803
8804   // Shifts don't perform usual arithmetic conversions, they just do integer
8805   // promotions on each operand. C99 6.5.7p3
8806
8807   // For the LHS, do usual unary conversions, but then reset them away
8808   // if this is a compound assignment.
8809   ExprResult OldLHS = LHS;
8810   LHS = UsualUnaryConversions(LHS.get());
8811   if (LHS.isInvalid())
8812     return QualType();
8813   QualType LHSType = LHS.get()->getType();
8814   if (IsCompAssign) LHS = OldLHS;
8815
8816   // The RHS is simpler.
8817   RHS = UsualUnaryConversions(RHS.get());
8818   if (RHS.isInvalid())
8819     return QualType();
8820   QualType RHSType = RHS.get()->getType();
8821
8822   // C99 6.5.7p2: Each of the operands shall have integer type.
8823   if (!LHSType->hasIntegerRepresentation() ||
8824       !RHSType->hasIntegerRepresentation())
8825     return InvalidOperands(Loc, LHS, RHS);
8826
8827   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8828   // hasIntegerRepresentation() above instead of this.
8829   if (isScopedEnumerationType(LHSType) ||
8830       isScopedEnumerationType(RHSType)) {
8831     return InvalidOperands(Loc, LHS, RHS);
8832   }
8833   // Sanity-check shift operands
8834   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8835
8836   // "The type of the result is that of the promoted left operand."
8837   return LHSType;
8838 }
8839
8840 static bool IsWithinTemplateSpecialization(Decl *D) {
8841   if (DeclContext *DC = D->getDeclContext()) {
8842     if (isa<ClassTemplateSpecializationDecl>(DC))
8843       return true;
8844     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8845       return FD->isFunctionTemplateSpecialization();
8846   }
8847   return false;
8848 }
8849
8850 /// If two different enums are compared, raise a warning.
8851 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8852                                 Expr *RHS) {
8853   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8854   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8855
8856   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8857   if (!LHSEnumType)
8858     return;
8859   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8860   if (!RHSEnumType)
8861     return;
8862
8863   // Ignore anonymous enums.
8864   if (!LHSEnumType->getDecl()->getIdentifier())
8865     return;
8866   if (!RHSEnumType->getDecl()->getIdentifier())
8867     return;
8868
8869   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8870     return;
8871
8872   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8873       << LHSStrippedType << RHSStrippedType
8874       << LHS->getSourceRange() << RHS->getSourceRange();
8875 }
8876
8877 /// \brief Diagnose bad pointer comparisons.
8878 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8879                                               ExprResult &LHS, ExprResult &RHS,
8880                                               bool IsError) {
8881   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8882                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8883     << LHS.get()->getType() << RHS.get()->getType()
8884     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8885 }
8886
8887 /// \brief Returns false if the pointers are converted to a composite type,
8888 /// true otherwise.
8889 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8890                                            ExprResult &LHS, ExprResult &RHS) {
8891   // C++ [expr.rel]p2:
8892   //   [...] Pointer conversions (4.10) and qualification
8893   //   conversions (4.4) are performed on pointer operands (or on
8894   //   a pointer operand and a null pointer constant) to bring
8895   //   them to their composite pointer type. [...]
8896   //
8897   // C++ [expr.eq]p1 uses the same notion for (in)equality
8898   // comparisons of pointers.
8899
8900   // C++ [expr.eq]p2:
8901   //   In addition, pointers to members can be compared, or a pointer to
8902   //   member and a null pointer constant. Pointer to member conversions
8903   //   (4.11) and qualification conversions (4.4) are performed to bring
8904   //   them to a common type. If one operand is a null pointer constant,
8905   //   the common type is the type of the other operand. Otherwise, the
8906   //   common type is a pointer to member type similar (4.4) to the type
8907   //   of one of the operands, with a cv-qualification signature (4.4)
8908   //   that is the union of the cv-qualification signatures of the operand
8909   //   types.
8910
8911   QualType LHSType = LHS.get()->getType();
8912   QualType RHSType = RHS.get()->getType();
8913   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8914          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8915
8916   bool NonStandardCompositeType = false;
8917   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8918   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8919   if (T.isNull()) {
8920     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8921     return true;
8922   }
8923
8924   if (NonStandardCompositeType)
8925     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8926       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8927       << RHS.get()->getSourceRange();
8928
8929   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8930   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8931   return false;
8932 }
8933
8934 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8935                                                     ExprResult &LHS,
8936                                                     ExprResult &RHS,
8937                                                     bool IsError) {
8938   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8939                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8940     << LHS.get()->getType() << RHS.get()->getType()
8941     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8942 }
8943
8944 static bool isObjCObjectLiteral(ExprResult &E) {
8945   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8946   case Stmt::ObjCArrayLiteralClass:
8947   case Stmt::ObjCDictionaryLiteralClass:
8948   case Stmt::ObjCStringLiteralClass:
8949   case Stmt::ObjCBoxedExprClass:
8950     return true;
8951   default:
8952     // Note that ObjCBoolLiteral is NOT an object literal!
8953     return false;
8954   }
8955 }
8956
8957 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8958   const ObjCObjectPointerType *Type =
8959     LHS->getType()->getAs<ObjCObjectPointerType>();
8960
8961   // If this is not actually an Objective-C object, bail out.
8962   if (!Type)
8963     return false;
8964
8965   // Get the LHS object's interface type.
8966   QualType InterfaceType = Type->getPointeeType();
8967
8968   // If the RHS isn't an Objective-C object, bail out.
8969   if (!RHS->getType()->isObjCObjectPointerType())
8970     return false;
8971
8972   // Try to find the -isEqual: method.
8973   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8974   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8975                                                       InterfaceType,
8976                                                       /*instance=*/true);
8977   if (!Method) {
8978     if (Type->isObjCIdType()) {
8979       // For 'id', just check the global pool.
8980       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8981                                                   /*receiverId=*/true);
8982     } else {
8983       // Check protocols.
8984       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8985                                              /*instance=*/true);
8986     }
8987   }
8988
8989   if (!Method)
8990     return false;
8991
8992   QualType T = Method->parameters()[0]->getType();
8993   if (!T->isObjCObjectPointerType())
8994     return false;
8995
8996   QualType R = Method->getReturnType();
8997   if (!R->isScalarType())
8998     return false;
8999
9000   return true;
9001 }
9002
9003 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9004   FromE = FromE->IgnoreParenImpCasts();
9005   switch (FromE->getStmtClass()) {
9006     default:
9007       break;
9008     case Stmt::ObjCStringLiteralClass:
9009       // "string literal"
9010       return LK_String;
9011     case Stmt::ObjCArrayLiteralClass:
9012       // "array literal"
9013       return LK_Array;
9014     case Stmt::ObjCDictionaryLiteralClass:
9015       // "dictionary literal"
9016       return LK_Dictionary;
9017     case Stmt::BlockExprClass:
9018       return LK_Block;
9019     case Stmt::ObjCBoxedExprClass: {
9020       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9021       switch (Inner->getStmtClass()) {
9022         case Stmt::IntegerLiteralClass:
9023         case Stmt::FloatingLiteralClass:
9024         case Stmt::CharacterLiteralClass:
9025         case Stmt::ObjCBoolLiteralExprClass:
9026         case Stmt::CXXBoolLiteralExprClass:
9027           // "numeric literal"
9028           return LK_Numeric;
9029         case Stmt::ImplicitCastExprClass: {
9030           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9031           // Boolean literals can be represented by implicit casts.
9032           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9033             return LK_Numeric;
9034           break;
9035         }
9036         default:
9037           break;
9038       }
9039       return LK_Boxed;
9040     }
9041   }
9042   return LK_None;
9043 }
9044
9045 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9046                                           ExprResult &LHS, ExprResult &RHS,
9047                                           BinaryOperator::Opcode Opc){
9048   Expr *Literal;
9049   Expr *Other;
9050   if (isObjCObjectLiteral(LHS)) {
9051     Literal = LHS.get();
9052     Other = RHS.get();
9053   } else {
9054     Literal = RHS.get();
9055     Other = LHS.get();
9056   }
9057
9058   // Don't warn on comparisons against nil.
9059   Other = Other->IgnoreParenCasts();
9060   if (Other->isNullPointerConstant(S.getASTContext(),
9061                                    Expr::NPC_ValueDependentIsNotNull))
9062     return;
9063
9064   // This should be kept in sync with warn_objc_literal_comparison.
9065   // LK_String should always be after the other literals, since it has its own
9066   // warning flag.
9067   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9068   assert(LiteralKind != Sema::LK_Block);
9069   if (LiteralKind == Sema::LK_None) {
9070     llvm_unreachable("Unknown Objective-C object literal kind");
9071   }
9072
9073   if (LiteralKind == Sema::LK_String)
9074     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9075       << Literal->getSourceRange();
9076   else
9077     S.Diag(Loc, diag::warn_objc_literal_comparison)
9078       << LiteralKind << Literal->getSourceRange();
9079
9080   if (BinaryOperator::isEqualityOp(Opc) &&
9081       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9082     SourceLocation Start = LHS.get()->getLocStart();
9083     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9084     CharSourceRange OpRange =
9085       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9086
9087     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9088       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9089       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9090       << FixItHint::CreateInsertion(End, "]");
9091   }
9092 }
9093
9094 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
9095                                                 ExprResult &RHS,
9096                                                 SourceLocation Loc,
9097                                                 BinaryOperatorKind Opc) {
9098   // Check that left hand side is !something.
9099   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9100   if (!UO || UO->getOpcode() != UO_LNot) return;
9101
9102   // Only check if the right hand side is non-bool arithmetic type.
9103   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9104
9105   // Make sure that the something in !something is not bool.
9106   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9107   if (SubExpr->isKnownToHaveBooleanValue()) return;
9108
9109   // Emit warning.
9110   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
9111       << Loc;
9112
9113   // First note suggest !(x < y)
9114   SourceLocation FirstOpen = SubExpr->getLocStart();
9115   SourceLocation FirstClose = RHS.get()->getLocEnd();
9116   FirstClose = S.getLocForEndOfToken(FirstClose);
9117   if (FirstClose.isInvalid())
9118     FirstOpen = SourceLocation();
9119   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9120       << FixItHint::CreateInsertion(FirstOpen, "(")
9121       << FixItHint::CreateInsertion(FirstClose, ")");
9122
9123   // Second note suggests (!x) < y
9124   SourceLocation SecondOpen = LHS.get()->getLocStart();
9125   SourceLocation SecondClose = LHS.get()->getLocEnd();
9126   SecondClose = S.getLocForEndOfToken(SecondClose);
9127   if (SecondClose.isInvalid())
9128     SecondOpen = SourceLocation();
9129   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9130       << FixItHint::CreateInsertion(SecondOpen, "(")
9131       << FixItHint::CreateInsertion(SecondClose, ")");
9132 }
9133
9134 // Get the decl for a simple expression: a reference to a variable,
9135 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9136 static ValueDecl *getCompareDecl(Expr *E) {
9137   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9138     return DR->getDecl();
9139   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9140     if (Ivar->isFreeIvar())
9141       return Ivar->getDecl();
9142   }
9143   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9144     if (Mem->isImplicitAccess())
9145       return Mem->getMemberDecl();
9146   }
9147   return nullptr;
9148 }
9149
9150 // C99 6.5.8, C++ [expr.rel]
9151 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9152                                     SourceLocation Loc, BinaryOperatorKind Opc,
9153                                     bool IsRelational) {
9154   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9155
9156   // Handle vector comparisons separately.
9157   if (LHS.get()->getType()->isVectorType() ||
9158       RHS.get()->getType()->isVectorType())
9159     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9160
9161   QualType LHSType = LHS.get()->getType();
9162   QualType RHSType = RHS.get()->getType();
9163
9164   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9165   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9166
9167   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9168   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9169
9170   if (!LHSType->hasFloatingRepresentation() &&
9171       !(LHSType->isBlockPointerType() && IsRelational) &&
9172       !LHS.get()->getLocStart().isMacroID() &&
9173       !RHS.get()->getLocStart().isMacroID() &&
9174       ActiveTemplateInstantiations.empty()) {
9175     // For non-floating point types, check for self-comparisons of the form
9176     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9177     // often indicate logic errors in the program.
9178     //
9179     // NOTE: Don't warn about comparison expressions resulting from macro
9180     // expansion. Also don't warn about comparisons which are only self
9181     // comparisons within a template specialization. The warnings should catch
9182     // obvious cases in the definition of the template anyways. The idea is to
9183     // warn when the typed comparison operator will always evaluate to the same
9184     // result.
9185     ValueDecl *DL = getCompareDecl(LHSStripped);
9186     ValueDecl *DR = getCompareDecl(RHSStripped);
9187     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9188       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9189                           << 0 // self-
9190                           << (Opc == BO_EQ
9191                               || Opc == BO_LE
9192                               || Opc == BO_GE));
9193     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9194                !DL->getType()->isReferenceType() &&
9195                !DR->getType()->isReferenceType()) {
9196         // what is it always going to eval to?
9197         char always_evals_to;
9198         switch(Opc) {
9199         case BO_EQ: // e.g. array1 == array2
9200           always_evals_to = 0; // false
9201           break;
9202         case BO_NE: // e.g. array1 != array2
9203           always_evals_to = 1; // true
9204           break;
9205         default:
9206           // best we can say is 'a constant'
9207           always_evals_to = 2; // e.g. array1 <= array2
9208           break;
9209         }
9210         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9211                             << 1 // array
9212                             << always_evals_to);
9213     }
9214
9215     if (isa<CastExpr>(LHSStripped))
9216       LHSStripped = LHSStripped->IgnoreParenCasts();
9217     if (isa<CastExpr>(RHSStripped))
9218       RHSStripped = RHSStripped->IgnoreParenCasts();
9219
9220     // Warn about comparisons against a string constant (unless the other
9221     // operand is null), the user probably wants strcmp.
9222     Expr *literalString = nullptr;
9223     Expr *literalStringStripped = nullptr;
9224     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9225         !RHSStripped->isNullPointerConstant(Context,
9226                                             Expr::NPC_ValueDependentIsNull)) {
9227       literalString = LHS.get();
9228       literalStringStripped = LHSStripped;
9229     } else if ((isa<StringLiteral>(RHSStripped) ||
9230                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9231                !LHSStripped->isNullPointerConstant(Context,
9232                                             Expr::NPC_ValueDependentIsNull)) {
9233       literalString = RHS.get();
9234       literalStringStripped = RHSStripped;
9235     }
9236
9237     if (literalString) {
9238       DiagRuntimeBehavior(Loc, nullptr,
9239         PDiag(diag::warn_stringcompare)
9240           << isa<ObjCEncodeExpr>(literalStringStripped)
9241           << literalString->getSourceRange());
9242     }
9243   }
9244
9245   // C99 6.5.8p3 / C99 6.5.9p4
9246   UsualArithmeticConversions(LHS, RHS);
9247   if (LHS.isInvalid() || RHS.isInvalid())
9248     return QualType();
9249
9250   LHSType = LHS.get()->getType();
9251   RHSType = RHS.get()->getType();
9252
9253   // The result of comparisons is 'bool' in C++, 'int' in C.
9254   QualType ResultTy = Context.getLogicalOperationType();
9255
9256   if (IsRelational) {
9257     if (LHSType->isRealType() && RHSType->isRealType())
9258       return ResultTy;
9259   } else {
9260     // Check for comparisons of floating point operands using != and ==.
9261     if (LHSType->hasFloatingRepresentation())
9262       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9263
9264     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9265       return ResultTy;
9266   }
9267
9268   const Expr::NullPointerConstantKind LHSNullKind =
9269       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9270   const Expr::NullPointerConstantKind RHSNullKind =
9271       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9272   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9273   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9274
9275   if (!IsRelational && LHSIsNull != RHSIsNull) {
9276     bool IsEquality = Opc == BO_EQ;
9277     if (RHSIsNull)
9278       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9279                                    RHS.get()->getSourceRange());
9280     else
9281       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9282                                    LHS.get()->getSourceRange());
9283   }
9284
9285   // All of the following pointer-related warnings are GCC extensions, except
9286   // when handling null pointer constants. 
9287   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9288     QualType LCanPointeeTy =
9289       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9290     QualType RCanPointeeTy =
9291       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9292
9293     if (getLangOpts().CPlusPlus) {
9294       if (LCanPointeeTy == RCanPointeeTy)
9295         return ResultTy;
9296       if (!IsRelational &&
9297           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9298         // Valid unless comparison between non-null pointer and function pointer
9299         // This is a gcc extension compatibility comparison.
9300         // In a SFINAE context, we treat this as a hard error to maintain
9301         // conformance with the C++ standard.
9302         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9303             && !LHSIsNull && !RHSIsNull) {
9304           diagnoseFunctionPointerToVoidComparison(
9305               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9306           
9307           if (isSFINAEContext())
9308             return QualType();
9309           
9310           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9311           return ResultTy;
9312         }
9313       }
9314
9315       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9316         return QualType();
9317       else
9318         return ResultTy;
9319     }
9320     // C99 6.5.9p2 and C99 6.5.8p2
9321     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9322                                    RCanPointeeTy.getUnqualifiedType())) {
9323       // Valid unless a relational comparison of function pointers
9324       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9325         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9326           << LHSType << RHSType << LHS.get()->getSourceRange()
9327           << RHS.get()->getSourceRange();
9328       }
9329     } else if (!IsRelational &&
9330                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9331       // Valid unless comparison between non-null pointer and function pointer
9332       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9333           && !LHSIsNull && !RHSIsNull)
9334         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9335                                                 /*isError*/false);
9336     } else {
9337       // Invalid
9338       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9339     }
9340     if (LCanPointeeTy != RCanPointeeTy) {
9341       // Treat NULL constant as a special case in OpenCL.
9342       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9343         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9344         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9345           Diag(Loc,
9346                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9347               << LHSType << RHSType << 0 /* comparison */
9348               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9349         }
9350       }
9351       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9352       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9353       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9354                                                : CK_BitCast;
9355       if (LHSIsNull && !RHSIsNull)
9356         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9357       else
9358         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9359     }
9360     return ResultTy;
9361   }
9362
9363   if (getLangOpts().CPlusPlus) {
9364     // Comparison of nullptr_t with itself.
9365     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9366       return ResultTy;
9367     
9368     // Comparison of pointers with null pointer constants and equality
9369     // comparisons of member pointers to null pointer constants.
9370     if (RHSIsNull &&
9371         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9372          (!IsRelational && 
9373           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9374       RHS = ImpCastExprToType(RHS.get(), LHSType, 
9375                         LHSType->isMemberPointerType()
9376                           ? CK_NullToMemberPointer
9377                           : CK_NullToPointer);
9378       return ResultTy;
9379     }
9380     if (LHSIsNull &&
9381         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9382          (!IsRelational && 
9383           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9384       LHS = ImpCastExprToType(LHS.get(), RHSType, 
9385                         RHSType->isMemberPointerType()
9386                           ? CK_NullToMemberPointer
9387                           : CK_NullToPointer);
9388       return ResultTy;
9389     }
9390
9391     // Comparison of member pointers.
9392     if (!IsRelational &&
9393         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9394       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9395         return QualType();
9396       else
9397         return ResultTy;
9398     }
9399
9400     // Handle scoped enumeration types specifically, since they don't promote
9401     // to integers.
9402     if (LHS.get()->getType()->isEnumeralType() &&
9403         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9404                                        RHS.get()->getType()))
9405       return ResultTy;
9406   }
9407
9408   // Handle block pointer types.
9409   if (!IsRelational && LHSType->isBlockPointerType() &&
9410       RHSType->isBlockPointerType()) {
9411     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9412     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9413
9414     if (!LHSIsNull && !RHSIsNull &&
9415         !Context.typesAreCompatible(lpointee, rpointee)) {
9416       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9417         << LHSType << RHSType << LHS.get()->getSourceRange()
9418         << RHS.get()->getSourceRange();
9419     }
9420     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9421     return ResultTy;
9422   }
9423
9424   // Allow block pointers to be compared with null pointer constants.
9425   if (!IsRelational
9426       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9427           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9428     if (!LHSIsNull && !RHSIsNull) {
9429       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9430              ->getPointeeType()->isVoidType())
9431             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9432                 ->getPointeeType()->isVoidType())))
9433         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9434           << LHSType << RHSType << LHS.get()->getSourceRange()
9435           << RHS.get()->getSourceRange();
9436     }
9437     if (LHSIsNull && !RHSIsNull)
9438       LHS = ImpCastExprToType(LHS.get(), RHSType,
9439                               RHSType->isPointerType() ? CK_BitCast
9440                                 : CK_AnyPointerToBlockPointerCast);
9441     else
9442       RHS = ImpCastExprToType(RHS.get(), LHSType,
9443                               LHSType->isPointerType() ? CK_BitCast
9444                                 : CK_AnyPointerToBlockPointerCast);
9445     return ResultTy;
9446   }
9447
9448   if (LHSType->isObjCObjectPointerType() ||
9449       RHSType->isObjCObjectPointerType()) {
9450     const PointerType *LPT = LHSType->getAs<PointerType>();
9451     const PointerType *RPT = RHSType->getAs<PointerType>();
9452     if (LPT || RPT) {
9453       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9454       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9455
9456       if (!LPtrToVoid && !RPtrToVoid &&
9457           !Context.typesAreCompatible(LHSType, RHSType)) {
9458         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9459                                           /*isError*/false);
9460       }
9461       if (LHSIsNull && !RHSIsNull) {
9462         Expr *E = LHS.get();
9463         if (getLangOpts().ObjCAutoRefCount)
9464           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9465         LHS = ImpCastExprToType(E, RHSType,
9466                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9467       }
9468       else {
9469         Expr *E = RHS.get();
9470         if (getLangOpts().ObjCAutoRefCount)
9471           CheckObjCARCConversion(SourceRange(), LHSType, E,
9472                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9473                                  /*DiagnoseCFAudited=*/false, Opc);
9474         RHS = ImpCastExprToType(E, LHSType,
9475                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9476       }
9477       return ResultTy;
9478     }
9479     if (LHSType->isObjCObjectPointerType() &&
9480         RHSType->isObjCObjectPointerType()) {
9481       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9482         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9483                                           /*isError*/false);
9484       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9485         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9486
9487       if (LHSIsNull && !RHSIsNull)
9488         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9489       else
9490         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9491       return ResultTy;
9492     }
9493   }
9494   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9495       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9496     unsigned DiagID = 0;
9497     bool isError = false;
9498     if (LangOpts.DebuggerSupport) {
9499       // Under a debugger, allow the comparison of pointers to integers,
9500       // since users tend to want to compare addresses.
9501     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9502         (RHSIsNull && RHSType->isIntegerType())) {
9503       if (IsRelational && !getLangOpts().CPlusPlus)
9504         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9505     } else if (IsRelational && !getLangOpts().CPlusPlus)
9506       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9507     else if (getLangOpts().CPlusPlus) {
9508       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9509       isError = true;
9510     } else
9511       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9512
9513     if (DiagID) {
9514       Diag(Loc, DiagID)
9515         << LHSType << RHSType << LHS.get()->getSourceRange()
9516         << RHS.get()->getSourceRange();
9517       if (isError)
9518         return QualType();
9519     }
9520     
9521     if (LHSType->isIntegerType())
9522       LHS = ImpCastExprToType(LHS.get(), RHSType,
9523                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9524     else
9525       RHS = ImpCastExprToType(RHS.get(), LHSType,
9526                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9527     return ResultTy;
9528   }
9529   
9530   // Handle block pointers.
9531   if (!IsRelational && RHSIsNull
9532       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9533     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9534     return ResultTy;
9535   }
9536   if (!IsRelational && LHSIsNull
9537       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9538     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9539     return ResultTy;
9540   }
9541
9542   return InvalidOperands(Loc, LHS, RHS);
9543 }
9544
9545
9546 // Return a signed type that is of identical size and number of elements.
9547 // For floating point vectors, return an integer type of identical size 
9548 // and number of elements.
9549 QualType Sema::GetSignedVectorType(QualType V) {
9550   const VectorType *VTy = V->getAs<VectorType>();
9551   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9552   if (TypeSize == Context.getTypeSize(Context.CharTy))
9553     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9554   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9555     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9556   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9557     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9558   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9559     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9560   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9561          "Unhandled vector element size in vector compare");
9562   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9563 }
9564
9565 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9566 /// operates on extended vector types.  Instead of producing an IntTy result,
9567 /// like a scalar comparison, a vector comparison produces a vector of integer
9568 /// types.
9569 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9570                                           SourceLocation Loc,
9571                                           bool IsRelational) {
9572   // Check to make sure we're operating on vectors of the same type and width,
9573   // Allowing one side to be a scalar of element type.
9574   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9575                               /*AllowBothBool*/true,
9576                               /*AllowBoolConversions*/getLangOpts().ZVector);
9577   if (vType.isNull())
9578     return vType;
9579
9580   QualType LHSType = LHS.get()->getType();
9581
9582   // If AltiVec, the comparison results in a numeric type, i.e.
9583   // bool for C++, int for C
9584   if (getLangOpts().AltiVec &&
9585       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9586     return Context.getLogicalOperationType();
9587
9588   // For non-floating point types, check for self-comparisons of the form
9589   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9590   // often indicate logic errors in the program.
9591   if (!LHSType->hasFloatingRepresentation() &&
9592       ActiveTemplateInstantiations.empty()) {
9593     if (DeclRefExpr* DRL
9594           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9595       if (DeclRefExpr* DRR
9596             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9597         if (DRL->getDecl() == DRR->getDecl())
9598           DiagRuntimeBehavior(Loc, nullptr,
9599                               PDiag(diag::warn_comparison_always)
9600                                 << 0 // self-
9601                                 << 2 // "a constant"
9602                               );
9603   }
9604
9605   // Check for comparisons of floating point operands using != and ==.
9606   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9607     assert (RHS.get()->getType()->hasFloatingRepresentation());
9608     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9609   }
9610   
9611   // Return a signed type for the vector.
9612   return GetSignedVectorType(vType);
9613 }
9614
9615 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9616                                           SourceLocation Loc) {
9617   // Ensure that either both operands are of the same vector type, or
9618   // one operand is of a vector type and the other is of its element type.
9619   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9620                                        /*AllowBothBool*/true,
9621                                        /*AllowBoolConversions*/false);
9622   if (vType.isNull())
9623     return InvalidOperands(Loc, LHS, RHS);
9624   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9625       vType->hasFloatingRepresentation())
9626     return InvalidOperands(Loc, LHS, RHS);
9627   
9628   return GetSignedVectorType(LHS.get()->getType());
9629 }
9630
9631 inline QualType Sema::CheckBitwiseOperands(
9632   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9633   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9634
9635   if (LHS.get()->getType()->isVectorType() ||
9636       RHS.get()->getType()->isVectorType()) {
9637     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9638         RHS.get()->getType()->hasIntegerRepresentation())
9639       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9640                         /*AllowBothBool*/true,
9641                         /*AllowBoolConversions*/getLangOpts().ZVector);
9642     return InvalidOperands(Loc, LHS, RHS);
9643   }
9644
9645   ExprResult LHSResult = LHS, RHSResult = RHS;
9646   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9647                                                  IsCompAssign);
9648   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9649     return QualType();
9650   LHS = LHSResult.get();
9651   RHS = RHSResult.get();
9652
9653   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9654     return compType;
9655   return InvalidOperands(Loc, LHS, RHS);
9656 }
9657
9658 // C99 6.5.[13,14]
9659 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9660                                            SourceLocation Loc,
9661                                            BinaryOperatorKind Opc) {
9662   // Check vector operands differently.
9663   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9664     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9665   
9666   // Diagnose cases where the user write a logical and/or but probably meant a
9667   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9668   // is a constant.
9669   if (LHS.get()->getType()->isIntegerType() &&
9670       !LHS.get()->getType()->isBooleanType() &&
9671       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9672       // Don't warn in macros or template instantiations.
9673       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9674     // If the RHS can be constant folded, and if it constant folds to something
9675     // that isn't 0 or 1 (which indicate a potential logical operation that
9676     // happened to fold to true/false) then warn.
9677     // Parens on the RHS are ignored.
9678     llvm::APSInt Result;
9679     if (RHS.get()->EvaluateAsInt(Result, Context))
9680       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9681            !RHS.get()->getExprLoc().isMacroID()) ||
9682           (Result != 0 && Result != 1)) {
9683         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9684           << RHS.get()->getSourceRange()
9685           << (Opc == BO_LAnd ? "&&" : "||");
9686         // Suggest replacing the logical operator with the bitwise version
9687         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9688             << (Opc == BO_LAnd ? "&" : "|")
9689             << FixItHint::CreateReplacement(SourceRange(
9690                                                  Loc, getLocForEndOfToken(Loc)),
9691                                             Opc == BO_LAnd ? "&" : "|");
9692         if (Opc == BO_LAnd)
9693           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9694           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9695               << FixItHint::CreateRemoval(
9696                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9697                               RHS.get()->getLocEnd()));
9698       }
9699   }
9700
9701   if (!Context.getLangOpts().CPlusPlus) {
9702     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9703     // not operate on the built-in scalar and vector float types.
9704     if (Context.getLangOpts().OpenCL &&
9705         Context.getLangOpts().OpenCLVersion < 120) {
9706       if (LHS.get()->getType()->isFloatingType() ||
9707           RHS.get()->getType()->isFloatingType())
9708         return InvalidOperands(Loc, LHS, RHS);
9709     }
9710
9711     LHS = UsualUnaryConversions(LHS.get());
9712     if (LHS.isInvalid())
9713       return QualType();
9714
9715     RHS = UsualUnaryConversions(RHS.get());
9716     if (RHS.isInvalid())
9717       return QualType();
9718
9719     if (!LHS.get()->getType()->isScalarType() ||
9720         !RHS.get()->getType()->isScalarType())
9721       return InvalidOperands(Loc, LHS, RHS);
9722
9723     return Context.IntTy;
9724   }
9725
9726   // The following is safe because we only use this method for
9727   // non-overloadable operands.
9728
9729   // C++ [expr.log.and]p1
9730   // C++ [expr.log.or]p1
9731   // The operands are both contextually converted to type bool.
9732   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9733   if (LHSRes.isInvalid())
9734     return InvalidOperands(Loc, LHS, RHS);
9735   LHS = LHSRes;
9736
9737   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9738   if (RHSRes.isInvalid())
9739     return InvalidOperands(Loc, LHS, RHS);
9740   RHS = RHSRes;
9741
9742   // C++ [expr.log.and]p2
9743   // C++ [expr.log.or]p2
9744   // The result is a bool.
9745   return Context.BoolTy;
9746 }
9747
9748 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9749   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9750   if (!ME) return false;
9751   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9752   ObjCMessageExpr *Base =
9753     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9754   if (!Base) return false;
9755   return Base->getMethodDecl() != nullptr;
9756 }
9757
9758 /// Is the given expression (which must be 'const') a reference to a
9759 /// variable which was originally non-const, but which has become
9760 /// 'const' due to being captured within a block?
9761 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9762 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9763   assert(E->isLValue() && E->getType().isConstQualified());
9764   E = E->IgnoreParens();
9765
9766   // Must be a reference to a declaration from an enclosing scope.
9767   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9768   if (!DRE) return NCCK_None;
9769   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9770
9771   // The declaration must be a variable which is not declared 'const'.
9772   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9773   if (!var) return NCCK_None;
9774   if (var->getType().isConstQualified()) return NCCK_None;
9775   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9776
9777   // Decide whether the first capture was for a block or a lambda.
9778   DeclContext *DC = S.CurContext, *Prev = nullptr;
9779   // Decide whether the first capture was for a block or a lambda.
9780   while (DC) {
9781     // For init-capture, it is possible that the variable belongs to the
9782     // template pattern of the current context.
9783     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9784       if (var->isInitCapture() &&
9785           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9786         break;
9787     if (DC == var->getDeclContext())
9788       break;
9789     Prev = DC;
9790     DC = DC->getParent();
9791   }
9792   // Unless we have an init-capture, we've gone one step too far.
9793   if (!var->isInitCapture())
9794     DC = Prev;
9795   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9796 }
9797
9798 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9799   Ty = Ty.getNonReferenceType();
9800   if (IsDereference && Ty->isPointerType())
9801     Ty = Ty->getPointeeType();
9802   return !Ty.isConstQualified();
9803 }
9804
9805 /// Emit the "read-only variable not assignable" error and print notes to give
9806 /// more information about why the variable is not assignable, such as pointing
9807 /// to the declaration of a const variable, showing that a method is const, or
9808 /// that the function is returning a const reference.
9809 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9810                                     SourceLocation Loc) {
9811   // Update err_typecheck_assign_const and note_typecheck_assign_const
9812   // when this enum is changed.
9813   enum {
9814     ConstFunction,
9815     ConstVariable,
9816     ConstMember,
9817     ConstMethod,
9818     ConstUnknown,  // Keep as last element
9819   };
9820
9821   SourceRange ExprRange = E->getSourceRange();
9822
9823   // Only emit one error on the first const found.  All other consts will emit
9824   // a note to the error.
9825   bool DiagnosticEmitted = false;
9826
9827   // Track if the current expression is the result of a derefence, and if the
9828   // next checked expression is the result of a derefence.
9829   bool IsDereference = false;
9830   bool NextIsDereference = false;
9831
9832   // Loop to process MemberExpr chains.
9833   while (true) {
9834     IsDereference = NextIsDereference;
9835     NextIsDereference = false;
9836
9837     E = E->IgnoreParenImpCasts();
9838     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9839       NextIsDereference = ME->isArrow();
9840       const ValueDecl *VD = ME->getMemberDecl();
9841       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9842         // Mutable fields can be modified even if the class is const.
9843         if (Field->isMutable()) {
9844           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9845           break;
9846         }
9847
9848         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9849           if (!DiagnosticEmitted) {
9850             S.Diag(Loc, diag::err_typecheck_assign_const)
9851                 << ExprRange << ConstMember << false /*static*/ << Field
9852                 << Field->getType();
9853             DiagnosticEmitted = true;
9854           }
9855           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9856               << ConstMember << false /*static*/ << Field << Field->getType()
9857               << Field->getSourceRange();
9858         }
9859         E = ME->getBase();
9860         continue;
9861       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9862         if (VDecl->getType().isConstQualified()) {
9863           if (!DiagnosticEmitted) {
9864             S.Diag(Loc, diag::err_typecheck_assign_const)
9865                 << ExprRange << ConstMember << true /*static*/ << VDecl
9866                 << VDecl->getType();
9867             DiagnosticEmitted = true;
9868           }
9869           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9870               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9871               << VDecl->getSourceRange();
9872         }
9873         // Static fields do not inherit constness from parents.
9874         break;
9875       }
9876       break;
9877     } // End MemberExpr
9878     break;
9879   }
9880
9881   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9882     // Function calls
9883     const FunctionDecl *FD = CE->getDirectCallee();
9884     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9885       if (!DiagnosticEmitted) {
9886         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9887                                                       << ConstFunction << FD;
9888         DiagnosticEmitted = true;
9889       }
9890       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9891              diag::note_typecheck_assign_const)
9892           << ConstFunction << FD << FD->getReturnType()
9893           << FD->getReturnTypeSourceRange();
9894     }
9895   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9896     // Point to variable declaration.
9897     if (const ValueDecl *VD = DRE->getDecl()) {
9898       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9899         if (!DiagnosticEmitted) {
9900           S.Diag(Loc, diag::err_typecheck_assign_const)
9901               << ExprRange << ConstVariable << VD << VD->getType();
9902           DiagnosticEmitted = true;
9903         }
9904         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9905             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9906       }
9907     }
9908   } else if (isa<CXXThisExpr>(E)) {
9909     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9910       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9911         if (MD->isConst()) {
9912           if (!DiagnosticEmitted) {
9913             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9914                                                           << ConstMethod << MD;
9915             DiagnosticEmitted = true;
9916           }
9917           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9918               << ConstMethod << MD << MD->getSourceRange();
9919         }
9920       }
9921     }
9922   }
9923
9924   if (DiagnosticEmitted)
9925     return;
9926
9927   // Can't determine a more specific message, so display the generic error.
9928   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9929 }
9930
9931 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9932 /// emit an error and return true.  If so, return false.
9933 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9934   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9935
9936   S.CheckShadowingDeclModification(E, Loc);
9937
9938   SourceLocation OrigLoc = Loc;
9939   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9940                                                               &Loc);
9941   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9942     IsLV = Expr::MLV_InvalidMessageExpression;
9943   if (IsLV == Expr::MLV_Valid)
9944     return false;
9945
9946   unsigned DiagID = 0;
9947   bool NeedType = false;
9948   switch (IsLV) { // C99 6.5.16p2
9949   case Expr::MLV_ConstQualified:
9950     // Use a specialized diagnostic when we're assigning to an object
9951     // from an enclosing function or block.
9952     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9953       if (NCCK == NCCK_Block)
9954         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9955       else
9956         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9957       break;
9958     }
9959
9960     // In ARC, use some specialized diagnostics for occasions where we
9961     // infer 'const'.  These are always pseudo-strong variables.
9962     if (S.getLangOpts().ObjCAutoRefCount) {
9963       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9964       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9965         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9966
9967         // Use the normal diagnostic if it's pseudo-__strong but the
9968         // user actually wrote 'const'.
9969         if (var->isARCPseudoStrong() &&
9970             (!var->getTypeSourceInfo() ||
9971              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9972           // There are two pseudo-strong cases:
9973           //  - self
9974           ObjCMethodDecl *method = S.getCurMethodDecl();
9975           if (method && var == method->getSelfDecl())
9976             DiagID = method->isClassMethod()
9977               ? diag::err_typecheck_arc_assign_self_class_method
9978               : diag::err_typecheck_arc_assign_self;
9979
9980           //  - fast enumeration variables
9981           else
9982             DiagID = diag::err_typecheck_arr_assign_enumeration;
9983
9984           SourceRange Assign;
9985           if (Loc != OrigLoc)
9986             Assign = SourceRange(OrigLoc, OrigLoc);
9987           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9988           // We need to preserve the AST regardless, so migration tool
9989           // can do its job.
9990           return false;
9991         }
9992       }
9993     }
9994
9995     // If none of the special cases above are triggered, then this is a
9996     // simple const assignment.
9997     if (DiagID == 0) {
9998       DiagnoseConstAssignment(S, E, Loc);
9999       return true;
10000     }
10001
10002     break;
10003   case Expr::MLV_ConstAddrSpace:
10004     DiagnoseConstAssignment(S, E, Loc);
10005     return true;
10006   case Expr::MLV_ArrayType:
10007   case Expr::MLV_ArrayTemporary:
10008     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10009     NeedType = true;
10010     break;
10011   case Expr::MLV_NotObjectType:
10012     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10013     NeedType = true;
10014     break;
10015   case Expr::MLV_LValueCast:
10016     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10017     break;
10018   case Expr::MLV_Valid:
10019     llvm_unreachable("did not take early return for MLV_Valid");
10020   case Expr::MLV_InvalidExpression:
10021   case Expr::MLV_MemberFunction:
10022   case Expr::MLV_ClassTemporary:
10023     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10024     break;
10025   case Expr::MLV_IncompleteType:
10026   case Expr::MLV_IncompleteVoidType:
10027     return S.RequireCompleteType(Loc, E->getType(),
10028              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10029   case Expr::MLV_DuplicateVectorComponents:
10030     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10031     break;
10032   case Expr::MLV_NoSetterProperty:
10033     llvm_unreachable("readonly properties should be processed differently");
10034   case Expr::MLV_InvalidMessageExpression:
10035     DiagID = diag::error_readonly_message_assignment;
10036     break;
10037   case Expr::MLV_SubObjCPropertySetting:
10038     DiagID = diag::error_no_subobject_property_setting;
10039     break;
10040   }
10041
10042   SourceRange Assign;
10043   if (Loc != OrigLoc)
10044     Assign = SourceRange(OrigLoc, OrigLoc);
10045   if (NeedType)
10046     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10047   else
10048     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10049   return true;
10050 }
10051
10052 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10053                                          SourceLocation Loc,
10054                                          Sema &Sema) {
10055   // C / C++ fields
10056   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10057   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10058   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10059     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10060       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10061   }
10062
10063   // Objective-C instance variables
10064   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10065   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10066   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10067     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10068     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10069     if (RL && RR && RL->getDecl() == RR->getDecl())
10070       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10071   }
10072 }
10073
10074 // C99 6.5.16.1
10075 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10076                                        SourceLocation Loc,
10077                                        QualType CompoundType) {
10078   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10079
10080   // Verify that LHS is a modifiable lvalue, and emit error if not.
10081   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10082     return QualType();
10083
10084   QualType LHSType = LHSExpr->getType();
10085   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10086                                              CompoundType;
10087   // OpenCL v1.2 s6.1.1.1 p2:
10088   // The half data type can only be used to declare a pointer to a buffer that
10089   // contains half values
10090   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
10091     LHSType->isHalfType()) {
10092     Diag(Loc, diag::err_opencl_half_load_store) << 1
10093         << LHSType.getUnqualifiedType();
10094     return QualType();
10095   }
10096     
10097   AssignConvertType ConvTy;
10098   if (CompoundType.isNull()) {
10099     Expr *RHSCheck = RHS.get();
10100
10101     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10102
10103     QualType LHSTy(LHSType);
10104     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10105     if (RHS.isInvalid())
10106       return QualType();
10107     // Special case of NSObject attributes on c-style pointer types.
10108     if (ConvTy == IncompatiblePointer &&
10109         ((Context.isObjCNSObjectType(LHSType) &&
10110           RHSType->isObjCObjectPointerType()) ||
10111          (Context.isObjCNSObjectType(RHSType) &&
10112           LHSType->isObjCObjectPointerType())))
10113       ConvTy = Compatible;
10114
10115     if (ConvTy == Compatible &&
10116         LHSType->isObjCObjectType())
10117         Diag(Loc, diag::err_objc_object_assignment)
10118           << LHSType;
10119
10120     // If the RHS is a unary plus or minus, check to see if they = and + are
10121     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10122     // instead of "x += 4".
10123     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10124       RHSCheck = ICE->getSubExpr();
10125     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10126       if ((UO->getOpcode() == UO_Plus ||
10127            UO->getOpcode() == UO_Minus) &&
10128           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10129           // Only if the two operators are exactly adjacent.
10130           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10131           // And there is a space or other character before the subexpr of the
10132           // unary +/-.  We don't want to warn on "x=-1".
10133           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10134           UO->getSubExpr()->getLocStart().isFileID()) {
10135         Diag(Loc, diag::warn_not_compound_assign)
10136           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10137           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10138       }
10139     }
10140
10141     if (ConvTy == Compatible) {
10142       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10143         // Warn about retain cycles where a block captures the LHS, but
10144         // not if the LHS is a simple variable into which the block is
10145         // being stored...unless that variable can be captured by reference!
10146         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10147         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10148         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10149           checkRetainCycles(LHSExpr, RHS.get());
10150
10151         // It is safe to assign a weak reference into a strong variable.
10152         // Although this code can still have problems:
10153         //   id x = self.weakProp;
10154         //   id y = self.weakProp;
10155         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10156         // paths through the function. This should be revisited if
10157         // -Wrepeated-use-of-weak is made flow-sensitive.
10158         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10159                              RHS.get()->getLocStart()))
10160           getCurFunction()->markSafeWeakUse(RHS.get());
10161
10162       } else if (getLangOpts().ObjCAutoRefCount) {
10163         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10164       }
10165     }
10166   } else {
10167     // Compound assignment "x += y"
10168     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10169   }
10170
10171   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10172                                RHS.get(), AA_Assigning))
10173     return QualType();
10174
10175   CheckForNullPointerDereference(*this, LHSExpr);
10176
10177   // C99 6.5.16p3: The type of an assignment expression is the type of the
10178   // left operand unless the left operand has qualified type, in which case
10179   // it is the unqualified version of the type of the left operand.
10180   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10181   // is converted to the type of the assignment expression (above).
10182   // C++ 5.17p1: the type of the assignment expression is that of its left
10183   // operand.
10184   return (getLangOpts().CPlusPlus
10185           ? LHSType : LHSType.getUnqualifiedType());
10186 }
10187
10188 // Only ignore explicit casts to void.
10189 static bool IgnoreCommaOperand(const Expr *E) {
10190   E = E->IgnoreParens();
10191
10192   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10193     if (CE->getCastKind() == CK_ToVoid) {
10194       return true;
10195     }
10196   }
10197
10198   return false;
10199 }
10200
10201 // Look for instances where it is likely the comma operator is confused with
10202 // another operator.  There is a whitelist of acceptable expressions for the
10203 // left hand side of the comma operator, otherwise emit a warning.
10204 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10205   // No warnings in macros
10206   if (Loc.isMacroID())
10207     return;
10208
10209   // Don't warn in template instantiations.
10210   if (!ActiveTemplateInstantiations.empty())
10211     return;
10212
10213   // Scope isn't fine-grained enough to whitelist the specific cases, so
10214   // instead, skip more than needed, then call back into here with the
10215   // CommaVisitor in SemaStmt.cpp.
10216   // The whitelisted locations are the initialization and increment portions
10217   // of a for loop.  The additional checks are on the condition of
10218   // if statements, do/while loops, and for loops.
10219   const unsigned ForIncrementFlags =
10220       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10221   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10222   const unsigned ScopeFlags = getCurScope()->getFlags();
10223   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10224       (ScopeFlags & ForInitFlags) == ForInitFlags)
10225     return;
10226
10227   // If there are multiple comma operators used together, get the RHS of the
10228   // of the comma operator as the LHS.
10229   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10230     if (BO->getOpcode() != BO_Comma)
10231       break;
10232     LHS = BO->getRHS();
10233   }
10234
10235   // Only allow some expressions on LHS to not warn.
10236   if (IgnoreCommaOperand(LHS))
10237     return;
10238
10239   Diag(Loc, diag::warn_comma_operator);
10240   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10241       << LHS->getSourceRange()
10242       << FixItHint::CreateInsertion(LHS->getLocStart(),
10243                                     LangOpts.CPlusPlus ? "static_cast<void>("
10244                                                        : "(void)(")
10245       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10246                                     ")");
10247 }
10248
10249 // C99 6.5.17
10250 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10251                                    SourceLocation Loc) {
10252   LHS = S.CheckPlaceholderExpr(LHS.get());
10253   RHS = S.CheckPlaceholderExpr(RHS.get());
10254   if (LHS.isInvalid() || RHS.isInvalid())
10255     return QualType();
10256
10257   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10258   // operands, but not unary promotions.
10259   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10260
10261   // So we treat the LHS as a ignored value, and in C++ we allow the
10262   // containing site to determine what should be done with the RHS.
10263   LHS = S.IgnoredValueConversions(LHS.get());
10264   if (LHS.isInvalid())
10265     return QualType();
10266
10267   S.DiagnoseUnusedExprResult(LHS.get());
10268
10269   if (!S.getLangOpts().CPlusPlus) {
10270     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10271     if (RHS.isInvalid())
10272       return QualType();
10273     if (!RHS.get()->getType()->isVoidType())
10274       S.RequireCompleteType(Loc, RHS.get()->getType(),
10275                             diag::err_incomplete_type);
10276   }
10277
10278   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10279     S.DiagnoseCommaOperator(LHS.get(), Loc);
10280
10281   return RHS.get()->getType();
10282 }
10283
10284 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10285 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10286 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10287                                                ExprValueKind &VK,
10288                                                ExprObjectKind &OK,
10289                                                SourceLocation OpLoc,
10290                                                bool IsInc, bool IsPrefix) {
10291   if (Op->isTypeDependent())
10292     return S.Context.DependentTy;
10293
10294   QualType ResType = Op->getType();
10295   // Atomic types can be used for increment / decrement where the non-atomic
10296   // versions can, so ignore the _Atomic() specifier for the purpose of
10297   // checking.
10298   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10299     ResType = ResAtomicType->getValueType();
10300
10301   assert(!ResType.isNull() && "no type for increment/decrement expression");
10302
10303   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10304     // Decrement of bool is not allowed.
10305     if (!IsInc) {
10306       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10307       return QualType();
10308     }
10309     // Increment of bool sets it to true, but is deprecated.
10310     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10311                                               : diag::warn_increment_bool)
10312       << Op->getSourceRange();
10313   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10314     // Error on enum increments and decrements in C++ mode
10315     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10316     return QualType();
10317   } else if (ResType->isRealType()) {
10318     // OK!
10319   } else if (ResType->isPointerType()) {
10320     // C99 6.5.2.4p2, 6.5.6p2
10321     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10322       return QualType();
10323   } else if (ResType->isObjCObjectPointerType()) {
10324     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10325     // Otherwise, we just need a complete type.
10326     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10327         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10328       return QualType();    
10329   } else if (ResType->isAnyComplexType()) {
10330     // C99 does not support ++/-- on complex types, we allow as an extension.
10331     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10332       << ResType << Op->getSourceRange();
10333   } else if (ResType->isPlaceholderType()) {
10334     ExprResult PR = S.CheckPlaceholderExpr(Op);
10335     if (PR.isInvalid()) return QualType();
10336     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10337                                           IsInc, IsPrefix);
10338   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10339     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10340   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10341              (ResType->getAs<VectorType>()->getVectorKind() !=
10342               VectorType::AltiVecBool)) {
10343     // The z vector extensions allow ++ and -- for non-bool vectors.
10344   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10345             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10346     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10347   } else {
10348     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10349       << ResType << int(IsInc) << Op->getSourceRange();
10350     return QualType();
10351   }
10352   // At this point, we know we have a real, complex or pointer type.
10353   // Now make sure the operand is a modifiable lvalue.
10354   if (CheckForModifiableLvalue(Op, OpLoc, S))
10355     return QualType();
10356   // In C++, a prefix increment is the same type as the operand. Otherwise
10357   // (in C or with postfix), the increment is the unqualified type of the
10358   // operand.
10359   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10360     VK = VK_LValue;
10361     OK = Op->getObjectKind();
10362     return ResType;
10363   } else {
10364     VK = VK_RValue;
10365     return ResType.getUnqualifiedType();
10366   }
10367 }
10368   
10369
10370 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10371 /// This routine allows us to typecheck complex/recursive expressions
10372 /// where the declaration is needed for type checking. We only need to
10373 /// handle cases when the expression references a function designator
10374 /// or is an lvalue. Here are some examples:
10375 ///  - &(x) => x
10376 ///  - &*****f => f for f a function designator.
10377 ///  - &s.xx => s
10378 ///  - &s.zz[1].yy -> s, if zz is an array
10379 ///  - *(x + 1) -> x, if x is an array
10380 ///  - &"123"[2] -> 0
10381 ///  - & __real__ x -> x
10382 static ValueDecl *getPrimaryDecl(Expr *E) {
10383   switch (E->getStmtClass()) {
10384   case Stmt::DeclRefExprClass:
10385     return cast<DeclRefExpr>(E)->getDecl();
10386   case Stmt::MemberExprClass:
10387     // If this is an arrow operator, the address is an offset from
10388     // the base's value, so the object the base refers to is
10389     // irrelevant.
10390     if (cast<MemberExpr>(E)->isArrow())
10391       return nullptr;
10392     // Otherwise, the expression refers to a part of the base
10393     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10394   case Stmt::ArraySubscriptExprClass: {
10395     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10396     // promotion of register arrays earlier.
10397     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10398     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10399       if (ICE->getSubExpr()->getType()->isArrayType())
10400         return getPrimaryDecl(ICE->getSubExpr());
10401     }
10402     return nullptr;
10403   }
10404   case Stmt::UnaryOperatorClass: {
10405     UnaryOperator *UO = cast<UnaryOperator>(E);
10406
10407     switch(UO->getOpcode()) {
10408     case UO_Real:
10409     case UO_Imag:
10410     case UO_Extension:
10411       return getPrimaryDecl(UO->getSubExpr());
10412     default:
10413       return nullptr;
10414     }
10415   }
10416   case Stmt::ParenExprClass:
10417     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10418   case Stmt::ImplicitCastExprClass:
10419     // If the result of an implicit cast is an l-value, we care about
10420     // the sub-expression; otherwise, the result here doesn't matter.
10421     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10422   default:
10423     return nullptr;
10424   }
10425 }
10426
10427 namespace {
10428   enum {
10429     AO_Bit_Field = 0,
10430     AO_Vector_Element = 1,
10431     AO_Property_Expansion = 2,
10432     AO_Register_Variable = 3,
10433     AO_No_Error = 4
10434   };
10435 }
10436 /// \brief Diagnose invalid operand for address of operations.
10437 ///
10438 /// \param Type The type of operand which cannot have its address taken.
10439 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10440                                          Expr *E, unsigned Type) {
10441   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10442 }
10443
10444 /// CheckAddressOfOperand - The operand of & must be either a function
10445 /// designator or an lvalue designating an object. If it is an lvalue, the
10446 /// object cannot be declared with storage class register or be a bit field.
10447 /// Note: The usual conversions are *not* applied to the operand of the &
10448 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10449 /// In C++, the operand might be an overloaded function name, in which case
10450 /// we allow the '&' but retain the overloaded-function type.
10451 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10452   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10453     if (PTy->getKind() == BuiltinType::Overload) {
10454       Expr *E = OrigOp.get()->IgnoreParens();
10455       if (!isa<OverloadExpr>(E)) {
10456         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10457         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10458           << OrigOp.get()->getSourceRange();
10459         return QualType();
10460       }
10461
10462       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10463       if (isa<UnresolvedMemberExpr>(Ovl))
10464         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10465           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10466             << OrigOp.get()->getSourceRange();
10467           return QualType();
10468         }
10469
10470       return Context.OverloadTy;
10471     }
10472
10473     if (PTy->getKind() == BuiltinType::UnknownAny)
10474       return Context.UnknownAnyTy;
10475
10476     if (PTy->getKind() == BuiltinType::BoundMember) {
10477       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10478         << OrigOp.get()->getSourceRange();
10479       return QualType();
10480     }
10481
10482     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10483     if (OrigOp.isInvalid()) return QualType();
10484   }
10485
10486   if (OrigOp.get()->isTypeDependent())
10487     return Context.DependentTy;
10488
10489   assert(!OrigOp.get()->getType()->isPlaceholderType());
10490
10491   // Make sure to ignore parentheses in subsequent checks
10492   Expr *op = OrigOp.get()->IgnoreParens();
10493
10494   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10495   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10496     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10497     return QualType();
10498   }
10499
10500   if (getLangOpts().C99) {
10501     // Implement C99-only parts of addressof rules.
10502     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10503       if (uOp->getOpcode() == UO_Deref)
10504         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10505         // (assuming the deref expression is valid).
10506         return uOp->getSubExpr()->getType();
10507     }
10508     // Technically, there should be a check for array subscript
10509     // expressions here, but the result of one is always an lvalue anyway.
10510   }
10511   ValueDecl *dcl = getPrimaryDecl(op);
10512
10513   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10514     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10515                                            op->getLocStart()))
10516       return QualType();
10517
10518   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10519   unsigned AddressOfError = AO_No_Error;
10520
10521   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10522     bool sfinae = (bool)isSFINAEContext();
10523     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10524                                   : diag::ext_typecheck_addrof_temporary)
10525       << op->getType() << op->getSourceRange();
10526     if (sfinae)
10527       return QualType();
10528     // Materialize the temporary as an lvalue so that we can take its address.
10529     OrigOp = op =
10530         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10531   } else if (isa<ObjCSelectorExpr>(op)) {
10532     return Context.getPointerType(op->getType());
10533   } else if (lval == Expr::LV_MemberFunction) {
10534     // If it's an instance method, make a member pointer.
10535     // The expression must have exactly the form &A::foo.
10536
10537     // If the underlying expression isn't a decl ref, give up.
10538     if (!isa<DeclRefExpr>(op)) {
10539       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10540         << OrigOp.get()->getSourceRange();
10541       return QualType();
10542     }
10543     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10544     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10545
10546     // The id-expression was parenthesized.
10547     if (OrigOp.get() != DRE) {
10548       Diag(OpLoc, diag::err_parens_pointer_member_function)
10549         << OrigOp.get()->getSourceRange();
10550
10551     // The method was named without a qualifier.
10552     } else if (!DRE->getQualifier()) {
10553       if (MD->getParent()->getName().empty())
10554         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10555           << op->getSourceRange();
10556       else {
10557         SmallString<32> Str;
10558         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10559         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10560           << op->getSourceRange()
10561           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10562       }
10563     }
10564
10565     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10566     if (isa<CXXDestructorDecl>(MD))
10567       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10568
10569     QualType MPTy = Context.getMemberPointerType(
10570         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10571     // Under the MS ABI, lock down the inheritance model now.
10572     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10573       (void)isCompleteType(OpLoc, MPTy);
10574     return MPTy;
10575   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10576     // C99 6.5.3.2p1
10577     // The operand must be either an l-value or a function designator
10578     if (!op->getType()->isFunctionType()) {
10579       // Use a special diagnostic for loads from property references.
10580       if (isa<PseudoObjectExpr>(op)) {
10581         AddressOfError = AO_Property_Expansion;
10582       } else {
10583         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10584           << op->getType() << op->getSourceRange();
10585         return QualType();
10586       }
10587     }
10588   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10589     // The operand cannot be a bit-field
10590     AddressOfError = AO_Bit_Field;
10591   } else if (op->getObjectKind() == OK_VectorComponent) {
10592     // The operand cannot be an element of a vector
10593     AddressOfError = AO_Vector_Element;
10594   } else if (dcl) { // C99 6.5.3.2p1
10595     // We have an lvalue with a decl. Make sure the decl is not declared
10596     // with the register storage-class specifier.
10597     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10598       // in C++ it is not error to take address of a register
10599       // variable (c++03 7.1.1P3)
10600       if (vd->getStorageClass() == SC_Register &&
10601           !getLangOpts().CPlusPlus) {
10602         AddressOfError = AO_Register_Variable;
10603       }
10604     } else if (isa<MSPropertyDecl>(dcl)) {
10605       AddressOfError = AO_Property_Expansion;
10606     } else if (isa<FunctionTemplateDecl>(dcl)) {
10607       return Context.OverloadTy;
10608     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10609       // Okay: we can take the address of a field.
10610       // Could be a pointer to member, though, if there is an explicit
10611       // scope qualifier for the class.
10612       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10613         DeclContext *Ctx = dcl->getDeclContext();
10614         if (Ctx && Ctx->isRecord()) {
10615           if (dcl->getType()->isReferenceType()) {
10616             Diag(OpLoc,
10617                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10618               << dcl->getDeclName() << dcl->getType();
10619             return QualType();
10620           }
10621
10622           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10623             Ctx = Ctx->getParent();
10624
10625           QualType MPTy = Context.getMemberPointerType(
10626               op->getType(),
10627               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10628           // Under the MS ABI, lock down the inheritance model now.
10629           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10630             (void)isCompleteType(OpLoc, MPTy);
10631           return MPTy;
10632         }
10633       }
10634     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10635                !isa<BindingDecl>(dcl))
10636       llvm_unreachable("Unknown/unexpected decl type");
10637   }
10638
10639   if (AddressOfError != AO_No_Error) {
10640     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10641     return QualType();
10642   }
10643
10644   if (lval == Expr::LV_IncompleteVoidType) {
10645     // Taking the address of a void variable is technically illegal, but we
10646     // allow it in cases which are otherwise valid.
10647     // Example: "extern void x; void* y = &x;".
10648     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10649   }
10650
10651   // If the operand has type "type", the result has type "pointer to type".
10652   if (op->getType()->isObjCObjectType())
10653     return Context.getObjCObjectPointerType(op->getType());
10654
10655   CheckAddressOfPackedMember(op);
10656
10657   return Context.getPointerType(op->getType());
10658 }
10659
10660 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10661   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10662   if (!DRE)
10663     return;
10664   const Decl *D = DRE->getDecl();
10665   if (!D)
10666     return;
10667   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10668   if (!Param)
10669     return;
10670   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10671     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10672       return;
10673   if (FunctionScopeInfo *FD = S.getCurFunction())
10674     if (!FD->ModifiedNonNullParams.count(Param))
10675       FD->ModifiedNonNullParams.insert(Param);
10676 }
10677
10678 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10679 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10680                                         SourceLocation OpLoc) {
10681   if (Op->isTypeDependent())
10682     return S.Context.DependentTy;
10683
10684   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10685   if (ConvResult.isInvalid())
10686     return QualType();
10687   Op = ConvResult.get();
10688   QualType OpTy = Op->getType();
10689   QualType Result;
10690
10691   if (isa<CXXReinterpretCastExpr>(Op)) {
10692     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10693     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10694                                      Op->getSourceRange());
10695   }
10696
10697   if (const PointerType *PT = OpTy->getAs<PointerType>())
10698   {
10699     Result = PT->getPointeeType();
10700   }
10701   else if (const ObjCObjectPointerType *OPT =
10702              OpTy->getAs<ObjCObjectPointerType>())
10703     Result = OPT->getPointeeType();
10704   else {
10705     ExprResult PR = S.CheckPlaceholderExpr(Op);
10706     if (PR.isInvalid()) return QualType();
10707     if (PR.get() != Op)
10708       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10709   }
10710
10711   if (Result.isNull()) {
10712     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10713       << OpTy << Op->getSourceRange();
10714     return QualType();
10715   }
10716
10717   // Note that per both C89 and C99, indirection is always legal, even if Result
10718   // is an incomplete type or void.  It would be possible to warn about
10719   // dereferencing a void pointer, but it's completely well-defined, and such a
10720   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10721   // for pointers to 'void' but is fine for any other pointer type:
10722   //
10723   // C++ [expr.unary.op]p1:
10724   //   [...] the expression to which [the unary * operator] is applied shall
10725   //   be a pointer to an object type, or a pointer to a function type
10726   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10727     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10728       << OpTy << Op->getSourceRange();
10729
10730   // Dereferences are usually l-values...
10731   VK = VK_LValue;
10732
10733   // ...except that certain expressions are never l-values in C.
10734   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10735     VK = VK_RValue;
10736   
10737   return Result;
10738 }
10739
10740 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10741   BinaryOperatorKind Opc;
10742   switch (Kind) {
10743   default: llvm_unreachable("Unknown binop!");
10744   case tok::periodstar:           Opc = BO_PtrMemD; break;
10745   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10746   case tok::star:                 Opc = BO_Mul; break;
10747   case tok::slash:                Opc = BO_Div; break;
10748   case tok::percent:              Opc = BO_Rem; break;
10749   case tok::plus:                 Opc = BO_Add; break;
10750   case tok::minus:                Opc = BO_Sub; break;
10751   case tok::lessless:             Opc = BO_Shl; break;
10752   case tok::greatergreater:       Opc = BO_Shr; break;
10753   case tok::lessequal:            Opc = BO_LE; break;
10754   case tok::less:                 Opc = BO_LT; break;
10755   case tok::greaterequal:         Opc = BO_GE; break;
10756   case tok::greater:              Opc = BO_GT; break;
10757   case tok::exclaimequal:         Opc = BO_NE; break;
10758   case tok::equalequal:           Opc = BO_EQ; break;
10759   case tok::amp:                  Opc = BO_And; break;
10760   case tok::caret:                Opc = BO_Xor; break;
10761   case tok::pipe:                 Opc = BO_Or; break;
10762   case tok::ampamp:               Opc = BO_LAnd; break;
10763   case tok::pipepipe:             Opc = BO_LOr; break;
10764   case tok::equal:                Opc = BO_Assign; break;
10765   case tok::starequal:            Opc = BO_MulAssign; break;
10766   case tok::slashequal:           Opc = BO_DivAssign; break;
10767   case tok::percentequal:         Opc = BO_RemAssign; break;
10768   case tok::plusequal:            Opc = BO_AddAssign; break;
10769   case tok::minusequal:           Opc = BO_SubAssign; break;
10770   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10771   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10772   case tok::ampequal:             Opc = BO_AndAssign; break;
10773   case tok::caretequal:           Opc = BO_XorAssign; break;
10774   case tok::pipeequal:            Opc = BO_OrAssign; break;
10775   case tok::comma:                Opc = BO_Comma; break;
10776   }
10777   return Opc;
10778 }
10779
10780 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10781   tok::TokenKind Kind) {
10782   UnaryOperatorKind Opc;
10783   switch (Kind) {
10784   default: llvm_unreachable("Unknown unary op!");
10785   case tok::plusplus:     Opc = UO_PreInc; break;
10786   case tok::minusminus:   Opc = UO_PreDec; break;
10787   case tok::amp:          Opc = UO_AddrOf; break;
10788   case tok::star:         Opc = UO_Deref; break;
10789   case tok::plus:         Opc = UO_Plus; break;
10790   case tok::minus:        Opc = UO_Minus; break;
10791   case tok::tilde:        Opc = UO_Not; break;
10792   case tok::exclaim:      Opc = UO_LNot; break;
10793   case tok::kw___real:    Opc = UO_Real; break;
10794   case tok::kw___imag:    Opc = UO_Imag; break;
10795   case tok::kw___extension__: Opc = UO_Extension; break;
10796   }
10797   return Opc;
10798 }
10799
10800 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10801 /// This warning is only emitted for builtin assignment operations. It is also
10802 /// suppressed in the event of macro expansions.
10803 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10804                                    SourceLocation OpLoc) {
10805   if (!S.ActiveTemplateInstantiations.empty())
10806     return;
10807   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10808     return;
10809   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10810   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10811   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10812   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10813   if (!LHSDeclRef || !RHSDeclRef ||
10814       LHSDeclRef->getLocation().isMacroID() ||
10815       RHSDeclRef->getLocation().isMacroID())
10816     return;
10817   const ValueDecl *LHSDecl =
10818     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10819   const ValueDecl *RHSDecl =
10820     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10821   if (LHSDecl != RHSDecl)
10822     return;
10823   if (LHSDecl->getType().isVolatileQualified())
10824     return;
10825   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10826     if (RefTy->getPointeeType().isVolatileQualified())
10827       return;
10828
10829   S.Diag(OpLoc, diag::warn_self_assignment)
10830       << LHSDeclRef->getType()
10831       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10832 }
10833
10834 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10835 /// is usually indicative of introspection within the Objective-C pointer.
10836 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10837                                           SourceLocation OpLoc) {
10838   if (!S.getLangOpts().ObjC1)
10839     return;
10840
10841   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10842   const Expr *LHS = L.get();
10843   const Expr *RHS = R.get();
10844
10845   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10846     ObjCPointerExpr = LHS;
10847     OtherExpr = RHS;
10848   }
10849   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10850     ObjCPointerExpr = RHS;
10851     OtherExpr = LHS;
10852   }
10853
10854   // This warning is deliberately made very specific to reduce false
10855   // positives with logic that uses '&' for hashing.  This logic mainly
10856   // looks for code trying to introspect into tagged pointers, which
10857   // code should generally never do.
10858   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10859     unsigned Diag = diag::warn_objc_pointer_masking;
10860     // Determine if we are introspecting the result of performSelectorXXX.
10861     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10862     // Special case messages to -performSelector and friends, which
10863     // can return non-pointer values boxed in a pointer value.
10864     // Some clients may wish to silence warnings in this subcase.
10865     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10866       Selector S = ME->getSelector();
10867       StringRef SelArg0 = S.getNameForSlot(0);
10868       if (SelArg0.startswith("performSelector"))
10869         Diag = diag::warn_objc_pointer_masking_performSelector;
10870     }
10871     
10872     S.Diag(OpLoc, Diag)
10873       << ObjCPointerExpr->getSourceRange();
10874   }
10875 }
10876
10877 static NamedDecl *getDeclFromExpr(Expr *E) {
10878   if (!E)
10879     return nullptr;
10880   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10881     return DRE->getDecl();
10882   if (auto *ME = dyn_cast<MemberExpr>(E))
10883     return ME->getMemberDecl();
10884   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10885     return IRE->getDecl();
10886   return nullptr;
10887 }
10888
10889 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10890 /// operator @p Opc at location @c TokLoc. This routine only supports
10891 /// built-in operations; ActOnBinOp handles overloaded operators.
10892 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10893                                     BinaryOperatorKind Opc,
10894                                     Expr *LHSExpr, Expr *RHSExpr) {
10895   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10896     // The syntax only allows initializer lists on the RHS of assignment,
10897     // so we don't need to worry about accepting invalid code for
10898     // non-assignment operators.
10899     // C++11 5.17p9:
10900     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10901     //   of x = {} is x = T().
10902     InitializationKind Kind =
10903         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10904     InitializedEntity Entity =
10905         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10906     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10907     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10908     if (Init.isInvalid())
10909       return Init;
10910     RHSExpr = Init.get();
10911   }
10912
10913   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10914   QualType ResultTy;     // Result type of the binary operator.
10915   // The following two variables are used for compound assignment operators
10916   QualType CompLHSTy;    // Type of LHS after promotions for computation
10917   QualType CompResultTy; // Type of computation result
10918   ExprValueKind VK = VK_RValue;
10919   ExprObjectKind OK = OK_Ordinary;
10920
10921   if (!getLangOpts().CPlusPlus) {
10922     // C cannot handle TypoExpr nodes on either side of a binop because it
10923     // doesn't handle dependent types properly, so make sure any TypoExprs have
10924     // been dealt with before checking the operands.
10925     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10926     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10927       if (Opc != BO_Assign)
10928         return ExprResult(E);
10929       // Avoid correcting the RHS to the same Expr as the LHS.
10930       Decl *D = getDeclFromExpr(E);
10931       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10932     });
10933     if (!LHS.isUsable() || !RHS.isUsable())
10934       return ExprError();
10935   }
10936
10937   if (getLangOpts().OpenCL) {
10938     QualType LHSTy = LHSExpr->getType();
10939     QualType RHSTy = RHSExpr->getType();
10940     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10941     // the ATOMIC_VAR_INIT macro.
10942     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10943       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10944       if (BO_Assign == Opc)
10945         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10946       else
10947         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10948       return ExprError();
10949     }
10950
10951     // OpenCL special types - image, sampler, pipe, and blocks are to be used
10952     // only with a builtin functions and therefore should be disallowed here.
10953     if (LHSTy->isImageType() || RHSTy->isImageType() ||
10954         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
10955         LHSTy->isPipeType() || RHSTy->isPipeType() ||
10956         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
10957       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10958       return ExprError();
10959     }
10960   }
10961
10962   switch (Opc) {
10963   case BO_Assign:
10964     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10965     if (getLangOpts().CPlusPlus &&
10966         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10967       VK = LHS.get()->getValueKind();
10968       OK = LHS.get()->getObjectKind();
10969     }
10970     if (!ResultTy.isNull()) {
10971       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10972       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10973     }
10974     RecordModifiableNonNullParam(*this, LHS.get());
10975     break;
10976   case BO_PtrMemD:
10977   case BO_PtrMemI:
10978     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10979                                             Opc == BO_PtrMemI);
10980     break;
10981   case BO_Mul:
10982   case BO_Div:
10983     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10984                                            Opc == BO_Div);
10985     break;
10986   case BO_Rem:
10987     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10988     break;
10989   case BO_Add:
10990     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10991     break;
10992   case BO_Sub:
10993     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10994     break;
10995   case BO_Shl:
10996   case BO_Shr:
10997     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10998     break;
10999   case BO_LE:
11000   case BO_LT:
11001   case BO_GE:
11002   case BO_GT:
11003     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11004     break;
11005   case BO_EQ:
11006   case BO_NE:
11007     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11008     break;
11009   case BO_And:
11010     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11011   case BO_Xor:
11012   case BO_Or:
11013     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
11014     break;
11015   case BO_LAnd:
11016   case BO_LOr:
11017     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11018     break;
11019   case BO_MulAssign:
11020   case BO_DivAssign:
11021     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11022                                                Opc == BO_DivAssign);
11023     CompLHSTy = CompResultTy;
11024     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11025       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11026     break;
11027   case BO_RemAssign:
11028     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11029     CompLHSTy = CompResultTy;
11030     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11031       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11032     break;
11033   case BO_AddAssign:
11034     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11035     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11036       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11037     break;
11038   case BO_SubAssign:
11039     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11040     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11041       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11042     break;
11043   case BO_ShlAssign:
11044   case BO_ShrAssign:
11045     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11046     CompLHSTy = CompResultTy;
11047     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11048       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11049     break;
11050   case BO_AndAssign:
11051   case BO_OrAssign: // fallthrough
11052     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11053   case BO_XorAssign:
11054     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
11055     CompLHSTy = CompResultTy;
11056     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11057       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11058     break;
11059   case BO_Comma:
11060     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11061     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11062       VK = RHS.get()->getValueKind();
11063       OK = RHS.get()->getObjectKind();
11064     }
11065     break;
11066   }
11067   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11068     return ExprError();
11069
11070   // Check for array bounds violations for both sides of the BinaryOperator
11071   CheckArrayAccess(LHS.get());
11072   CheckArrayAccess(RHS.get());
11073
11074   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11075     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11076                                                  &Context.Idents.get("object_setClass"),
11077                                                  SourceLocation(), LookupOrdinaryName);
11078     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11079       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11080       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11081       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11082       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11083       FixItHint::CreateInsertion(RHSLocEnd, ")");
11084     }
11085     else
11086       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11087   }
11088   else if (const ObjCIvarRefExpr *OIRE =
11089            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11090     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11091   
11092   if (CompResultTy.isNull())
11093     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11094                                         OK, OpLoc, FPFeatures.fp_contract);
11095   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11096       OK_ObjCProperty) {
11097     VK = VK_LValue;
11098     OK = LHS.get()->getObjectKind();
11099   }
11100   return new (Context) CompoundAssignOperator(
11101       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11102       OpLoc, FPFeatures.fp_contract);
11103 }
11104
11105 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11106 /// operators are mixed in a way that suggests that the programmer forgot that
11107 /// comparison operators have higher precedence. The most typical example of
11108 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11109 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11110                                       SourceLocation OpLoc, Expr *LHSExpr,
11111                                       Expr *RHSExpr) {
11112   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11113   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11114
11115   // Check that one of the sides is a comparison operator and the other isn't.
11116   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11117   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11118   if (isLeftComp == isRightComp)
11119     return;
11120
11121   // Bitwise operations are sometimes used as eager logical ops.
11122   // Don't diagnose this.
11123   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11124   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11125   if (isLeftBitwise || isRightBitwise)
11126     return;
11127
11128   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11129                                                    OpLoc)
11130                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11131   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11132   SourceRange ParensRange = isLeftComp ?
11133       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11134     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11135
11136   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11137     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11138   SuggestParentheses(Self, OpLoc,
11139     Self.PDiag(diag::note_precedence_silence) << OpStr,
11140     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11141   SuggestParentheses(Self, OpLoc,
11142     Self.PDiag(diag::note_precedence_bitwise_first)
11143       << BinaryOperator::getOpcodeStr(Opc),
11144     ParensRange);
11145 }
11146
11147 /// \brief It accepts a '&&' expr that is inside a '||' one.
11148 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11149 /// in parentheses.
11150 static void
11151 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11152                                        BinaryOperator *Bop) {
11153   assert(Bop->getOpcode() == BO_LAnd);
11154   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11155       << Bop->getSourceRange() << OpLoc;
11156   SuggestParentheses(Self, Bop->getOperatorLoc(),
11157     Self.PDiag(diag::note_precedence_silence)
11158       << Bop->getOpcodeStr(),
11159     Bop->getSourceRange());
11160 }
11161
11162 /// \brief Returns true if the given expression can be evaluated as a constant
11163 /// 'true'.
11164 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11165   bool Res;
11166   return !E->isValueDependent() &&
11167          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11168 }
11169
11170 /// \brief Returns true if the given expression can be evaluated as a constant
11171 /// 'false'.
11172 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11173   bool Res;
11174   return !E->isValueDependent() &&
11175          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11176 }
11177
11178 /// \brief Look for '&&' in the left hand of a '||' expr.
11179 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11180                                              Expr *LHSExpr, Expr *RHSExpr) {
11181   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11182     if (Bop->getOpcode() == BO_LAnd) {
11183       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11184       if (EvaluatesAsFalse(S, RHSExpr))
11185         return;
11186       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11187       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11188         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11189     } else if (Bop->getOpcode() == BO_LOr) {
11190       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11191         // If it's "a || b && 1 || c" we didn't warn earlier for
11192         // "a || b && 1", but warn now.
11193         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11194           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11195       }
11196     }
11197   }
11198 }
11199
11200 /// \brief Look for '&&' in the right hand of a '||' expr.
11201 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11202                                              Expr *LHSExpr, Expr *RHSExpr) {
11203   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11204     if (Bop->getOpcode() == BO_LAnd) {
11205       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11206       if (EvaluatesAsFalse(S, LHSExpr))
11207         return;
11208       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11209       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11210         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11211     }
11212   }
11213 }
11214
11215 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11216 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11217 /// the '&' expression in parentheses.
11218 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11219                                          SourceLocation OpLoc, Expr *SubExpr) {
11220   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11221     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11222       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11223         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11224         << Bop->getSourceRange() << OpLoc;
11225       SuggestParentheses(S, Bop->getOperatorLoc(),
11226         S.PDiag(diag::note_precedence_silence)
11227           << Bop->getOpcodeStr(),
11228         Bop->getSourceRange());
11229     }
11230   }
11231 }
11232
11233 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11234                                     Expr *SubExpr, StringRef Shift) {
11235   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11236     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11237       StringRef Op = Bop->getOpcodeStr();
11238       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11239           << Bop->getSourceRange() << OpLoc << Shift << Op;
11240       SuggestParentheses(S, Bop->getOperatorLoc(),
11241           S.PDiag(diag::note_precedence_silence) << Op,
11242           Bop->getSourceRange());
11243     }
11244   }
11245 }
11246
11247 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11248                                  Expr *LHSExpr, Expr *RHSExpr) {
11249   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11250   if (!OCE)
11251     return;
11252
11253   FunctionDecl *FD = OCE->getDirectCallee();
11254   if (!FD || !FD->isOverloadedOperator())
11255     return;
11256
11257   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11258   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11259     return;
11260
11261   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11262       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11263       << (Kind == OO_LessLess);
11264   SuggestParentheses(S, OCE->getOperatorLoc(),
11265                      S.PDiag(diag::note_precedence_silence)
11266                          << (Kind == OO_LessLess ? "<<" : ">>"),
11267                      OCE->getSourceRange());
11268   SuggestParentheses(S, OpLoc,
11269                      S.PDiag(diag::note_evaluate_comparison_first),
11270                      SourceRange(OCE->getArg(1)->getLocStart(),
11271                                  RHSExpr->getLocEnd()));
11272 }
11273
11274 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11275 /// precedence.
11276 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11277                                     SourceLocation OpLoc, Expr *LHSExpr,
11278                                     Expr *RHSExpr){
11279   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11280   if (BinaryOperator::isBitwiseOp(Opc))
11281     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11282
11283   // Diagnose "arg1 & arg2 | arg3"
11284   if ((Opc == BO_Or || Opc == BO_Xor) &&
11285       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11286     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11287     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11288   }
11289
11290   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11291   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11292   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11293     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11294     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11295   }
11296
11297   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11298       || Opc == BO_Shr) {
11299     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11300     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11301     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11302   }
11303
11304   // Warn on overloaded shift operators and comparisons, such as:
11305   // cout << 5 == 4;
11306   if (BinaryOperator::isComparisonOp(Opc))
11307     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11308 }
11309
11310 // Binary Operators.  'Tok' is the token for the operator.
11311 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11312                             tok::TokenKind Kind,
11313                             Expr *LHSExpr, Expr *RHSExpr) {
11314   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11315   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11316   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11317
11318   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11319   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11320
11321   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11322 }
11323
11324 /// Build an overloaded binary operator expression in the given scope.
11325 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11326                                        BinaryOperatorKind Opc,
11327                                        Expr *LHS, Expr *RHS) {
11328   // Find all of the overloaded operators visible from this
11329   // point. We perform both an operator-name lookup from the local
11330   // scope and an argument-dependent lookup based on the types of
11331   // the arguments.
11332   UnresolvedSet<16> Functions;
11333   OverloadedOperatorKind OverOp
11334     = BinaryOperator::getOverloadedOperator(Opc);
11335   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11336     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11337                                    RHS->getType(), Functions);
11338
11339   // Build the (potentially-overloaded, potentially-dependent)
11340   // binary operation.
11341   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11342 }
11343
11344 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11345                             BinaryOperatorKind Opc,
11346                             Expr *LHSExpr, Expr *RHSExpr) {
11347   // We want to end up calling one of checkPseudoObjectAssignment
11348   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11349   // both expressions are overloadable or either is type-dependent),
11350   // or CreateBuiltinBinOp (in any other case).  We also want to get
11351   // any placeholder types out of the way.
11352
11353   // Handle pseudo-objects in the LHS.
11354   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11355     // Assignments with a pseudo-object l-value need special analysis.
11356     if (pty->getKind() == BuiltinType::PseudoObject &&
11357         BinaryOperator::isAssignmentOp(Opc))
11358       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11359
11360     // Don't resolve overloads if the other type is overloadable.
11361     if (pty->getKind() == BuiltinType::Overload) {
11362       // We can't actually test that if we still have a placeholder,
11363       // though.  Fortunately, none of the exceptions we see in that
11364       // code below are valid when the LHS is an overload set.  Note
11365       // that an overload set can be dependently-typed, but it never
11366       // instantiates to having an overloadable type.
11367       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11368       if (resolvedRHS.isInvalid()) return ExprError();
11369       RHSExpr = resolvedRHS.get();
11370
11371       if (RHSExpr->isTypeDependent() ||
11372           RHSExpr->getType()->isOverloadableType())
11373         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11374     }
11375         
11376     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11377     if (LHS.isInvalid()) return ExprError();
11378     LHSExpr = LHS.get();
11379   }
11380
11381   // Handle pseudo-objects in the RHS.
11382   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11383     // An overload in the RHS can potentially be resolved by the type
11384     // being assigned to.
11385     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11386       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11387         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11388
11389       if (LHSExpr->getType()->isOverloadableType())
11390         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11391
11392       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11393     }
11394
11395     // Don't resolve overloads if the other type is overloadable.
11396     if (pty->getKind() == BuiltinType::Overload &&
11397         LHSExpr->getType()->isOverloadableType())
11398       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11399
11400     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11401     if (!resolvedRHS.isUsable()) return ExprError();
11402     RHSExpr = resolvedRHS.get();
11403   }
11404
11405   if (getLangOpts().CPlusPlus) {
11406     // If either expression is type-dependent, always build an
11407     // overloaded op.
11408     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11409       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11410
11411     // Otherwise, build an overloaded op if either expression has an
11412     // overloadable type.
11413     if (LHSExpr->getType()->isOverloadableType() ||
11414         RHSExpr->getType()->isOverloadableType())
11415       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11416   }
11417
11418   // Build a built-in binary operation.
11419   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11420 }
11421
11422 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11423                                       UnaryOperatorKind Opc,
11424                                       Expr *InputExpr) {
11425   ExprResult Input = InputExpr;
11426   ExprValueKind VK = VK_RValue;
11427   ExprObjectKind OK = OK_Ordinary;
11428   QualType resultType;
11429   if (getLangOpts().OpenCL) {
11430     QualType Ty = InputExpr->getType();
11431     // The only legal unary operation for atomics is '&'.
11432     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11433     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11434     // only with a builtin functions and therefore should be disallowed here.
11435         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11436         || Ty->isBlockPointerType())) {
11437       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11438                        << InputExpr->getType()
11439                        << Input.get()->getSourceRange());
11440     }
11441   }
11442   switch (Opc) {
11443   case UO_PreInc:
11444   case UO_PreDec:
11445   case UO_PostInc:
11446   case UO_PostDec:
11447     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11448                                                 OpLoc,
11449                                                 Opc == UO_PreInc ||
11450                                                 Opc == UO_PostInc,
11451                                                 Opc == UO_PreInc ||
11452                                                 Opc == UO_PreDec);
11453     break;
11454   case UO_AddrOf:
11455     resultType = CheckAddressOfOperand(Input, OpLoc);
11456     RecordModifiableNonNullParam(*this, InputExpr);
11457     break;
11458   case UO_Deref: {
11459     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11460     if (Input.isInvalid()) return ExprError();
11461     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11462     break;
11463   }
11464   case UO_Plus:
11465   case UO_Minus:
11466     Input = UsualUnaryConversions(Input.get());
11467     if (Input.isInvalid()) return ExprError();
11468     resultType = Input.get()->getType();
11469     if (resultType->isDependentType())
11470       break;
11471     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11472       break;
11473     else if (resultType->isVectorType() &&
11474              // The z vector extensions don't allow + or - with bool vectors.
11475              (!Context.getLangOpts().ZVector ||
11476               resultType->getAs<VectorType>()->getVectorKind() !=
11477               VectorType::AltiVecBool))
11478       break;
11479     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11480              Opc == UO_Plus &&
11481              resultType->isPointerType())
11482       break;
11483
11484     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11485       << resultType << Input.get()->getSourceRange());
11486
11487   case UO_Not: // bitwise complement
11488     Input = UsualUnaryConversions(Input.get());
11489     if (Input.isInvalid())
11490       return ExprError();
11491     resultType = Input.get()->getType();
11492     if (resultType->isDependentType())
11493       break;
11494     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11495     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11496       // C99 does not support '~' for complex conjugation.
11497       Diag(OpLoc, diag::ext_integer_complement_complex)
11498           << resultType << Input.get()->getSourceRange();
11499     else if (resultType->hasIntegerRepresentation())
11500       break;
11501     else if (resultType->isExtVectorType()) {
11502       if (Context.getLangOpts().OpenCL) {
11503         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11504         // on vector float types.
11505         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11506         if (!T->isIntegerType())
11507           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11508                            << resultType << Input.get()->getSourceRange());
11509       }
11510       break;
11511     } else {
11512       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11513                        << resultType << Input.get()->getSourceRange());
11514     }
11515     break;
11516
11517   case UO_LNot: // logical negation
11518     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11519     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11520     if (Input.isInvalid()) return ExprError();
11521     resultType = Input.get()->getType();
11522
11523     // Though we still have to promote half FP to float...
11524     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11525       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11526       resultType = Context.FloatTy;
11527     }
11528
11529     if (resultType->isDependentType())
11530       break;
11531     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11532       // C99 6.5.3.3p1: ok, fallthrough;
11533       if (Context.getLangOpts().CPlusPlus) {
11534         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11535         // operand contextually converted to bool.
11536         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11537                                   ScalarTypeToBooleanCastKind(resultType));
11538       } else if (Context.getLangOpts().OpenCL &&
11539                  Context.getLangOpts().OpenCLVersion < 120) {
11540         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11541         // operate on scalar float types.
11542         if (!resultType->isIntegerType())
11543           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11544                            << resultType << Input.get()->getSourceRange());
11545       }
11546     } else if (resultType->isExtVectorType()) {
11547       if (Context.getLangOpts().OpenCL &&
11548           Context.getLangOpts().OpenCLVersion < 120) {
11549         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11550         // operate on vector float types.
11551         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11552         if (!T->isIntegerType())
11553           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11554                            << resultType << Input.get()->getSourceRange());
11555       }
11556       // Vector logical not returns the signed variant of the operand type.
11557       resultType = GetSignedVectorType(resultType);
11558       break;
11559     } else {
11560       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11561         << resultType << Input.get()->getSourceRange());
11562     }
11563     
11564     // LNot always has type int. C99 6.5.3.3p5.
11565     // In C++, it's bool. C++ 5.3.1p8
11566     resultType = Context.getLogicalOperationType();
11567     break;
11568   case UO_Real:
11569   case UO_Imag:
11570     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11571     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11572     // complex l-values to ordinary l-values and all other values to r-values.
11573     if (Input.isInvalid()) return ExprError();
11574     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11575       if (Input.get()->getValueKind() != VK_RValue &&
11576           Input.get()->getObjectKind() == OK_Ordinary)
11577         VK = Input.get()->getValueKind();
11578     } else if (!getLangOpts().CPlusPlus) {
11579       // In C, a volatile scalar is read by __imag. In C++, it is not.
11580       Input = DefaultLvalueConversion(Input.get());
11581     }
11582     break;
11583   case UO_Extension:
11584   case UO_Coawait:
11585     resultType = Input.get()->getType();
11586     VK = Input.get()->getValueKind();
11587     OK = Input.get()->getObjectKind();
11588     break;
11589   }
11590   if (resultType.isNull() || Input.isInvalid())
11591     return ExprError();
11592
11593   // Check for array bounds violations in the operand of the UnaryOperator,
11594   // except for the '*' and '&' operators that have to be handled specially
11595   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11596   // that are explicitly defined as valid by the standard).
11597   if (Opc != UO_AddrOf && Opc != UO_Deref)
11598     CheckArrayAccess(Input.get());
11599
11600   return new (Context)
11601       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11602 }
11603
11604 /// \brief Determine whether the given expression is a qualified member
11605 /// access expression, of a form that could be turned into a pointer to member
11606 /// with the address-of operator.
11607 static bool isQualifiedMemberAccess(Expr *E) {
11608   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11609     if (!DRE->getQualifier())
11610       return false;
11611     
11612     ValueDecl *VD = DRE->getDecl();
11613     if (!VD->isCXXClassMember())
11614       return false;
11615     
11616     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11617       return true;
11618     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11619       return Method->isInstance();
11620       
11621     return false;
11622   }
11623   
11624   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11625     if (!ULE->getQualifier())
11626       return false;
11627     
11628     for (NamedDecl *D : ULE->decls()) {
11629       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11630         if (Method->isInstance())
11631           return true;
11632       } else {
11633         // Overload set does not contain methods.
11634         break;
11635       }
11636     }
11637     
11638     return false;
11639   }
11640   
11641   return false;
11642 }
11643
11644 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11645                               UnaryOperatorKind Opc, Expr *Input) {
11646   // First things first: handle placeholders so that the
11647   // overloaded-operator check considers the right type.
11648   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11649     // Increment and decrement of pseudo-object references.
11650     if (pty->getKind() == BuiltinType::PseudoObject &&
11651         UnaryOperator::isIncrementDecrementOp(Opc))
11652       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11653
11654     // extension is always a builtin operator.
11655     if (Opc == UO_Extension)
11656       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11657
11658     // & gets special logic for several kinds of placeholder.
11659     // The builtin code knows what to do.
11660     if (Opc == UO_AddrOf &&
11661         (pty->getKind() == BuiltinType::Overload ||
11662          pty->getKind() == BuiltinType::UnknownAny ||
11663          pty->getKind() == BuiltinType::BoundMember))
11664       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11665
11666     // Anything else needs to be handled now.
11667     ExprResult Result = CheckPlaceholderExpr(Input);
11668     if (Result.isInvalid()) return ExprError();
11669     Input = Result.get();
11670   }
11671
11672   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11673       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11674       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11675     // Find all of the overloaded operators visible from this
11676     // point. We perform both an operator-name lookup from the local
11677     // scope and an argument-dependent lookup based on the types of
11678     // the arguments.
11679     UnresolvedSet<16> Functions;
11680     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11681     if (S && OverOp != OO_None)
11682       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11683                                    Functions);
11684
11685     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11686   }
11687
11688   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11689 }
11690
11691 // Unary Operators.  'Tok' is the token for the operator.
11692 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11693                               tok::TokenKind Op, Expr *Input) {
11694   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11695 }
11696
11697 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11698 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11699                                 LabelDecl *TheDecl) {
11700   TheDecl->markUsed(Context);
11701   // Create the AST node.  The address of a label always has type 'void*'.
11702   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11703                                      Context.getPointerType(Context.VoidTy));
11704 }
11705
11706 /// Given the last statement in a statement-expression, check whether
11707 /// the result is a producing expression (like a call to an
11708 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11709 /// release out of the full-expression.  Otherwise, return null.
11710 /// Cannot fail.
11711 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11712   // Should always be wrapped with one of these.
11713   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11714   if (!cleanups) return nullptr;
11715
11716   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11717   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11718     return nullptr;
11719
11720   // Splice out the cast.  This shouldn't modify any interesting
11721   // features of the statement.
11722   Expr *producer = cast->getSubExpr();
11723   assert(producer->getType() == cast->getType());
11724   assert(producer->getValueKind() == cast->getValueKind());
11725   cleanups->setSubExpr(producer);
11726   return cleanups;
11727 }
11728
11729 void Sema::ActOnStartStmtExpr() {
11730   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11731 }
11732
11733 void Sema::ActOnStmtExprError() {
11734   // Note that function is also called by TreeTransform when leaving a
11735   // StmtExpr scope without rebuilding anything.
11736
11737   DiscardCleanupsInEvaluationContext();
11738   PopExpressionEvaluationContext();
11739 }
11740
11741 ExprResult
11742 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11743                     SourceLocation RPLoc) { // "({..})"
11744   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11745   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11746
11747   if (hasAnyUnrecoverableErrorsInThisFunction())
11748     DiscardCleanupsInEvaluationContext();
11749   assert(!Cleanup.exprNeedsCleanups() &&
11750          "cleanups within StmtExpr not correctly bound!");
11751   PopExpressionEvaluationContext();
11752
11753   // FIXME: there are a variety of strange constraints to enforce here, for
11754   // example, it is not possible to goto into a stmt expression apparently.
11755   // More semantic analysis is needed.
11756
11757   // If there are sub-stmts in the compound stmt, take the type of the last one
11758   // as the type of the stmtexpr.
11759   QualType Ty = Context.VoidTy;
11760   bool StmtExprMayBindToTemp = false;
11761   if (!Compound->body_empty()) {
11762     Stmt *LastStmt = Compound->body_back();
11763     LabelStmt *LastLabelStmt = nullptr;
11764     // If LastStmt is a label, skip down through into the body.
11765     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11766       LastLabelStmt = Label;
11767       LastStmt = Label->getSubStmt();
11768     }
11769
11770     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11771       // Do function/array conversion on the last expression, but not
11772       // lvalue-to-rvalue.  However, initialize an unqualified type.
11773       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11774       if (LastExpr.isInvalid())
11775         return ExprError();
11776       Ty = LastExpr.get()->getType().getUnqualifiedType();
11777
11778       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11779         // In ARC, if the final expression ends in a consume, splice
11780         // the consume out and bind it later.  In the alternate case
11781         // (when dealing with a retainable type), the result
11782         // initialization will create a produce.  In both cases the
11783         // result will be +1, and we'll need to balance that out with
11784         // a bind.
11785         if (Expr *rebuiltLastStmt
11786               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11787           LastExpr = rebuiltLastStmt;
11788         } else {
11789           LastExpr = PerformCopyInitialization(
11790                             InitializedEntity::InitializeResult(LPLoc, 
11791                                                                 Ty,
11792                                                                 false),
11793                                                    SourceLocation(),
11794                                                LastExpr);
11795         }
11796
11797         if (LastExpr.isInvalid())
11798           return ExprError();
11799         if (LastExpr.get() != nullptr) {
11800           if (!LastLabelStmt)
11801             Compound->setLastStmt(LastExpr.get());
11802           else
11803             LastLabelStmt->setSubStmt(LastExpr.get());
11804           StmtExprMayBindToTemp = true;
11805         }
11806       }
11807     }
11808   }
11809
11810   // FIXME: Check that expression type is complete/non-abstract; statement
11811   // expressions are not lvalues.
11812   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11813   if (StmtExprMayBindToTemp)
11814     return MaybeBindToTemporary(ResStmtExpr);
11815   return ResStmtExpr;
11816 }
11817
11818 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11819                                       TypeSourceInfo *TInfo,
11820                                       ArrayRef<OffsetOfComponent> Components,
11821                                       SourceLocation RParenLoc) {
11822   QualType ArgTy = TInfo->getType();
11823   bool Dependent = ArgTy->isDependentType();
11824   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11825   
11826   // We must have at least one component that refers to the type, and the first
11827   // one is known to be a field designator.  Verify that the ArgTy represents
11828   // a struct/union/class.
11829   if (!Dependent && !ArgTy->isRecordType())
11830     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
11831                        << ArgTy << TypeRange);
11832   
11833   // Type must be complete per C99 7.17p3 because a declaring a variable
11834   // with an incomplete type would be ill-formed.
11835   if (!Dependent 
11836       && RequireCompleteType(BuiltinLoc, ArgTy,
11837                              diag::err_offsetof_incomplete_type, TypeRange))
11838     return ExprError();
11839   
11840   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11841   // GCC extension, diagnose them.
11842   // FIXME: This diagnostic isn't actually visible because the location is in
11843   // a system header!
11844   if (Components.size() != 1)
11845     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11846       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11847   
11848   bool DidWarnAboutNonPOD = false;
11849   QualType CurrentType = ArgTy;
11850   SmallVector<OffsetOfNode, 4> Comps;
11851   SmallVector<Expr*, 4> Exprs;
11852   for (const OffsetOfComponent &OC : Components) {
11853     if (OC.isBrackets) {
11854       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11855       if (!CurrentType->isDependentType()) {
11856         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11857         if(!AT)
11858           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11859                            << CurrentType);
11860         CurrentType = AT->getElementType();
11861       } else
11862         CurrentType = Context.DependentTy;
11863       
11864       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11865       if (IdxRval.isInvalid())
11866         return ExprError();
11867       Expr *Idx = IdxRval.get();
11868
11869       // The expression must be an integral expression.
11870       // FIXME: An integral constant expression?
11871       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11872           !Idx->getType()->isIntegerType())
11873         return ExprError(Diag(Idx->getLocStart(),
11874                               diag::err_typecheck_subscript_not_integer)
11875                          << Idx->getSourceRange());
11876
11877       // Record this array index.
11878       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11879       Exprs.push_back(Idx);
11880       continue;
11881     }
11882     
11883     // Offset of a field.
11884     if (CurrentType->isDependentType()) {
11885       // We have the offset of a field, but we can't look into the dependent
11886       // type. Just record the identifier of the field.
11887       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11888       CurrentType = Context.DependentTy;
11889       continue;
11890     }
11891     
11892     // We need to have a complete type to look into.
11893     if (RequireCompleteType(OC.LocStart, CurrentType,
11894                             diag::err_offsetof_incomplete_type))
11895       return ExprError();
11896     
11897     // Look for the designated field.
11898     const RecordType *RC = CurrentType->getAs<RecordType>();
11899     if (!RC) 
11900       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11901                        << CurrentType);
11902     RecordDecl *RD = RC->getDecl();
11903     
11904     // C++ [lib.support.types]p5:
11905     //   The macro offsetof accepts a restricted set of type arguments in this
11906     //   International Standard. type shall be a POD structure or a POD union
11907     //   (clause 9).
11908     // C++11 [support.types]p4:
11909     //   If type is not a standard-layout class (Clause 9), the results are
11910     //   undefined.
11911     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11912       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11913       unsigned DiagID =
11914         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11915                             : diag::ext_offsetof_non_pod_type;
11916
11917       if (!IsSafe && !DidWarnAboutNonPOD &&
11918           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11919                               PDiag(DiagID)
11920                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11921                               << CurrentType))
11922         DidWarnAboutNonPOD = true;
11923     }
11924     
11925     // Look for the field.
11926     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11927     LookupQualifiedName(R, RD);
11928     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11929     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11930     if (!MemberDecl) {
11931       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11932         MemberDecl = IndirectMemberDecl->getAnonField();
11933     }
11934
11935     if (!MemberDecl)
11936       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11937                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
11938                                                               OC.LocEnd));
11939     
11940     // C99 7.17p3:
11941     //   (If the specified member is a bit-field, the behavior is undefined.)
11942     //
11943     // We diagnose this as an error.
11944     if (MemberDecl->isBitField()) {
11945       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11946         << MemberDecl->getDeclName()
11947         << SourceRange(BuiltinLoc, RParenLoc);
11948       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11949       return ExprError();
11950     }
11951
11952     RecordDecl *Parent = MemberDecl->getParent();
11953     if (IndirectMemberDecl)
11954       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11955
11956     // If the member was found in a base class, introduce OffsetOfNodes for
11957     // the base class indirections.
11958     CXXBasePaths Paths;
11959     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11960                       Paths)) {
11961       if (Paths.getDetectedVirtual()) {
11962         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11963           << MemberDecl->getDeclName()
11964           << SourceRange(BuiltinLoc, RParenLoc);
11965         return ExprError();
11966       }
11967
11968       CXXBasePath &Path = Paths.front();
11969       for (const CXXBasePathElement &B : Path)
11970         Comps.push_back(OffsetOfNode(B.Base));
11971     }
11972
11973     if (IndirectMemberDecl) {
11974       for (auto *FI : IndirectMemberDecl->chain()) {
11975         assert(isa<FieldDecl>(FI));
11976         Comps.push_back(OffsetOfNode(OC.LocStart,
11977                                      cast<FieldDecl>(FI), OC.LocEnd));
11978       }
11979     } else
11980       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11981
11982     CurrentType = MemberDecl->getType().getNonReferenceType(); 
11983   }
11984   
11985   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11986                               Comps, Exprs, RParenLoc);
11987 }
11988
11989 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11990                                       SourceLocation BuiltinLoc,
11991                                       SourceLocation TypeLoc,
11992                                       ParsedType ParsedArgTy,
11993                                       ArrayRef<OffsetOfComponent> Components,
11994                                       SourceLocation RParenLoc) {
11995   
11996   TypeSourceInfo *ArgTInfo;
11997   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11998   if (ArgTy.isNull())
11999     return ExprError();
12000
12001   if (!ArgTInfo)
12002     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12003
12004   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12005 }
12006
12007
12008 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12009                                  Expr *CondExpr,
12010                                  Expr *LHSExpr, Expr *RHSExpr,
12011                                  SourceLocation RPLoc) {
12012   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12013
12014   ExprValueKind VK = VK_RValue;
12015   ExprObjectKind OK = OK_Ordinary;
12016   QualType resType;
12017   bool ValueDependent = false;
12018   bool CondIsTrue = false;
12019   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12020     resType = Context.DependentTy;
12021     ValueDependent = true;
12022   } else {
12023     // The conditional expression is required to be a constant expression.
12024     llvm::APSInt condEval(32);
12025     ExprResult CondICE
12026       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12027           diag::err_typecheck_choose_expr_requires_constant, false);
12028     if (CondICE.isInvalid())
12029       return ExprError();
12030     CondExpr = CondICE.get();
12031     CondIsTrue = condEval.getZExtValue();
12032
12033     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12034     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12035
12036     resType = ActiveExpr->getType();
12037     ValueDependent = ActiveExpr->isValueDependent();
12038     VK = ActiveExpr->getValueKind();
12039     OK = ActiveExpr->getObjectKind();
12040   }
12041
12042   return new (Context)
12043       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12044                  CondIsTrue, resType->isDependentType(), ValueDependent);
12045 }
12046
12047 //===----------------------------------------------------------------------===//
12048 // Clang Extensions.
12049 //===----------------------------------------------------------------------===//
12050
12051 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12052 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12053   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12054
12055   if (LangOpts.CPlusPlus) {
12056     Decl *ManglingContextDecl;
12057     if (MangleNumberingContext *MCtx =
12058             getCurrentMangleNumberContext(Block->getDeclContext(),
12059                                           ManglingContextDecl)) {
12060       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12061       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12062     }
12063   }
12064
12065   PushBlockScope(CurScope, Block);
12066   CurContext->addDecl(Block);
12067   if (CurScope)
12068     PushDeclContext(CurScope, Block);
12069   else
12070     CurContext = Block;
12071
12072   getCurBlock()->HasImplicitReturnType = true;
12073
12074   // Enter a new evaluation context to insulate the block from any
12075   // cleanups from the enclosing full-expression.
12076   PushExpressionEvaluationContext(PotentiallyEvaluated);  
12077 }
12078
12079 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12080                                Scope *CurScope) {
12081   assert(ParamInfo.getIdentifier() == nullptr &&
12082          "block-id should have no identifier!");
12083   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12084   BlockScopeInfo *CurBlock = getCurBlock();
12085
12086   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12087   QualType T = Sig->getType();
12088
12089   // FIXME: We should allow unexpanded parameter packs here, but that would,
12090   // in turn, make the block expression contain unexpanded parameter packs.
12091   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12092     // Drop the parameters.
12093     FunctionProtoType::ExtProtoInfo EPI;
12094     EPI.HasTrailingReturn = false;
12095     EPI.TypeQuals |= DeclSpec::TQ_const;
12096     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12097     Sig = Context.getTrivialTypeSourceInfo(T);
12098   }
12099   
12100   // GetTypeForDeclarator always produces a function type for a block
12101   // literal signature.  Furthermore, it is always a FunctionProtoType
12102   // unless the function was written with a typedef.
12103   assert(T->isFunctionType() &&
12104          "GetTypeForDeclarator made a non-function block signature");
12105
12106   // Look for an explicit signature in that function type.
12107   FunctionProtoTypeLoc ExplicitSignature;
12108
12109   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12110   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12111
12112     // Check whether that explicit signature was synthesized by
12113     // GetTypeForDeclarator.  If so, don't save that as part of the
12114     // written signature.
12115     if (ExplicitSignature.getLocalRangeBegin() ==
12116         ExplicitSignature.getLocalRangeEnd()) {
12117       // This would be much cheaper if we stored TypeLocs instead of
12118       // TypeSourceInfos.
12119       TypeLoc Result = ExplicitSignature.getReturnLoc();
12120       unsigned Size = Result.getFullDataSize();
12121       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12122       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12123
12124       ExplicitSignature = FunctionProtoTypeLoc();
12125     }
12126   }
12127
12128   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12129   CurBlock->FunctionType = T;
12130
12131   const FunctionType *Fn = T->getAs<FunctionType>();
12132   QualType RetTy = Fn->getReturnType();
12133   bool isVariadic =
12134     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12135
12136   CurBlock->TheDecl->setIsVariadic(isVariadic);
12137
12138   // Context.DependentTy is used as a placeholder for a missing block
12139   // return type.  TODO:  what should we do with declarators like:
12140   //   ^ * { ... }
12141   // If the answer is "apply template argument deduction"....
12142   if (RetTy != Context.DependentTy) {
12143     CurBlock->ReturnType = RetTy;
12144     CurBlock->TheDecl->setBlockMissingReturnType(false);
12145     CurBlock->HasImplicitReturnType = false;
12146   }
12147
12148   // Push block parameters from the declarator if we had them.
12149   SmallVector<ParmVarDecl*, 8> Params;
12150   if (ExplicitSignature) {
12151     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12152       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12153       if (Param->getIdentifier() == nullptr &&
12154           !Param->isImplicit() &&
12155           !Param->isInvalidDecl() &&
12156           !getLangOpts().CPlusPlus)
12157         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12158       Params.push_back(Param);
12159     }
12160
12161   // Fake up parameter variables if we have a typedef, like
12162   //   ^ fntype { ... }
12163   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12164     for (const auto &I : Fn->param_types()) {
12165       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12166           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12167       Params.push_back(Param);
12168     }
12169   }
12170
12171   // Set the parameters on the block decl.
12172   if (!Params.empty()) {
12173     CurBlock->TheDecl->setParams(Params);
12174     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12175                              /*CheckParameterNames=*/false);
12176   }
12177   
12178   // Finally we can process decl attributes.
12179   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12180
12181   // Put the parameter variables in scope.
12182   for (auto AI : CurBlock->TheDecl->parameters()) {
12183     AI->setOwningFunction(CurBlock->TheDecl);
12184
12185     // If this has an identifier, add it to the scope stack.
12186     if (AI->getIdentifier()) {
12187       CheckShadow(CurBlock->TheScope, AI);
12188
12189       PushOnScopeChains(AI, CurBlock->TheScope);
12190     }
12191   }
12192 }
12193
12194 /// ActOnBlockError - If there is an error parsing a block, this callback
12195 /// is invoked to pop the information about the block from the action impl.
12196 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12197   // Leave the expression-evaluation context.
12198   DiscardCleanupsInEvaluationContext();
12199   PopExpressionEvaluationContext();
12200
12201   // Pop off CurBlock, handle nested blocks.
12202   PopDeclContext();
12203   PopFunctionScopeInfo();
12204 }
12205
12206 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12207 /// literal was successfully completed.  ^(int x){...}
12208 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12209                                     Stmt *Body, Scope *CurScope) {
12210   // If blocks are disabled, emit an error.
12211   if (!LangOpts.Blocks)
12212     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12213
12214   // Leave the expression-evaluation context.
12215   if (hasAnyUnrecoverableErrorsInThisFunction())
12216     DiscardCleanupsInEvaluationContext();
12217   assert(!Cleanup.exprNeedsCleanups() &&
12218          "cleanups within block not correctly bound!");
12219   PopExpressionEvaluationContext();
12220
12221   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12222
12223   if (BSI->HasImplicitReturnType)
12224     deduceClosureReturnType(*BSI);
12225
12226   PopDeclContext();
12227
12228   QualType RetTy = Context.VoidTy;
12229   if (!BSI->ReturnType.isNull())
12230     RetTy = BSI->ReturnType;
12231
12232   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12233   QualType BlockTy;
12234
12235   // Set the captured variables on the block.
12236   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12237   SmallVector<BlockDecl::Capture, 4> Captures;
12238   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12239     if (Cap.isThisCapture())
12240       continue;
12241     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12242                               Cap.isNested(), Cap.getInitExpr());
12243     Captures.push_back(NewCap);
12244   }
12245   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12246
12247   // If the user wrote a function type in some form, try to use that.
12248   if (!BSI->FunctionType.isNull()) {
12249     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12250
12251     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12252     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12253     
12254     // Turn protoless block types into nullary block types.
12255     if (isa<FunctionNoProtoType>(FTy)) {
12256       FunctionProtoType::ExtProtoInfo EPI;
12257       EPI.ExtInfo = Ext;
12258       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12259
12260     // Otherwise, if we don't need to change anything about the function type,
12261     // preserve its sugar structure.
12262     } else if (FTy->getReturnType() == RetTy &&
12263                (!NoReturn || FTy->getNoReturnAttr())) {
12264       BlockTy = BSI->FunctionType;
12265
12266     // Otherwise, make the minimal modifications to the function type.
12267     } else {
12268       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12269       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12270       EPI.TypeQuals = 0; // FIXME: silently?
12271       EPI.ExtInfo = Ext;
12272       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12273     }
12274
12275   // If we don't have a function type, just build one from nothing.
12276   } else {
12277     FunctionProtoType::ExtProtoInfo EPI;
12278     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12279     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12280   }
12281
12282   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12283   BlockTy = Context.getBlockPointerType(BlockTy);
12284
12285   // If needed, diagnose invalid gotos and switches in the block.
12286   if (getCurFunction()->NeedsScopeChecking() &&
12287       !PP.isCodeCompletionEnabled())
12288     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12289
12290   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12291
12292   // Try to apply the named return value optimization. We have to check again
12293   // if we can do this, though, because blocks keep return statements around
12294   // to deduce an implicit return type.
12295   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12296       !BSI->TheDecl->isDependentContext())
12297     computeNRVO(Body, BSI);
12298   
12299   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12300   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12301   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12302
12303   // If the block isn't obviously global, i.e. it captures anything at
12304   // all, then we need to do a few things in the surrounding context:
12305   if (Result->getBlockDecl()->hasCaptures()) {
12306     // First, this expression has a new cleanup object.
12307     ExprCleanupObjects.push_back(Result->getBlockDecl());
12308     Cleanup.setExprNeedsCleanups(true);
12309
12310     // It also gets a branch-protected scope if any of the captured
12311     // variables needs destruction.
12312     for (const auto &CI : Result->getBlockDecl()->captures()) {
12313       const VarDecl *var = CI.getVariable();
12314       if (var->getType().isDestructedType() != QualType::DK_none) {
12315         getCurFunction()->setHasBranchProtectedScope();
12316         break;
12317       }
12318     }
12319   }
12320
12321   return Result;
12322 }
12323
12324 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12325                             SourceLocation RPLoc) {
12326   TypeSourceInfo *TInfo;
12327   GetTypeFromParser(Ty, &TInfo);
12328   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12329 }
12330
12331 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12332                                 Expr *E, TypeSourceInfo *TInfo,
12333                                 SourceLocation RPLoc) {
12334   Expr *OrigExpr = E;
12335   bool IsMS = false;
12336
12337   // CUDA device code does not support varargs.
12338   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12339     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12340       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12341       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12342         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12343     }
12344   }
12345
12346   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12347   // as Microsoft ABI on an actual Microsoft platform, where
12348   // __builtin_ms_va_list and __builtin_va_list are the same.)
12349   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12350       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12351     QualType MSVaListType = Context.getBuiltinMSVaListType();
12352     if (Context.hasSameType(MSVaListType, E->getType())) {
12353       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12354         return ExprError();
12355       IsMS = true;
12356     }
12357   }
12358
12359   // Get the va_list type
12360   QualType VaListType = Context.getBuiltinVaListType();
12361   if (!IsMS) {
12362     if (VaListType->isArrayType()) {
12363       // Deal with implicit array decay; for example, on x86-64,
12364       // va_list is an array, but it's supposed to decay to
12365       // a pointer for va_arg.
12366       VaListType = Context.getArrayDecayedType(VaListType);
12367       // Make sure the input expression also decays appropriately.
12368       ExprResult Result = UsualUnaryConversions(E);
12369       if (Result.isInvalid())
12370         return ExprError();
12371       E = Result.get();
12372     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12373       // If va_list is a record type and we are compiling in C++ mode,
12374       // check the argument using reference binding.
12375       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12376           Context, Context.getLValueReferenceType(VaListType), false);
12377       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12378       if (Init.isInvalid())
12379         return ExprError();
12380       E = Init.getAs<Expr>();
12381     } else {
12382       // Otherwise, the va_list argument must be an l-value because
12383       // it is modified by va_arg.
12384       if (!E->isTypeDependent() &&
12385           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12386         return ExprError();
12387     }
12388   }
12389
12390   if (!IsMS && !E->isTypeDependent() &&
12391       !Context.hasSameType(VaListType, E->getType()))
12392     return ExprError(Diag(E->getLocStart(),
12393                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12394       << OrigExpr->getType() << E->getSourceRange());
12395
12396   if (!TInfo->getType()->isDependentType()) {
12397     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12398                             diag::err_second_parameter_to_va_arg_incomplete,
12399                             TInfo->getTypeLoc()))
12400       return ExprError();
12401
12402     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12403                                TInfo->getType(),
12404                                diag::err_second_parameter_to_va_arg_abstract,
12405                                TInfo->getTypeLoc()))
12406       return ExprError();
12407
12408     if (!TInfo->getType().isPODType(Context)) {
12409       Diag(TInfo->getTypeLoc().getBeginLoc(),
12410            TInfo->getType()->isObjCLifetimeType()
12411              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12412              : diag::warn_second_parameter_to_va_arg_not_pod)
12413         << TInfo->getType()
12414         << TInfo->getTypeLoc().getSourceRange();
12415     }
12416
12417     // Check for va_arg where arguments of the given type will be promoted
12418     // (i.e. this va_arg is guaranteed to have undefined behavior).
12419     QualType PromoteType;
12420     if (TInfo->getType()->isPromotableIntegerType()) {
12421       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12422       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12423         PromoteType = QualType();
12424     }
12425     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12426       PromoteType = Context.DoubleTy;
12427     if (!PromoteType.isNull())
12428       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12429                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12430                           << TInfo->getType()
12431                           << PromoteType
12432                           << TInfo->getTypeLoc().getSourceRange());
12433   }
12434
12435   QualType T = TInfo->getType().getNonLValueExprType(Context);
12436   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12437 }
12438
12439 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12440   // The type of __null will be int or long, depending on the size of
12441   // pointers on the target.
12442   QualType Ty;
12443   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12444   if (pw == Context.getTargetInfo().getIntWidth())
12445     Ty = Context.IntTy;
12446   else if (pw == Context.getTargetInfo().getLongWidth())
12447     Ty = Context.LongTy;
12448   else if (pw == Context.getTargetInfo().getLongLongWidth())
12449     Ty = Context.LongLongTy;
12450   else {
12451     llvm_unreachable("I don't know size of pointer!");
12452   }
12453
12454   return new (Context) GNUNullExpr(Ty, TokenLoc);
12455 }
12456
12457 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12458                                               bool Diagnose) {
12459   if (!getLangOpts().ObjC1)
12460     return false;
12461
12462   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12463   if (!PT)
12464     return false;
12465
12466   if (!PT->isObjCIdType()) {
12467     // Check if the destination is the 'NSString' interface.
12468     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12469     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12470       return false;
12471   }
12472   
12473   // Ignore any parens, implicit casts (should only be
12474   // array-to-pointer decays), and not-so-opaque values.  The last is
12475   // important for making this trigger for property assignments.
12476   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12477   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12478     if (OV->getSourceExpr())
12479       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12480
12481   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12482   if (!SL || !SL->isAscii())
12483     return false;
12484   if (Diagnose) {
12485     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12486       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12487     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12488   }
12489   return true;
12490 }
12491
12492 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12493                                               const Expr *SrcExpr) {
12494   if (!DstType->isFunctionPointerType() ||
12495       !SrcExpr->getType()->isFunctionType())
12496     return false;
12497
12498   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12499   if (!DRE)
12500     return false;
12501
12502   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12503   if (!FD)
12504     return false;
12505
12506   return !S.checkAddressOfFunctionIsAvailable(FD,
12507                                               /*Complain=*/true,
12508                                               SrcExpr->getLocStart());
12509 }
12510
12511 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12512                                     SourceLocation Loc,
12513                                     QualType DstType, QualType SrcType,
12514                                     Expr *SrcExpr, AssignmentAction Action,
12515                                     bool *Complained) {
12516   if (Complained)
12517     *Complained = false;
12518
12519   // Decode the result (notice that AST's are still created for extensions).
12520   bool CheckInferredResultType = false;
12521   bool isInvalid = false;
12522   unsigned DiagKind = 0;
12523   FixItHint Hint;
12524   ConversionFixItGenerator ConvHints;
12525   bool MayHaveConvFixit = false;
12526   bool MayHaveFunctionDiff = false;
12527   const ObjCInterfaceDecl *IFace = nullptr;
12528   const ObjCProtocolDecl *PDecl = nullptr;
12529
12530   switch (ConvTy) {
12531   case Compatible:
12532       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12533       return false;
12534
12535   case PointerToInt:
12536     DiagKind = diag::ext_typecheck_convert_pointer_int;
12537     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12538     MayHaveConvFixit = true;
12539     break;
12540   case IntToPointer:
12541     DiagKind = diag::ext_typecheck_convert_int_pointer;
12542     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12543     MayHaveConvFixit = true;
12544     break;
12545   case IncompatiblePointer:
12546     if (Action == AA_Passing_CFAudited)
12547       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12548     else if (SrcType->isFunctionPointerType() &&
12549              DstType->isFunctionPointerType())
12550       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12551     else
12552       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12553
12554     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12555       SrcType->isObjCObjectPointerType();
12556     if (Hint.isNull() && !CheckInferredResultType) {
12557       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12558     }
12559     else if (CheckInferredResultType) {
12560       SrcType = SrcType.getUnqualifiedType();
12561       DstType = DstType.getUnqualifiedType();
12562     }
12563     MayHaveConvFixit = true;
12564     break;
12565   case IncompatiblePointerSign:
12566     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12567     break;
12568   case FunctionVoidPointer:
12569     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12570     break;
12571   case IncompatiblePointerDiscardsQualifiers: {
12572     // Perform array-to-pointer decay if necessary.
12573     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12574
12575     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12576     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12577     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12578       DiagKind = diag::err_typecheck_incompatible_address_space;
12579       break;
12580
12581
12582     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12583       DiagKind = diag::err_typecheck_incompatible_ownership;
12584       break;
12585     }
12586
12587     llvm_unreachable("unknown error case for discarding qualifiers!");
12588     // fallthrough
12589   }
12590   case CompatiblePointerDiscardsQualifiers:
12591     // If the qualifiers lost were because we were applying the
12592     // (deprecated) C++ conversion from a string literal to a char*
12593     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12594     // Ideally, this check would be performed in
12595     // checkPointerTypesForAssignment. However, that would require a
12596     // bit of refactoring (so that the second argument is an
12597     // expression, rather than a type), which should be done as part
12598     // of a larger effort to fix checkPointerTypesForAssignment for
12599     // C++ semantics.
12600     if (getLangOpts().CPlusPlus &&
12601         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12602       return false;
12603     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12604     break;
12605   case IncompatibleNestedPointerQualifiers:
12606     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12607     break;
12608   case IntToBlockPointer:
12609     DiagKind = diag::err_int_to_block_pointer;
12610     break;
12611   case IncompatibleBlockPointer:
12612     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12613     break;
12614   case IncompatibleObjCQualifiedId: {
12615     if (SrcType->isObjCQualifiedIdType()) {
12616       const ObjCObjectPointerType *srcOPT =
12617                 SrcType->getAs<ObjCObjectPointerType>();
12618       for (auto *srcProto : srcOPT->quals()) {
12619         PDecl = srcProto;
12620         break;
12621       }
12622       if (const ObjCInterfaceType *IFaceT =
12623             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12624         IFace = IFaceT->getDecl();
12625     }
12626     else if (DstType->isObjCQualifiedIdType()) {
12627       const ObjCObjectPointerType *dstOPT =
12628         DstType->getAs<ObjCObjectPointerType>();
12629       for (auto *dstProto : dstOPT->quals()) {
12630         PDecl = dstProto;
12631         break;
12632       }
12633       if (const ObjCInterfaceType *IFaceT =
12634             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12635         IFace = IFaceT->getDecl();
12636     }
12637     DiagKind = diag::warn_incompatible_qualified_id;
12638     break;
12639   }
12640   case IncompatibleVectors:
12641     DiagKind = diag::warn_incompatible_vectors;
12642     break;
12643   case IncompatibleObjCWeakRef:
12644     DiagKind = diag::err_arc_weak_unavailable_assign;
12645     break;
12646   case Incompatible:
12647     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12648       if (Complained)
12649         *Complained = true;
12650       return true;
12651     }
12652
12653     DiagKind = diag::err_typecheck_convert_incompatible;
12654     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12655     MayHaveConvFixit = true;
12656     isInvalid = true;
12657     MayHaveFunctionDiff = true;
12658     break;
12659   }
12660
12661   QualType FirstType, SecondType;
12662   switch (Action) {
12663   case AA_Assigning:
12664   case AA_Initializing:
12665     // The destination type comes first.
12666     FirstType = DstType;
12667     SecondType = SrcType;
12668     break;
12669
12670   case AA_Returning:
12671   case AA_Passing:
12672   case AA_Passing_CFAudited:
12673   case AA_Converting:
12674   case AA_Sending:
12675   case AA_Casting:
12676     // The source type comes first.
12677     FirstType = SrcType;
12678     SecondType = DstType;
12679     break;
12680   }
12681
12682   PartialDiagnostic FDiag = PDiag(DiagKind);
12683   if (Action == AA_Passing_CFAudited)
12684     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12685   else
12686     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12687
12688   // If we can fix the conversion, suggest the FixIts.
12689   assert(ConvHints.isNull() || Hint.isNull());
12690   if (!ConvHints.isNull()) {
12691     for (FixItHint &H : ConvHints.Hints)
12692       FDiag << H;
12693   } else {
12694     FDiag << Hint;
12695   }
12696   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12697
12698   if (MayHaveFunctionDiff)
12699     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12700
12701   Diag(Loc, FDiag);
12702   if (DiagKind == diag::warn_incompatible_qualified_id &&
12703       PDecl && IFace && !IFace->hasDefinition())
12704       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12705         << IFace->getName() << PDecl->getName();
12706     
12707   if (SecondType == Context.OverloadTy)
12708     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12709                               FirstType, /*TakingAddress=*/true);
12710
12711   if (CheckInferredResultType)
12712     EmitRelatedResultTypeNote(SrcExpr);
12713
12714   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12715     EmitRelatedResultTypeNoteForReturn(DstType);
12716   
12717   if (Complained)
12718     *Complained = true;
12719   return isInvalid;
12720 }
12721
12722 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12723                                                  llvm::APSInt *Result) {
12724   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12725   public:
12726     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12727       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12728     }
12729   } Diagnoser;
12730   
12731   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12732 }
12733
12734 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12735                                                  llvm::APSInt *Result,
12736                                                  unsigned DiagID,
12737                                                  bool AllowFold) {
12738   class IDDiagnoser : public VerifyICEDiagnoser {
12739     unsigned DiagID;
12740     
12741   public:
12742     IDDiagnoser(unsigned DiagID)
12743       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12744     
12745     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12746       S.Diag(Loc, DiagID) << SR;
12747     }
12748   } Diagnoser(DiagID);
12749   
12750   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12751 }
12752
12753 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12754                                             SourceRange SR) {
12755   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12756 }
12757
12758 ExprResult
12759 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12760                                       VerifyICEDiagnoser &Diagnoser,
12761                                       bool AllowFold) {
12762   SourceLocation DiagLoc = E->getLocStart();
12763
12764   if (getLangOpts().CPlusPlus11) {
12765     // C++11 [expr.const]p5:
12766     //   If an expression of literal class type is used in a context where an
12767     //   integral constant expression is required, then that class type shall
12768     //   have a single non-explicit conversion function to an integral or
12769     //   unscoped enumeration type
12770     ExprResult Converted;
12771     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12772     public:
12773       CXX11ConvertDiagnoser(bool Silent)
12774           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12775                                 Silent, true) {}
12776
12777       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12778                                            QualType T) override {
12779         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12780       }
12781
12782       SemaDiagnosticBuilder diagnoseIncomplete(
12783           Sema &S, SourceLocation Loc, QualType T) override {
12784         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12785       }
12786
12787       SemaDiagnosticBuilder diagnoseExplicitConv(
12788           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12789         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12790       }
12791
12792       SemaDiagnosticBuilder noteExplicitConv(
12793           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12794         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12795                  << ConvTy->isEnumeralType() << ConvTy;
12796       }
12797
12798       SemaDiagnosticBuilder diagnoseAmbiguous(
12799           Sema &S, SourceLocation Loc, QualType T) override {
12800         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12801       }
12802
12803       SemaDiagnosticBuilder noteAmbiguous(
12804           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12805         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12806                  << ConvTy->isEnumeralType() << ConvTy;
12807       }
12808
12809       SemaDiagnosticBuilder diagnoseConversion(
12810           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12811         llvm_unreachable("conversion functions are permitted");
12812       }
12813     } ConvertDiagnoser(Diagnoser.Suppress);
12814
12815     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12816                                                     ConvertDiagnoser);
12817     if (Converted.isInvalid())
12818       return Converted;
12819     E = Converted.get();
12820     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12821       return ExprError();
12822   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12823     // An ICE must be of integral or unscoped enumeration type.
12824     if (!Diagnoser.Suppress)
12825       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12826     return ExprError();
12827   }
12828
12829   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12830   // in the non-ICE case.
12831   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12832     if (Result)
12833       *Result = E->EvaluateKnownConstInt(Context);
12834     return E;
12835   }
12836
12837   Expr::EvalResult EvalResult;
12838   SmallVector<PartialDiagnosticAt, 8> Notes;
12839   EvalResult.Diag = &Notes;
12840
12841   // Try to evaluate the expression, and produce diagnostics explaining why it's
12842   // not a constant expression as a side-effect.
12843   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12844                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12845
12846   // In C++11, we can rely on diagnostics being produced for any expression
12847   // which is not a constant expression. If no diagnostics were produced, then
12848   // this is a constant expression.
12849   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12850     if (Result)
12851       *Result = EvalResult.Val.getInt();
12852     return E;
12853   }
12854
12855   // If our only note is the usual "invalid subexpression" note, just point
12856   // the caret at its location rather than producing an essentially
12857   // redundant note.
12858   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12859         diag::note_invalid_subexpr_in_const_expr) {
12860     DiagLoc = Notes[0].first;
12861     Notes.clear();
12862   }
12863
12864   if (!Folded || !AllowFold) {
12865     if (!Diagnoser.Suppress) {
12866       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12867       for (const PartialDiagnosticAt &Note : Notes)
12868         Diag(Note.first, Note.second);
12869     }
12870
12871     return ExprError();
12872   }
12873
12874   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12875   for (const PartialDiagnosticAt &Note : Notes)
12876     Diag(Note.first, Note.second);
12877
12878   if (Result)
12879     *Result = EvalResult.Val.getInt();
12880   return E;
12881 }
12882
12883 namespace {
12884   // Handle the case where we conclude a expression which we speculatively
12885   // considered to be unevaluated is actually evaluated.
12886   class TransformToPE : public TreeTransform<TransformToPE> {
12887     typedef TreeTransform<TransformToPE> BaseTransform;
12888
12889   public:
12890     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12891
12892     // Make sure we redo semantic analysis
12893     bool AlwaysRebuild() { return true; }
12894
12895     // Make sure we handle LabelStmts correctly.
12896     // FIXME: This does the right thing, but maybe we need a more general
12897     // fix to TreeTransform?
12898     StmtResult TransformLabelStmt(LabelStmt *S) {
12899       S->getDecl()->setStmt(nullptr);
12900       return BaseTransform::TransformLabelStmt(S);
12901     }
12902
12903     // We need to special-case DeclRefExprs referring to FieldDecls which
12904     // are not part of a member pointer formation; normal TreeTransforming
12905     // doesn't catch this case because of the way we represent them in the AST.
12906     // FIXME: This is a bit ugly; is it really the best way to handle this
12907     // case?
12908     //
12909     // Error on DeclRefExprs referring to FieldDecls.
12910     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12911       if (isa<FieldDecl>(E->getDecl()) &&
12912           !SemaRef.isUnevaluatedContext())
12913         return SemaRef.Diag(E->getLocation(),
12914                             diag::err_invalid_non_static_member_use)
12915             << E->getDecl() << E->getSourceRange();
12916
12917       return BaseTransform::TransformDeclRefExpr(E);
12918     }
12919
12920     // Exception: filter out member pointer formation
12921     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12922       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12923         return E;
12924
12925       return BaseTransform::TransformUnaryOperator(E);
12926     }
12927
12928     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12929       // Lambdas never need to be transformed.
12930       return E;
12931     }
12932   };
12933 }
12934
12935 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12936   assert(isUnevaluatedContext() &&
12937          "Should only transform unevaluated expressions");
12938   ExprEvalContexts.back().Context =
12939       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12940   if (isUnevaluatedContext())
12941     return E;
12942   return TransformToPE(*this).TransformExpr(E);
12943 }
12944
12945 void
12946 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12947                                       Decl *LambdaContextDecl,
12948                                       bool IsDecltype) {
12949   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
12950                                 LambdaContextDecl, IsDecltype);
12951   Cleanup.reset();
12952   if (!MaybeODRUseExprs.empty())
12953     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12954 }
12955
12956 void
12957 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12958                                       ReuseLambdaContextDecl_t,
12959                                       bool IsDecltype) {
12960   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12961   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12962 }
12963
12964 void Sema::PopExpressionEvaluationContext() {
12965   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12966   unsigned NumTypos = Rec.NumTypos;
12967
12968   if (!Rec.Lambdas.empty()) {
12969     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12970       unsigned D;
12971       if (Rec.isUnevaluated()) {
12972         // C++11 [expr.prim.lambda]p2:
12973         //   A lambda-expression shall not appear in an unevaluated operand
12974         //   (Clause 5).
12975         D = diag::err_lambda_unevaluated_operand;
12976       } else {
12977         // C++1y [expr.const]p2:
12978         //   A conditional-expression e is a core constant expression unless the
12979         //   evaluation of e, following the rules of the abstract machine, would
12980         //   evaluate [...] a lambda-expression.
12981         D = diag::err_lambda_in_constant_expression;
12982       }
12983       for (const auto *L : Rec.Lambdas)
12984         Diag(L->getLocStart(), D);
12985     } else {
12986       // Mark the capture expressions odr-used. This was deferred
12987       // during lambda expression creation.
12988       for (auto *Lambda : Rec.Lambdas) {
12989         for (auto *C : Lambda->capture_inits())
12990           MarkDeclarationsReferencedInExpr(C);
12991       }
12992     }
12993   }
12994
12995   // When are coming out of an unevaluated context, clear out any
12996   // temporaries that we may have created as part of the evaluation of
12997   // the expression in that context: they aren't relevant because they
12998   // will never be constructed.
12999   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13000     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13001                              ExprCleanupObjects.end());
13002     Cleanup = Rec.ParentCleanup;
13003     CleanupVarDeclMarking();
13004     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13005   // Otherwise, merge the contexts together.
13006   } else {
13007     Cleanup.mergeFrom(Rec.ParentCleanup);
13008     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13009                             Rec.SavedMaybeODRUseExprs.end());
13010   }
13011
13012   // Pop the current expression evaluation context off the stack.
13013   ExprEvalContexts.pop_back();
13014
13015   if (!ExprEvalContexts.empty())
13016     ExprEvalContexts.back().NumTypos += NumTypos;
13017   else
13018     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13019                             "last ExpressionEvaluationContextRecord");
13020 }
13021
13022 void Sema::DiscardCleanupsInEvaluationContext() {
13023   ExprCleanupObjects.erase(
13024          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13025          ExprCleanupObjects.end());
13026   Cleanup.reset();
13027   MaybeODRUseExprs.clear();
13028 }
13029
13030 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13031   if (!E->getType()->isVariablyModifiedType())
13032     return E;
13033   return TransformToPotentiallyEvaluated(E);
13034 }
13035
13036 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
13037   // Do not mark anything as "used" within a dependent context; wait for
13038   // an instantiation.
13039   if (SemaRef.CurContext->isDependentContext())
13040     return false;
13041
13042   switch (SemaRef.ExprEvalContexts.back().Context) {
13043     case Sema::Unevaluated:
13044     case Sema::UnevaluatedAbstract:
13045       // We are in an expression that is not potentially evaluated; do nothing.
13046       // (Depending on how you read the standard, we actually do need to do
13047       // something here for null pointer constants, but the standard's
13048       // definition of a null pointer constant is completely crazy.)
13049       return false;
13050
13051     case Sema::DiscardedStatement:
13052       // These are technically a potentially evaluated but they have the effect
13053       // of suppressing use marking.
13054       return false;
13055
13056     case Sema::ConstantEvaluated:
13057     case Sema::PotentiallyEvaluated:
13058       // We are in a potentially evaluated expression (or a constant-expression
13059       // in C++03); we need to do implicit template instantiation, implicitly
13060       // define class members, and mark most declarations as used.
13061       return true;
13062
13063     case Sema::PotentiallyEvaluatedIfUsed:
13064       // Referenced declarations will only be used if the construct in the
13065       // containing expression is used.
13066       return false;
13067   }
13068   llvm_unreachable("Invalid context");
13069 }
13070
13071 /// \brief Mark a function referenced, and check whether it is odr-used
13072 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13073 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13074                                   bool MightBeOdrUse) {
13075   assert(Func && "No function?");
13076
13077   Func->setReferenced();
13078
13079   // C++11 [basic.def.odr]p3:
13080   //   A function whose name appears as a potentially-evaluated expression is
13081   //   odr-used if it is the unique lookup result or the selected member of a
13082   //   set of overloaded functions [...].
13083   //
13084   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13085   // can just check that here.
13086   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13087
13088   // Determine whether we require a function definition to exist, per
13089   // C++11 [temp.inst]p3:
13090   //   Unless a function template specialization has been explicitly
13091   //   instantiated or explicitly specialized, the function template
13092   //   specialization is implicitly instantiated when the specialization is
13093   //   referenced in a context that requires a function definition to exist.
13094   //
13095   // We consider constexpr function templates to be referenced in a context
13096   // that requires a definition to exist whenever they are referenced.
13097   //
13098   // FIXME: This instantiates constexpr functions too frequently. If this is
13099   // really an unevaluated context (and we're not just in the definition of a
13100   // function template or overload resolution or other cases which we
13101   // incorrectly consider to be unevaluated contexts), and we're not in a
13102   // subexpression which we actually need to evaluate (for instance, a
13103   // template argument, array bound or an expression in a braced-init-list),
13104   // we are not permitted to instantiate this constexpr function definition.
13105   //
13106   // FIXME: This also implicitly defines special members too frequently. They
13107   // are only supposed to be implicitly defined if they are odr-used, but they
13108   // are not odr-used from constant expressions in unevaluated contexts.
13109   // However, they cannot be referenced if they are deleted, and they are
13110   // deleted whenever the implicit definition of the special member would
13111   // fail (with very few exceptions).
13112   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13113   bool NeedDefinition =
13114       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13115                                          (MD && !MD->isUserProvided())));
13116
13117   // C++14 [temp.expl.spec]p6:
13118   //   If a template [...] is explicitly specialized then that specialization
13119   //   shall be declared before the first use of that specialization that would
13120   //   cause an implicit instantiation to take place, in every translation unit
13121   //   in which such a use occurs
13122   if (NeedDefinition &&
13123       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13124        Func->getMemberSpecializationInfo()))
13125     checkSpecializationVisibility(Loc, Func);
13126
13127   // If we don't need to mark the function as used, and we don't need to
13128   // try to provide a definition, there's nothing more to do.
13129   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13130       (!NeedDefinition || Func->getBody()))
13131     return;
13132
13133   // Note that this declaration has been used.
13134   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13135     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13136     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13137       if (Constructor->isDefaultConstructor()) {
13138         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13139           return;
13140         DefineImplicitDefaultConstructor(Loc, Constructor);
13141       } else if (Constructor->isCopyConstructor()) {
13142         DefineImplicitCopyConstructor(Loc, Constructor);
13143       } else if (Constructor->isMoveConstructor()) {
13144         DefineImplicitMoveConstructor(Loc, Constructor);
13145       }
13146     } else if (Constructor->getInheritedConstructor()) {
13147       DefineInheritingConstructor(Loc, Constructor);
13148     }
13149   } else if (CXXDestructorDecl *Destructor =
13150                  dyn_cast<CXXDestructorDecl>(Func)) {
13151     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13152     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13153       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13154         return;
13155       DefineImplicitDestructor(Loc, Destructor);
13156     }
13157     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13158       MarkVTableUsed(Loc, Destructor->getParent());
13159   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13160     if (MethodDecl->isOverloadedOperator() &&
13161         MethodDecl->getOverloadedOperator() == OO_Equal) {
13162       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13163       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13164         if (MethodDecl->isCopyAssignmentOperator())
13165           DefineImplicitCopyAssignment(Loc, MethodDecl);
13166         else if (MethodDecl->isMoveAssignmentOperator())
13167           DefineImplicitMoveAssignment(Loc, MethodDecl);
13168       }
13169     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13170                MethodDecl->getParent()->isLambda()) {
13171       CXXConversionDecl *Conversion =
13172           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13173       if (Conversion->isLambdaToBlockPointerConversion())
13174         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13175       else
13176         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13177     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13178       MarkVTableUsed(Loc, MethodDecl->getParent());
13179   }
13180
13181   // Recursive functions should be marked when used from another function.
13182   // FIXME: Is this really right?
13183   if (CurContext == Func) return;
13184
13185   // Resolve the exception specification for any function which is
13186   // used: CodeGen will need it.
13187   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13188   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13189     ResolveExceptionSpec(Loc, FPT);
13190
13191   // Implicit instantiation of function templates and member functions of
13192   // class templates.
13193   if (Func->isImplicitlyInstantiable()) {
13194     bool AlreadyInstantiated = false;
13195     SourceLocation PointOfInstantiation = Loc;
13196     if (FunctionTemplateSpecializationInfo *SpecInfo
13197                               = Func->getTemplateSpecializationInfo()) {
13198       if (SpecInfo->getPointOfInstantiation().isInvalid())
13199         SpecInfo->setPointOfInstantiation(Loc);
13200       else if (SpecInfo->getTemplateSpecializationKind()
13201                  == TSK_ImplicitInstantiation) {
13202         AlreadyInstantiated = true;
13203         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13204       }
13205     } else if (MemberSpecializationInfo *MSInfo
13206                                 = Func->getMemberSpecializationInfo()) {
13207       if (MSInfo->getPointOfInstantiation().isInvalid())
13208         MSInfo->setPointOfInstantiation(Loc);
13209       else if (MSInfo->getTemplateSpecializationKind()
13210                  == TSK_ImplicitInstantiation) {
13211         AlreadyInstantiated = true;
13212         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13213       }
13214     }
13215
13216     if (!AlreadyInstantiated || Func->isConstexpr()) {
13217       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13218           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13219           ActiveTemplateInstantiations.size())
13220         PendingLocalImplicitInstantiations.push_back(
13221             std::make_pair(Func, PointOfInstantiation));
13222       else if (Func->isConstexpr())
13223         // Do not defer instantiations of constexpr functions, to avoid the
13224         // expression evaluator needing to call back into Sema if it sees a
13225         // call to such a function.
13226         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13227       else {
13228         PendingInstantiations.push_back(std::make_pair(Func,
13229                                                        PointOfInstantiation));
13230         // Notify the consumer that a function was implicitly instantiated.
13231         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13232       }
13233     }
13234   } else {
13235     // Walk redefinitions, as some of them may be instantiable.
13236     for (auto i : Func->redecls()) {
13237       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13238         MarkFunctionReferenced(Loc, i, OdrUse);
13239     }
13240   }
13241
13242   if (!OdrUse) return;
13243
13244   // Keep track of used but undefined functions.
13245   if (!Func->isDefined()) {
13246     if (mightHaveNonExternalLinkage(Func))
13247       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13248     else if (Func->getMostRecentDecl()->isInlined() &&
13249              !LangOpts.GNUInline &&
13250              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13251       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13252   }
13253
13254   Func->markUsed(Context);
13255 }
13256
13257 static void
13258 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13259                                    ValueDecl *var, DeclContext *DC) {
13260   DeclContext *VarDC = var->getDeclContext();
13261
13262   //  If the parameter still belongs to the translation unit, then
13263   //  we're actually just using one parameter in the declaration of
13264   //  the next.
13265   if (isa<ParmVarDecl>(var) &&
13266       isa<TranslationUnitDecl>(VarDC))
13267     return;
13268
13269   // For C code, don't diagnose about capture if we're not actually in code
13270   // right now; it's impossible to write a non-constant expression outside of
13271   // function context, so we'll get other (more useful) diagnostics later.
13272   //
13273   // For C++, things get a bit more nasty... it would be nice to suppress this
13274   // diagnostic for certain cases like using a local variable in an array bound
13275   // for a member of a local class, but the correct predicate is not obvious.
13276   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13277     return;
13278
13279   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13280   unsigned ContextKind = 3; // unknown
13281   if (isa<CXXMethodDecl>(VarDC) &&
13282       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13283     ContextKind = 2;
13284   } else if (isa<FunctionDecl>(VarDC)) {
13285     ContextKind = 0;
13286   } else if (isa<BlockDecl>(VarDC)) {
13287     ContextKind = 1;
13288   }
13289
13290   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13291     << var << ValueKind << ContextKind << VarDC;
13292   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13293       << var;
13294
13295   // FIXME: Add additional diagnostic info about class etc. which prevents
13296   // capture.
13297 }
13298
13299  
13300 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
13301                                       bool &SubCapturesAreNested,
13302                                       QualType &CaptureType, 
13303                                       QualType &DeclRefType) {
13304    // Check whether we've already captured it.
13305   if (CSI->CaptureMap.count(Var)) {
13306     // If we found a capture, any subcaptures are nested.
13307     SubCapturesAreNested = true;
13308       
13309     // Retrieve the capture type for this variable.
13310     CaptureType = CSI->getCapture(Var).getCaptureType();
13311       
13312     // Compute the type of an expression that refers to this variable.
13313     DeclRefType = CaptureType.getNonReferenceType();
13314
13315     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13316     // are mutable in the sense that user can change their value - they are
13317     // private instances of the captured declarations.
13318     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13319     if (Cap.isCopyCapture() &&
13320         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13321         !(isa<CapturedRegionScopeInfo>(CSI) &&
13322           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13323       DeclRefType.addConst();
13324     return true;
13325   }
13326   return false;
13327 }
13328
13329 // Only block literals, captured statements, and lambda expressions can
13330 // capture; other scopes don't work.
13331 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
13332                                  SourceLocation Loc, 
13333                                  const bool Diagnose, Sema &S) {
13334   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13335     return getLambdaAwareParentOfDeclContext(DC);
13336   else if (Var->hasLocalStorage()) {
13337     if (Diagnose)
13338        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13339   }
13340   return nullptr;
13341 }
13342
13343 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13344 // certain types of variables (unnamed, variably modified types etc.)
13345 // so check for eligibility.
13346 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
13347                                  SourceLocation Loc, 
13348                                  const bool Diagnose, Sema &S) {
13349
13350   bool IsBlock = isa<BlockScopeInfo>(CSI);
13351   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13352
13353   // Lambdas are not allowed to capture unnamed variables
13354   // (e.g. anonymous unions).
13355   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13356   // assuming that's the intent.
13357   if (IsLambda && !Var->getDeclName()) {
13358     if (Diagnose) {
13359       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13360       S.Diag(Var->getLocation(), diag::note_declared_at);
13361     }
13362     return false;
13363   }
13364
13365   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13366   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13367     if (Diagnose) {
13368       S.Diag(Loc, diag::err_ref_vm_type);
13369       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13370         << Var->getDeclName();
13371     }
13372     return false;
13373   }
13374   // Prohibit structs with flexible array members too.
13375   // We cannot capture what is in the tail end of the struct.
13376   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13377     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13378       if (Diagnose) {
13379         if (IsBlock)
13380           S.Diag(Loc, diag::err_ref_flexarray_type);
13381         else
13382           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13383             << Var->getDeclName();
13384         S.Diag(Var->getLocation(), diag::note_previous_decl)
13385           << Var->getDeclName();
13386       }
13387       return false;
13388     }
13389   }
13390   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13391   // Lambdas and captured statements are not allowed to capture __block
13392   // variables; they don't support the expected semantics.
13393   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13394     if (Diagnose) {
13395       S.Diag(Loc, diag::err_capture_block_variable)
13396         << Var->getDeclName() << !IsLambda;
13397       S.Diag(Var->getLocation(), diag::note_previous_decl)
13398         << Var->getDeclName();
13399     }
13400     return false;
13401   }
13402
13403   return true;
13404 }
13405
13406 // Returns true if the capture by block was successful.
13407 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
13408                                  SourceLocation Loc, 
13409                                  const bool BuildAndDiagnose, 
13410                                  QualType &CaptureType,
13411                                  QualType &DeclRefType, 
13412                                  const bool Nested,
13413                                  Sema &S) {
13414   Expr *CopyExpr = nullptr;
13415   bool ByRef = false;
13416       
13417   // Blocks are not allowed to capture arrays.
13418   if (CaptureType->isArrayType()) {
13419     if (BuildAndDiagnose) {
13420       S.Diag(Loc, diag::err_ref_array_type);
13421       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13422       << Var->getDeclName();
13423     }
13424     return false;
13425   }
13426
13427   // Forbid the block-capture of autoreleasing variables.
13428   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13429     if (BuildAndDiagnose) {
13430       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13431         << /*block*/ 0;
13432       S.Diag(Var->getLocation(), diag::note_previous_decl)
13433         << Var->getDeclName();
13434     }
13435     return false;
13436   }
13437   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13438   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13439       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13440     // Block capture by reference does not change the capture or
13441     // declaration reference types.
13442     ByRef = true;
13443   } else {
13444     // Block capture by copy introduces 'const'.
13445     CaptureType = CaptureType.getNonReferenceType().withConst();
13446     DeclRefType = CaptureType;
13447                 
13448     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13449       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13450         // The capture logic needs the destructor, so make sure we mark it.
13451         // Usually this is unnecessary because most local variables have
13452         // their destructors marked at declaration time, but parameters are
13453         // an exception because it's technically only the call site that
13454         // actually requires the destructor.
13455         if (isa<ParmVarDecl>(Var))
13456           S.FinalizeVarWithDestructor(Var, Record);
13457
13458         // Enter a new evaluation context to insulate the copy
13459         // full-expression.
13460         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13461
13462         // According to the blocks spec, the capture of a variable from
13463         // the stack requires a const copy constructor.  This is not true
13464         // of the copy/move done to move a __block variable to the heap.
13465         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13466                                                   DeclRefType.withConst(), 
13467                                                   VK_LValue, Loc);
13468             
13469         ExprResult Result
13470           = S.PerformCopyInitialization(
13471               InitializedEntity::InitializeBlock(Var->getLocation(),
13472                                                   CaptureType, false),
13473               Loc, DeclRef);
13474             
13475         // Build a full-expression copy expression if initialization
13476         // succeeded and used a non-trivial constructor.  Recover from
13477         // errors by pretending that the copy isn't necessary.
13478         if (!Result.isInvalid() &&
13479             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13480                 ->isTrivial()) {
13481           Result = S.MaybeCreateExprWithCleanups(Result);
13482           CopyExpr = Result.get();
13483         }
13484       }
13485     }
13486   }
13487
13488   // Actually capture the variable.
13489   if (BuildAndDiagnose)
13490     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
13491                     SourceLocation(), CaptureType, CopyExpr);
13492
13493   return true;
13494
13495 }
13496
13497
13498 /// \brief Capture the given variable in the captured region.
13499 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13500                                     VarDecl *Var, 
13501                                     SourceLocation Loc, 
13502                                     const bool BuildAndDiagnose, 
13503                                     QualType &CaptureType,
13504                                     QualType &DeclRefType, 
13505                                     const bool RefersToCapturedVariable,
13506                                     Sema &S) {
13507   // By default, capture variables by reference.
13508   bool ByRef = true;
13509   // Using an LValue reference type is consistent with Lambdas (see below).
13510   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13511     if (S.IsOpenMPCapturedDecl(Var))
13512       DeclRefType = DeclRefType.getUnqualifiedType();
13513     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13514   }
13515
13516   if (ByRef)
13517     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13518   else
13519     CaptureType = DeclRefType;
13520
13521   Expr *CopyExpr = nullptr;
13522   if (BuildAndDiagnose) {
13523     // The current implementation assumes that all variables are captured
13524     // by references. Since there is no capture by copy, no expression
13525     // evaluation will be needed.
13526     RecordDecl *RD = RSI->TheRecordDecl;
13527
13528     FieldDecl *Field
13529       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13530                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13531                           nullptr, false, ICIS_NoInit);
13532     Field->setImplicit(true);
13533     Field->setAccess(AS_private);
13534     RD->addDecl(Field);
13535  
13536     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13537                                             DeclRefType, VK_LValue, Loc);
13538     Var->setReferenced(true);
13539     Var->markUsed(S.Context);
13540   }
13541
13542   // Actually capture the variable.
13543   if (BuildAndDiagnose)
13544     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13545                     SourceLocation(), CaptureType, CopyExpr);
13546   
13547   
13548   return true;
13549 }
13550
13551 /// \brief Create a field within the lambda class for the variable
13552 /// being captured.
13553 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 
13554                                     QualType FieldType, QualType DeclRefType,
13555                                     SourceLocation Loc,
13556                                     bool RefersToCapturedVariable) {
13557   CXXRecordDecl *Lambda = LSI->Lambda;
13558
13559   // Build the non-static data member.
13560   FieldDecl *Field
13561     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13562                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13563                         nullptr, false, ICIS_NoInit);
13564   Field->setImplicit(true);
13565   Field->setAccess(AS_private);
13566   Lambda->addDecl(Field);
13567 }
13568
13569 /// \brief Capture the given variable in the lambda.
13570 static bool captureInLambda(LambdaScopeInfo *LSI,
13571                             VarDecl *Var, 
13572                             SourceLocation Loc, 
13573                             const bool BuildAndDiagnose, 
13574                             QualType &CaptureType,
13575                             QualType &DeclRefType, 
13576                             const bool RefersToCapturedVariable,
13577                             const Sema::TryCaptureKind Kind, 
13578                             SourceLocation EllipsisLoc,
13579                             const bool IsTopScope,
13580                             Sema &S) {
13581
13582   // Determine whether we are capturing by reference or by value.
13583   bool ByRef = false;
13584   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13585     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13586   } else {
13587     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13588   }
13589     
13590   // Compute the type of the field that will capture this variable.
13591   if (ByRef) {
13592     // C++11 [expr.prim.lambda]p15:
13593     //   An entity is captured by reference if it is implicitly or
13594     //   explicitly captured but not captured by copy. It is
13595     //   unspecified whether additional unnamed non-static data
13596     //   members are declared in the closure type for entities
13597     //   captured by reference.
13598     //
13599     // FIXME: It is not clear whether we want to build an lvalue reference
13600     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13601     // to do the former, while EDG does the latter. Core issue 1249 will 
13602     // clarify, but for now we follow GCC because it's a more permissive and
13603     // easily defensible position.
13604     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13605   } else {
13606     // C++11 [expr.prim.lambda]p14:
13607     //   For each entity captured by copy, an unnamed non-static
13608     //   data member is declared in the closure type. The
13609     //   declaration order of these members is unspecified. The type
13610     //   of such a data member is the type of the corresponding
13611     //   captured entity if the entity is not a reference to an
13612     //   object, or the referenced type otherwise. [Note: If the
13613     //   captured entity is a reference to a function, the
13614     //   corresponding data member is also a reference to a
13615     //   function. - end note ]
13616     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13617       if (!RefType->getPointeeType()->isFunctionType())
13618         CaptureType = RefType->getPointeeType();
13619     }
13620
13621     // Forbid the lambda copy-capture of autoreleasing variables.
13622     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13623       if (BuildAndDiagnose) {
13624         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13625         S.Diag(Var->getLocation(), diag::note_previous_decl)
13626           << Var->getDeclName();
13627       }
13628       return false;
13629     }
13630
13631     // Make sure that by-copy captures are of a complete and non-abstract type.
13632     if (BuildAndDiagnose) {
13633       if (!CaptureType->isDependentType() &&
13634           S.RequireCompleteType(Loc, CaptureType,
13635                                 diag::err_capture_of_incomplete_type,
13636                                 Var->getDeclName()))
13637         return false;
13638
13639       if (S.RequireNonAbstractType(Loc, CaptureType,
13640                                    diag::err_capture_of_abstract_type))
13641         return false;
13642     }
13643   }
13644
13645   // Capture this variable in the lambda.
13646   if (BuildAndDiagnose)
13647     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13648                             RefersToCapturedVariable);
13649     
13650   // Compute the type of a reference to this captured variable.
13651   if (ByRef)
13652     DeclRefType = CaptureType.getNonReferenceType();
13653   else {
13654     // C++ [expr.prim.lambda]p5:
13655     //   The closure type for a lambda-expression has a public inline 
13656     //   function call operator [...]. This function call operator is 
13657     //   declared const (9.3.1) if and only if the lambda-expression's 
13658     //   parameter-declaration-clause is not followed by mutable.
13659     DeclRefType = CaptureType.getNonReferenceType();
13660     if (!LSI->Mutable && !CaptureType->isReferenceType())
13661       DeclRefType.addConst();      
13662   }
13663     
13664   // Add the capture.
13665   if (BuildAndDiagnose)
13666     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
13667                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13668       
13669   return true;
13670 }
13671
13672 bool Sema::tryCaptureVariable(
13673     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13674     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13675     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13676   // An init-capture is notionally from the context surrounding its
13677   // declaration, but its parent DC is the lambda class.
13678   DeclContext *VarDC = Var->getDeclContext();
13679   if (Var->isInitCapture())
13680     VarDC = VarDC->getParent();
13681   
13682   DeclContext *DC = CurContext;
13683   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
13684       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
13685   // We need to sync up the Declaration Context with the
13686   // FunctionScopeIndexToStopAt
13687   if (FunctionScopeIndexToStopAt) {
13688     unsigned FSIndex = FunctionScopes.size() - 1;
13689     while (FSIndex != MaxFunctionScopesIndex) {
13690       DC = getLambdaAwareParentOfDeclContext(DC);
13691       --FSIndex;
13692     }
13693   }
13694
13695   
13696   // If the variable is declared in the current context, there is no need to
13697   // capture it.
13698   if (VarDC == DC) return true;
13699
13700   // Capture global variables if it is required to use private copy of this
13701   // variable.
13702   bool IsGlobal = !Var->hasLocalStorage();
13703   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13704     return true;
13705
13706   // Walk up the stack to determine whether we can capture the variable,
13707   // performing the "simple" checks that don't depend on type. We stop when
13708   // we've either hit the declared scope of the variable or find an existing
13709   // capture of that variable.  We start from the innermost capturing-entity
13710   // (the DC) and ensure that all intervening capturing-entities 
13711   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13712   // declcontext can either capture the variable or have already captured
13713   // the variable.
13714   CaptureType = Var->getType();
13715   DeclRefType = CaptureType.getNonReferenceType();
13716   bool Nested = false;
13717   bool Explicit = (Kind != TryCapture_Implicit);
13718   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13719   do {
13720     // Only block literals, captured statements, and lambda expressions can
13721     // capture; other scopes don't work.
13722     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
13723                                                               ExprLoc, 
13724                                                               BuildAndDiagnose,
13725                                                               *this);
13726     // We need to check for the parent *first* because, if we *have*
13727     // private-captured a global variable, we need to recursively capture it in
13728     // intermediate blocks, lambdas, etc.
13729     if (!ParentDC) {
13730       if (IsGlobal) {
13731         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13732         break;
13733       }
13734       return true;
13735     }
13736
13737     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13738     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13739
13740
13741     // Check whether we've already captured it.
13742     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
13743                                              DeclRefType)) 
13744       break;
13745     // If we are instantiating a generic lambda call operator body, 
13746     // we do not want to capture new variables.  What was captured
13747     // during either a lambdas transformation or initial parsing
13748     // should be used. 
13749     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13750       if (BuildAndDiagnose) {
13751         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
13752         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13753           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13754           Diag(Var->getLocation(), diag::note_previous_decl) 
13755              << Var->getDeclName();
13756           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
13757         } else
13758           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13759       }
13760       return true;
13761     }
13762     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13763     // certain types of variables (unnamed, variably modified types etc.)
13764     // so check for eligibility.
13765     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13766        return true;
13767
13768     // Try to capture variable-length arrays types.
13769     if (Var->getType()->isVariablyModifiedType()) {
13770       // We're going to walk down into the type and look for VLA
13771       // expressions.
13772       QualType QTy = Var->getType();
13773       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13774         QTy = PVD->getOriginalType();
13775       captureVariablyModifiedType(Context, QTy, CSI);
13776     }
13777
13778     if (getLangOpts().OpenMP) {
13779       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13780         // OpenMP private variables should not be captured in outer scope, so
13781         // just break here. Similarly, global variables that are captured in a
13782         // target region should not be captured outside the scope of the region.
13783         if (RSI->CapRegionKind == CR_OpenMP) {
13784           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13785           // When we detect target captures we are looking from inside the
13786           // target region, therefore we need to propagate the capture from the
13787           // enclosing region. Therefore, the capture is not initially nested.
13788           if (IsTargetCap)
13789             FunctionScopesIndex--;
13790
13791           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13792             Nested = !IsTargetCap;
13793             DeclRefType = DeclRefType.getUnqualifiedType();
13794             CaptureType = Context.getLValueReferenceType(DeclRefType);
13795             break;
13796           }
13797         }
13798       }
13799     }
13800     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13801       // No capture-default, and this is not an explicit capture 
13802       // so cannot capture this variable.  
13803       if (BuildAndDiagnose) {
13804         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13805         Diag(Var->getLocation(), diag::note_previous_decl) 
13806           << Var->getDeclName();
13807         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13808           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13809                diag::note_lambda_decl);
13810         // FIXME: If we error out because an outer lambda can not implicitly
13811         // capture a variable that an inner lambda explicitly captures, we
13812         // should have the inner lambda do the explicit capture - because
13813         // it makes for cleaner diagnostics later.  This would purely be done
13814         // so that the diagnostic does not misleadingly claim that a variable 
13815         // can not be captured by a lambda implicitly even though it is captured 
13816         // explicitly.  Suggestion:
13817         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
13818         //    at the function head
13819         //  - cache the StartingDeclContext - this must be a lambda 
13820         //  - captureInLambda in the innermost lambda the variable.
13821       }
13822       return true;
13823     }
13824
13825     FunctionScopesIndex--;
13826     DC = ParentDC;
13827     Explicit = false;
13828   } while (!VarDC->Equals(DC));
13829
13830   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13831   // computing the type of the capture at each step, checking type-specific 
13832   // requirements, and adding captures if requested. 
13833   // If the variable had already been captured previously, we start capturing 
13834   // at the lambda nested within that one.   
13835   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
13836        ++I) {
13837     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13838     
13839     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13840       if (!captureInBlock(BSI, Var, ExprLoc, 
13841                           BuildAndDiagnose, CaptureType, 
13842                           DeclRefType, Nested, *this))
13843         return true;
13844       Nested = true;
13845     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13846       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
13847                                    BuildAndDiagnose, CaptureType, 
13848                                    DeclRefType, Nested, *this))
13849         return true;
13850       Nested = true;
13851     } else {
13852       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13853       if (!captureInLambda(LSI, Var, ExprLoc, 
13854                            BuildAndDiagnose, CaptureType, 
13855                            DeclRefType, Nested, Kind, EllipsisLoc, 
13856                             /*IsTopScope*/I == N - 1, *this))
13857         return true;
13858       Nested = true;
13859     }
13860   }
13861   return false;
13862 }
13863
13864 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13865                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
13866   QualType CaptureType;
13867   QualType DeclRefType;
13868   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13869                             /*BuildAndDiagnose=*/true, CaptureType,
13870                             DeclRefType, nullptr);
13871 }
13872
13873 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13874   QualType CaptureType;
13875   QualType DeclRefType;
13876   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13877                              /*BuildAndDiagnose=*/false, CaptureType,
13878                              DeclRefType, nullptr);
13879 }
13880
13881 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13882   QualType CaptureType;
13883   QualType DeclRefType;
13884   
13885   // Determine whether we can capture this variable.
13886   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13887                          /*BuildAndDiagnose=*/false, CaptureType, 
13888                          DeclRefType, nullptr))
13889     return QualType();
13890
13891   return DeclRefType;
13892 }
13893
13894
13895
13896 // If either the type of the variable or the initializer is dependent, 
13897 // return false. Otherwise, determine whether the variable is a constant
13898 // expression. Use this if you need to know if a variable that might or
13899 // might not be dependent is truly a constant expression.
13900 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
13901     ASTContext &Context) {
13902  
13903   if (Var->getType()->isDependentType()) 
13904     return false;
13905   const VarDecl *DefVD = nullptr;
13906   Var->getAnyInitializer(DefVD);
13907   if (!DefVD) 
13908     return false;
13909   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13910   Expr *Init = cast<Expr>(Eval->Value);
13911   if (Init->isValueDependent()) 
13912     return false;
13913   return IsVariableAConstantExpression(Var, Context); 
13914 }
13915
13916
13917 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13918   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
13919   // an object that satisfies the requirements for appearing in a
13920   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13921   // is immediately applied."  This function handles the lvalue-to-rvalue
13922   // conversion part.
13923   MaybeODRUseExprs.erase(E->IgnoreParens());
13924   
13925   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13926   // to a variable that is a constant expression, and if so, identify it as
13927   // a reference to a variable that does not involve an odr-use of that 
13928   // variable. 
13929   if (LambdaScopeInfo *LSI = getCurLambda()) {
13930     Expr *SansParensExpr = E->IgnoreParens();
13931     VarDecl *Var = nullptr;
13932     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
13933       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13934     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13935       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13936     
13937     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
13938       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
13939   }
13940 }
13941
13942 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13943   Res = CorrectDelayedTyposInExpr(Res);
13944
13945   if (!Res.isUsable())
13946     return Res;
13947
13948   // If a constant-expression is a reference to a variable where we delay
13949   // deciding whether it is an odr-use, just assume we will apply the
13950   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13951   // (a non-type template argument), we have special handling anyway.
13952   UpdateMarkingForLValueToRValue(Res.get());
13953   return Res;
13954 }
13955
13956 void Sema::CleanupVarDeclMarking() {
13957   for (Expr *E : MaybeODRUseExprs) {
13958     VarDecl *Var;
13959     SourceLocation Loc;
13960     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13961       Var = cast<VarDecl>(DRE->getDecl());
13962       Loc = DRE->getLocation();
13963     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13964       Var = cast<VarDecl>(ME->getMemberDecl());
13965       Loc = ME->getMemberLoc();
13966     } else {
13967       llvm_unreachable("Unexpected expression");
13968     }
13969
13970     MarkVarDeclODRUsed(Var, Loc, *this,
13971                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13972   }
13973
13974   MaybeODRUseExprs.clear();
13975 }
13976
13977
13978 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13979                                     VarDecl *Var, Expr *E) {
13980   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13981          "Invalid Expr argument to DoMarkVarDeclReferenced");
13982   Var->setReferenced();
13983
13984   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13985   bool MarkODRUsed = true;
13986
13987   // If the context is not potentially evaluated, this is not an odr-use and
13988   // does not trigger instantiation.
13989   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13990     if (SemaRef.isUnevaluatedContext())
13991       return;
13992
13993     // If we don't yet know whether this context is going to end up being an
13994     // evaluated context, and we're referencing a variable from an enclosing
13995     // scope, add a potential capture.
13996     //
13997     // FIXME: Is this necessary? These contexts are only used for default
13998     // arguments, where local variables can't be used.
13999     const bool RefersToEnclosingScope =
14000         (SemaRef.CurContext != Var->getDeclContext() &&
14001          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14002     if (RefersToEnclosingScope) {
14003       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
14004         // If a variable could potentially be odr-used, defer marking it so
14005         // until we finish analyzing the full expression for any
14006         // lvalue-to-rvalue
14007         // or discarded value conversions that would obviate odr-use.
14008         // Add it to the list of potential captures that will be analyzed
14009         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14010         // unless the variable is a reference that was initialized by a constant
14011         // expression (this will never need to be captured or odr-used).
14012         assert(E && "Capture variable should be used in an expression.");
14013         if (!Var->getType()->isReferenceType() ||
14014             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14015           LSI->addPotentialCapture(E->IgnoreParens());
14016       }
14017     }
14018
14019     if (!isTemplateInstantiation(TSK))
14020       return;
14021
14022     // Instantiate, but do not mark as odr-used, variable templates.
14023     MarkODRUsed = false;
14024   }
14025
14026   VarTemplateSpecializationDecl *VarSpec =
14027       dyn_cast<VarTemplateSpecializationDecl>(Var);
14028   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14029          "Can't instantiate a partial template specialization.");
14030
14031   // If this might be a member specialization of a static data member, check
14032   // the specialization is visible. We already did the checks for variable
14033   // template specializations when we created them.
14034   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14035     SemaRef.checkSpecializationVisibility(Loc, Var);
14036
14037   // Perform implicit instantiation of static data members, static data member
14038   // templates of class templates, and variable template specializations. Delay
14039   // instantiations of variable templates, except for those that could be used
14040   // in a constant expression.
14041   if (isTemplateInstantiation(TSK)) {
14042     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14043
14044     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14045       if (Var->getPointOfInstantiation().isInvalid()) {
14046         // This is a modification of an existing AST node. Notify listeners.
14047         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14048           L->StaticDataMemberInstantiated(Var);
14049       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14050         // Don't bother trying to instantiate it again, unless we might need
14051         // its initializer before we get to the end of the TU.
14052         TryInstantiating = false;
14053     }
14054
14055     if (Var->getPointOfInstantiation().isInvalid())
14056       Var->setTemplateSpecializationKind(TSK, Loc);
14057
14058     if (TryInstantiating) {
14059       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14060       bool InstantiationDependent = false;
14061       bool IsNonDependent =
14062           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14063                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14064                   : true;
14065
14066       // Do not instantiate specializations that are still type-dependent.
14067       if (IsNonDependent) {
14068         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14069           // Do not defer instantiations of variables which could be used in a
14070           // constant expression.
14071           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14072         } else {
14073           SemaRef.PendingInstantiations
14074               .push_back(std::make_pair(Var, PointOfInstantiation));
14075         }
14076       }
14077     }
14078   }
14079
14080   if (!MarkODRUsed)
14081     return;
14082
14083   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14084   // the requirements for appearing in a constant expression (5.19) and, if
14085   // it is an object, the lvalue-to-rvalue conversion (4.1)
14086   // is immediately applied."  We check the first part here, and
14087   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14088   // Note that we use the C++11 definition everywhere because nothing in
14089   // C++03 depends on whether we get the C++03 version correct. The second
14090   // part does not apply to references, since they are not objects.
14091   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14092     // A reference initialized by a constant expression can never be
14093     // odr-used, so simply ignore it.
14094     if (!Var->getType()->isReferenceType())
14095       SemaRef.MaybeODRUseExprs.insert(E);
14096   } else
14097     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14098                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14099 }
14100
14101 /// \brief Mark a variable referenced, and check whether it is odr-used
14102 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14103 /// used directly for normal expressions referring to VarDecl.
14104 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14105   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14106 }
14107
14108 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14109                                Decl *D, Expr *E, bool MightBeOdrUse) {
14110   if (SemaRef.isInOpenMPDeclareTargetContext())
14111     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14112
14113   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14114     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14115     return;
14116   }
14117
14118   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14119
14120   // If this is a call to a method via a cast, also mark the method in the
14121   // derived class used in case codegen can devirtualize the call.
14122   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14123   if (!ME)
14124     return;
14125   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14126   if (!MD)
14127     return;
14128   // Only attempt to devirtualize if this is truly a virtual call.
14129   bool IsVirtualCall = MD->isVirtual() &&
14130                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14131   if (!IsVirtualCall)
14132     return;
14133   const Expr *Base = ME->getBase();
14134   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14135   if (!MostDerivedClassDecl)
14136     return;
14137   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14138   if (!DM || DM->isPure())
14139     return;
14140   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14141
14142
14143 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14144 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14145   // TODO: update this with DR# once a defect report is filed.
14146   // C++11 defect. The address of a pure member should not be an ODR use, even
14147   // if it's a qualified reference.
14148   bool OdrUse = true;
14149   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14150     if (Method->isVirtual())
14151       OdrUse = false;
14152   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14153 }
14154
14155 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14156 void Sema::MarkMemberReferenced(MemberExpr *E) {
14157   // C++11 [basic.def.odr]p2:
14158   //   A non-overloaded function whose name appears as a potentially-evaluated
14159   //   expression or a member of a set of candidate functions, if selected by
14160   //   overload resolution when referred to from a potentially-evaluated
14161   //   expression, is odr-used, unless it is a pure virtual function and its
14162   //   name is not explicitly qualified.
14163   bool MightBeOdrUse = true;
14164   if (E->performsVirtualDispatch(getLangOpts())) {
14165     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14166       if (Method->isPure())
14167         MightBeOdrUse = false;
14168   }
14169   SourceLocation Loc = E->getMemberLoc().isValid() ?
14170                             E->getMemberLoc() : E->getLocStart();
14171   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14172 }
14173
14174 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14175 /// marks the declaration referenced, and performs odr-use checking for
14176 /// functions and variables. This method should not be used when building a
14177 /// normal expression which refers to a variable.
14178 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14179                                  bool MightBeOdrUse) {
14180   if (MightBeOdrUse) {
14181     if (auto *VD = dyn_cast<VarDecl>(D)) {
14182       MarkVariableReferenced(Loc, VD);
14183       return;
14184     }
14185   }
14186   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14187     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14188     return;
14189   }
14190   D->setReferenced();
14191 }
14192
14193 namespace {
14194   // Mark all of the declarations referenced
14195   // FIXME: Not fully implemented yet! We need to have a better understanding
14196   // of when we're entering
14197   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14198     Sema &S;
14199     SourceLocation Loc;
14200
14201   public:
14202     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14203
14204     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14205
14206     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14207     bool TraverseRecordType(RecordType *T);
14208   };
14209 }
14210
14211 bool MarkReferencedDecls::TraverseTemplateArgument(
14212     const TemplateArgument &Arg) {
14213   if (Arg.getKind() == TemplateArgument::Declaration) {
14214     if (Decl *D = Arg.getAsDecl())
14215       S.MarkAnyDeclReferenced(Loc, D, true);
14216   }
14217
14218   return Inherited::TraverseTemplateArgument(Arg);
14219 }
14220
14221 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14222   if (ClassTemplateSpecializationDecl *Spec
14223                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14224     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14225     return TraverseTemplateArguments(Args.data(), Args.size());
14226   }
14227
14228   return true;
14229 }
14230
14231 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14232   MarkReferencedDecls Marker(*this, Loc);
14233   Marker.TraverseType(Context.getCanonicalType(T));
14234 }
14235
14236 namespace {
14237   /// \brief Helper class that marks all of the declarations referenced by
14238   /// potentially-evaluated subexpressions as "referenced".
14239   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14240     Sema &S;
14241     bool SkipLocalVariables;
14242     
14243   public:
14244     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14245     
14246     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
14247       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14248     
14249     void VisitDeclRefExpr(DeclRefExpr *E) {
14250       // If we were asked not to visit local variables, don't.
14251       if (SkipLocalVariables) {
14252         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14253           if (VD->hasLocalStorage())
14254             return;
14255       }
14256       
14257       S.MarkDeclRefReferenced(E);
14258     }
14259
14260     void VisitMemberExpr(MemberExpr *E) {
14261       S.MarkMemberReferenced(E);
14262       Inherited::VisitMemberExpr(E);
14263     }
14264     
14265     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14266       S.MarkFunctionReferenced(E->getLocStart(),
14267             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14268       Visit(E->getSubExpr());
14269     }
14270     
14271     void VisitCXXNewExpr(CXXNewExpr *E) {
14272       if (E->getOperatorNew())
14273         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14274       if (E->getOperatorDelete())
14275         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14276       Inherited::VisitCXXNewExpr(E);
14277     }
14278
14279     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14280       if (E->getOperatorDelete())
14281         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14282       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14283       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14284         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14285         S.MarkFunctionReferenced(E->getLocStart(), 
14286                                     S.LookupDestructor(Record));
14287       }
14288       
14289       Inherited::VisitCXXDeleteExpr(E);
14290     }
14291     
14292     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14293       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14294       Inherited::VisitCXXConstructExpr(E);
14295     }
14296     
14297     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14298       Visit(E->getExpr());
14299     }
14300
14301     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14302       Inherited::VisitImplicitCastExpr(E);
14303
14304       if (E->getCastKind() == CK_LValueToRValue)
14305         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14306     }
14307   };
14308 }
14309
14310 /// \brief Mark any declarations that appear within this expression or any
14311 /// potentially-evaluated subexpressions as "referenced".
14312 ///
14313 /// \param SkipLocalVariables If true, don't mark local variables as 
14314 /// 'referenced'.
14315 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
14316                                             bool SkipLocalVariables) {
14317   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14318 }
14319
14320 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14321 /// of the program being compiled.
14322 ///
14323 /// This routine emits the given diagnostic when the code currently being
14324 /// type-checked is "potentially evaluated", meaning that there is a
14325 /// possibility that the code will actually be executable. Code in sizeof()
14326 /// expressions, code used only during overload resolution, etc., are not
14327 /// potentially evaluated. This routine will suppress such diagnostics or,
14328 /// in the absolutely nutty case of potentially potentially evaluated
14329 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14330 /// later.
14331 ///
14332 /// This routine should be used for all diagnostics that describe the run-time
14333 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14334 /// Failure to do so will likely result in spurious diagnostics or failures
14335 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14336 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14337                                const PartialDiagnostic &PD) {
14338   switch (ExprEvalContexts.back().Context) {
14339   case Unevaluated:
14340   case UnevaluatedAbstract:
14341   case DiscardedStatement:
14342     // The argument will never be evaluated, so don't complain.
14343     break;
14344
14345   case ConstantEvaluated:
14346     // Relevant diagnostics should be produced by constant evaluation.
14347     break;
14348
14349   case PotentiallyEvaluated:
14350   case PotentiallyEvaluatedIfUsed:
14351     if (Statement && getCurFunctionOrMethodDecl()) {
14352       FunctionScopes.back()->PossiblyUnreachableDiags.
14353         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14354     }
14355     else
14356       Diag(Loc, PD);
14357       
14358     return true;
14359   }
14360
14361   return false;
14362 }
14363
14364 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14365                                CallExpr *CE, FunctionDecl *FD) {
14366   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14367     return false;
14368
14369   // If we're inside a decltype's expression, don't check for a valid return
14370   // type or construct temporaries until we know whether this is the last call.
14371   if (ExprEvalContexts.back().IsDecltype) {
14372     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14373     return false;
14374   }
14375
14376   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14377     FunctionDecl *FD;
14378     CallExpr *CE;
14379     
14380   public:
14381     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14382       : FD(FD), CE(CE) { }
14383
14384     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14385       if (!FD) {
14386         S.Diag(Loc, diag::err_call_incomplete_return)
14387           << T << CE->getSourceRange();
14388         return;
14389       }
14390       
14391       S.Diag(Loc, diag::err_call_function_incomplete_return)
14392         << CE->getSourceRange() << FD->getDeclName() << T;
14393       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14394           << FD->getDeclName();
14395     }
14396   } Diagnoser(FD, CE);
14397   
14398   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14399     return true;
14400
14401   return false;
14402 }
14403
14404 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14405 // will prevent this condition from triggering, which is what we want.
14406 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14407   SourceLocation Loc;
14408
14409   unsigned diagnostic = diag::warn_condition_is_assignment;
14410   bool IsOrAssign = false;
14411
14412   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14413     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14414       return;
14415
14416     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14417
14418     // Greylist some idioms by putting them into a warning subcategory.
14419     if (ObjCMessageExpr *ME
14420           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14421       Selector Sel = ME->getSelector();
14422
14423       // self = [<foo> init...]
14424       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14425         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14426
14427       // <foo> = [<bar> nextObject]
14428       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14429         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14430     }
14431
14432     Loc = Op->getOperatorLoc();
14433   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14434     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14435       return;
14436
14437     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14438     Loc = Op->getOperatorLoc();
14439   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14440     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14441   else {
14442     // Not an assignment.
14443     return;
14444   }
14445
14446   Diag(Loc, diagnostic) << E->getSourceRange();
14447
14448   SourceLocation Open = E->getLocStart();
14449   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14450   Diag(Loc, diag::note_condition_assign_silence)
14451         << FixItHint::CreateInsertion(Open, "(")
14452         << FixItHint::CreateInsertion(Close, ")");
14453
14454   if (IsOrAssign)
14455     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14456       << FixItHint::CreateReplacement(Loc, "!=");
14457   else
14458     Diag(Loc, diag::note_condition_assign_to_comparison)
14459       << FixItHint::CreateReplacement(Loc, "==");
14460 }
14461
14462 /// \brief Redundant parentheses over an equality comparison can indicate
14463 /// that the user intended an assignment used as condition.
14464 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14465   // Don't warn if the parens came from a macro.
14466   SourceLocation parenLoc = ParenE->getLocStart();
14467   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14468     return;
14469   // Don't warn for dependent expressions.
14470   if (ParenE->isTypeDependent())
14471     return;
14472
14473   Expr *E = ParenE->IgnoreParens();
14474
14475   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14476     if (opE->getOpcode() == BO_EQ &&
14477         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14478                                                            == Expr::MLV_Valid) {
14479       SourceLocation Loc = opE->getOperatorLoc();
14480       
14481       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14482       SourceRange ParenERange = ParenE->getSourceRange();
14483       Diag(Loc, diag::note_equality_comparison_silence)
14484         << FixItHint::CreateRemoval(ParenERange.getBegin())
14485         << FixItHint::CreateRemoval(ParenERange.getEnd());
14486       Diag(Loc, diag::note_equality_comparison_to_assign)
14487         << FixItHint::CreateReplacement(Loc, "=");
14488     }
14489 }
14490
14491 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14492                                        bool IsConstexpr) {
14493   DiagnoseAssignmentAsCondition(E);
14494   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14495     DiagnoseEqualityWithExtraParens(parenE);
14496
14497   ExprResult result = CheckPlaceholderExpr(E);
14498   if (result.isInvalid()) return ExprError();
14499   E = result.get();
14500
14501   if (!E->isTypeDependent()) {
14502     if (getLangOpts().CPlusPlus)
14503       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14504
14505     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14506     if (ERes.isInvalid())
14507       return ExprError();
14508     E = ERes.get();
14509
14510     QualType T = E->getType();
14511     if (!T->isScalarType()) { // C99 6.8.4.1p1
14512       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14513         << T << E->getSourceRange();
14514       return ExprError();
14515     }
14516     CheckBoolLikeConversion(E, Loc);
14517   }
14518
14519   return E;
14520 }
14521
14522 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14523                                            Expr *SubExpr, ConditionKind CK) {
14524   // Empty conditions are valid in for-statements.
14525   if (!SubExpr)
14526     return ConditionResult();
14527
14528   ExprResult Cond;
14529   switch (CK) {
14530   case ConditionKind::Boolean:
14531     Cond = CheckBooleanCondition(Loc, SubExpr);
14532     break;
14533
14534   case ConditionKind::ConstexprIf:
14535     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14536     break;
14537
14538   case ConditionKind::Switch:
14539     Cond = CheckSwitchCondition(Loc, SubExpr);
14540     break;
14541   }
14542   if (Cond.isInvalid())
14543     return ConditionError();
14544
14545   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14546   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14547   if (!FullExpr.get())
14548     return ConditionError();
14549
14550   return ConditionResult(*this, nullptr, FullExpr,
14551                          CK == ConditionKind::ConstexprIf);
14552 }
14553
14554 namespace {
14555   /// A visitor for rebuilding a call to an __unknown_any expression
14556   /// to have an appropriate type.
14557   struct RebuildUnknownAnyFunction
14558     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14559
14560     Sema &S;
14561
14562     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14563
14564     ExprResult VisitStmt(Stmt *S) {
14565       llvm_unreachable("unexpected statement!");
14566     }
14567
14568     ExprResult VisitExpr(Expr *E) {
14569       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14570         << E->getSourceRange();
14571       return ExprError();
14572     }
14573
14574     /// Rebuild an expression which simply semantically wraps another
14575     /// expression which it shares the type and value kind of.
14576     template <class T> ExprResult rebuildSugarExpr(T *E) {
14577       ExprResult SubResult = Visit(E->getSubExpr());
14578       if (SubResult.isInvalid()) return ExprError();
14579
14580       Expr *SubExpr = SubResult.get();
14581       E->setSubExpr(SubExpr);
14582       E->setType(SubExpr->getType());
14583       E->setValueKind(SubExpr->getValueKind());
14584       assert(E->getObjectKind() == OK_Ordinary);
14585       return E;
14586     }
14587
14588     ExprResult VisitParenExpr(ParenExpr *E) {
14589       return rebuildSugarExpr(E);
14590     }
14591
14592     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14593       return rebuildSugarExpr(E);
14594     }
14595
14596     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14597       ExprResult SubResult = Visit(E->getSubExpr());
14598       if (SubResult.isInvalid()) return ExprError();
14599
14600       Expr *SubExpr = SubResult.get();
14601       E->setSubExpr(SubExpr);
14602       E->setType(S.Context.getPointerType(SubExpr->getType()));
14603       assert(E->getValueKind() == VK_RValue);
14604       assert(E->getObjectKind() == OK_Ordinary);
14605       return E;
14606     }
14607
14608     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14609       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14610
14611       E->setType(VD->getType());
14612
14613       assert(E->getValueKind() == VK_RValue);
14614       if (S.getLangOpts().CPlusPlus &&
14615           !(isa<CXXMethodDecl>(VD) &&
14616             cast<CXXMethodDecl>(VD)->isInstance()))
14617         E->setValueKind(VK_LValue);
14618
14619       return E;
14620     }
14621
14622     ExprResult VisitMemberExpr(MemberExpr *E) {
14623       return resolveDecl(E, E->getMemberDecl());
14624     }
14625
14626     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14627       return resolveDecl(E, E->getDecl());
14628     }
14629   };
14630 }
14631
14632 /// Given a function expression of unknown-any type, try to rebuild it
14633 /// to have a function type.
14634 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14635   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14636   if (Result.isInvalid()) return ExprError();
14637   return S.DefaultFunctionArrayConversion(Result.get());
14638 }
14639
14640 namespace {
14641   /// A visitor for rebuilding an expression of type __unknown_anytype
14642   /// into one which resolves the type directly on the referring
14643   /// expression.  Strict preservation of the original source
14644   /// structure is not a goal.
14645   struct RebuildUnknownAnyExpr
14646     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14647
14648     Sema &S;
14649
14650     /// The current destination type.
14651     QualType DestType;
14652
14653     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14654       : S(S), DestType(CastType) {}
14655
14656     ExprResult VisitStmt(Stmt *S) {
14657       llvm_unreachable("unexpected statement!");
14658     }
14659
14660     ExprResult VisitExpr(Expr *E) {
14661       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14662         << E->getSourceRange();
14663       return ExprError();
14664     }
14665
14666     ExprResult VisitCallExpr(CallExpr *E);
14667     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14668
14669     /// Rebuild an expression which simply semantically wraps another
14670     /// expression which it shares the type and value kind of.
14671     template <class T> ExprResult rebuildSugarExpr(T *E) {
14672       ExprResult SubResult = Visit(E->getSubExpr());
14673       if (SubResult.isInvalid()) return ExprError();
14674       Expr *SubExpr = SubResult.get();
14675       E->setSubExpr(SubExpr);
14676       E->setType(SubExpr->getType());
14677       E->setValueKind(SubExpr->getValueKind());
14678       assert(E->getObjectKind() == OK_Ordinary);
14679       return E;
14680     }
14681
14682     ExprResult VisitParenExpr(ParenExpr *E) {
14683       return rebuildSugarExpr(E);
14684     }
14685
14686     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14687       return rebuildSugarExpr(E);
14688     }
14689
14690     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14691       const PointerType *Ptr = DestType->getAs<PointerType>();
14692       if (!Ptr) {
14693         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14694           << E->getSourceRange();
14695         return ExprError();
14696       }
14697       assert(E->getValueKind() == VK_RValue);
14698       assert(E->getObjectKind() == OK_Ordinary);
14699       E->setType(DestType);
14700
14701       // Build the sub-expression as if it were an object of the pointee type.
14702       DestType = Ptr->getPointeeType();
14703       ExprResult SubResult = Visit(E->getSubExpr());
14704       if (SubResult.isInvalid()) return ExprError();
14705       E->setSubExpr(SubResult.get());
14706       return E;
14707     }
14708
14709     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14710
14711     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14712
14713     ExprResult VisitMemberExpr(MemberExpr *E) {
14714       return resolveDecl(E, E->getMemberDecl());
14715     }
14716
14717     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14718       return resolveDecl(E, E->getDecl());
14719     }
14720   };
14721 }
14722
14723 /// Rebuilds a call expression which yielded __unknown_anytype.
14724 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14725   Expr *CalleeExpr = E->getCallee();
14726
14727   enum FnKind {
14728     FK_MemberFunction,
14729     FK_FunctionPointer,
14730     FK_BlockPointer
14731   };
14732
14733   FnKind Kind;
14734   QualType CalleeType = CalleeExpr->getType();
14735   if (CalleeType == S.Context.BoundMemberTy) {
14736     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14737     Kind = FK_MemberFunction;
14738     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14739   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14740     CalleeType = Ptr->getPointeeType();
14741     Kind = FK_FunctionPointer;
14742   } else {
14743     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14744     Kind = FK_BlockPointer;
14745   }
14746   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14747
14748   // Verify that this is a legal result type of a function.
14749   if (DestType->isArrayType() || DestType->isFunctionType()) {
14750     unsigned diagID = diag::err_func_returning_array_function;
14751     if (Kind == FK_BlockPointer)
14752       diagID = diag::err_block_returning_array_function;
14753
14754     S.Diag(E->getExprLoc(), diagID)
14755       << DestType->isFunctionType() << DestType;
14756     return ExprError();
14757   }
14758
14759   // Otherwise, go ahead and set DestType as the call's result.
14760   E->setType(DestType.getNonLValueExprType(S.Context));
14761   E->setValueKind(Expr::getValueKindForType(DestType));
14762   assert(E->getObjectKind() == OK_Ordinary);
14763
14764   // Rebuild the function type, replacing the result type with DestType.
14765   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14766   if (Proto) {
14767     // __unknown_anytype(...) is a special case used by the debugger when
14768     // it has no idea what a function's signature is.
14769     //
14770     // We want to build this call essentially under the K&R
14771     // unprototyped rules, but making a FunctionNoProtoType in C++
14772     // would foul up all sorts of assumptions.  However, we cannot
14773     // simply pass all arguments as variadic arguments, nor can we
14774     // portably just call the function under a non-variadic type; see
14775     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14776     // However, it turns out that in practice it is generally safe to
14777     // call a function declared as "A foo(B,C,D);" under the prototype
14778     // "A foo(B,C,D,...);".  The only known exception is with the
14779     // Windows ABI, where any variadic function is implicitly cdecl
14780     // regardless of its normal CC.  Therefore we change the parameter
14781     // types to match the types of the arguments.
14782     //
14783     // This is a hack, but it is far superior to moving the
14784     // corresponding target-specific code from IR-gen to Sema/AST.
14785
14786     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14787     SmallVector<QualType, 8> ArgTypes;
14788     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14789       ArgTypes.reserve(E->getNumArgs());
14790       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14791         Expr *Arg = E->getArg(i);
14792         QualType ArgType = Arg->getType();
14793         if (E->isLValue()) {
14794           ArgType = S.Context.getLValueReferenceType(ArgType);
14795         } else if (E->isXValue()) {
14796           ArgType = S.Context.getRValueReferenceType(ArgType);
14797         }
14798         ArgTypes.push_back(ArgType);
14799       }
14800       ParamTypes = ArgTypes;
14801     }
14802     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14803                                          Proto->getExtProtoInfo());
14804   } else {
14805     DestType = S.Context.getFunctionNoProtoType(DestType,
14806                                                 FnType->getExtInfo());
14807   }
14808
14809   // Rebuild the appropriate pointer-to-function type.
14810   switch (Kind) { 
14811   case FK_MemberFunction:
14812     // Nothing to do.
14813     break;
14814
14815   case FK_FunctionPointer:
14816     DestType = S.Context.getPointerType(DestType);
14817     break;
14818
14819   case FK_BlockPointer:
14820     DestType = S.Context.getBlockPointerType(DestType);
14821     break;
14822   }
14823
14824   // Finally, we can recurse.
14825   ExprResult CalleeResult = Visit(CalleeExpr);
14826   if (!CalleeResult.isUsable()) return ExprError();
14827   E->setCallee(CalleeResult.get());
14828
14829   // Bind a temporary if necessary.
14830   return S.MaybeBindToTemporary(E);
14831 }
14832
14833 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14834   // Verify that this is a legal result type of a call.
14835   if (DestType->isArrayType() || DestType->isFunctionType()) {
14836     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14837       << DestType->isFunctionType() << DestType;
14838     return ExprError();
14839   }
14840
14841   // Rewrite the method result type if available.
14842   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14843     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14844     Method->setReturnType(DestType);
14845   }
14846
14847   // Change the type of the message.
14848   E->setType(DestType.getNonReferenceType());
14849   E->setValueKind(Expr::getValueKindForType(DestType));
14850
14851   return S.MaybeBindToTemporary(E);
14852 }
14853
14854 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14855   // The only case we should ever see here is a function-to-pointer decay.
14856   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14857     assert(E->getValueKind() == VK_RValue);
14858     assert(E->getObjectKind() == OK_Ordinary);
14859   
14860     E->setType(DestType);
14861   
14862     // Rebuild the sub-expression as the pointee (function) type.
14863     DestType = DestType->castAs<PointerType>()->getPointeeType();
14864   
14865     ExprResult Result = Visit(E->getSubExpr());
14866     if (!Result.isUsable()) return ExprError();
14867   
14868     E->setSubExpr(Result.get());
14869     return E;
14870   } else if (E->getCastKind() == CK_LValueToRValue) {
14871     assert(E->getValueKind() == VK_RValue);
14872     assert(E->getObjectKind() == OK_Ordinary);
14873
14874     assert(isa<BlockPointerType>(E->getType()));
14875
14876     E->setType(DestType);
14877
14878     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14879     DestType = S.Context.getLValueReferenceType(DestType);
14880
14881     ExprResult Result = Visit(E->getSubExpr());
14882     if (!Result.isUsable()) return ExprError();
14883
14884     E->setSubExpr(Result.get());
14885     return E;
14886   } else {
14887     llvm_unreachable("Unhandled cast type!");
14888   }
14889 }
14890
14891 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14892   ExprValueKind ValueKind = VK_LValue;
14893   QualType Type = DestType;
14894
14895   // We know how to make this work for certain kinds of decls:
14896
14897   //  - functions
14898   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14899     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14900       DestType = Ptr->getPointeeType();
14901       ExprResult Result = resolveDecl(E, VD);
14902       if (Result.isInvalid()) return ExprError();
14903       return S.ImpCastExprToType(Result.get(), Type,
14904                                  CK_FunctionToPointerDecay, VK_RValue);
14905     }
14906
14907     if (!Type->isFunctionType()) {
14908       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14909         << VD << E->getSourceRange();
14910       return ExprError();
14911     }
14912     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14913       // We must match the FunctionDecl's type to the hack introduced in
14914       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14915       // type. See the lengthy commentary in that routine.
14916       QualType FDT = FD->getType();
14917       const FunctionType *FnType = FDT->castAs<FunctionType>();
14918       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14919       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14920       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14921         SourceLocation Loc = FD->getLocation();
14922         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14923                                       FD->getDeclContext(),
14924                                       Loc, Loc, FD->getNameInfo().getName(),
14925                                       DestType, FD->getTypeSourceInfo(),
14926                                       SC_None, false/*isInlineSpecified*/,
14927                                       FD->hasPrototype(),
14928                                       false/*isConstexprSpecified*/);
14929           
14930         if (FD->getQualifier())
14931           NewFD->setQualifierInfo(FD->getQualifierLoc());
14932
14933         SmallVector<ParmVarDecl*, 16> Params;
14934         for (const auto &AI : FT->param_types()) {
14935           ParmVarDecl *Param =
14936             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14937           Param->setScopeInfo(0, Params.size());
14938           Params.push_back(Param);
14939         }
14940         NewFD->setParams(Params);
14941         DRE->setDecl(NewFD);
14942         VD = DRE->getDecl();
14943       }
14944     }
14945
14946     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14947       if (MD->isInstance()) {
14948         ValueKind = VK_RValue;
14949         Type = S.Context.BoundMemberTy;
14950       }
14951
14952     // Function references aren't l-values in C.
14953     if (!S.getLangOpts().CPlusPlus)
14954       ValueKind = VK_RValue;
14955
14956   //  - variables
14957   } else if (isa<VarDecl>(VD)) {
14958     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14959       Type = RefTy->getPointeeType();
14960     } else if (Type->isFunctionType()) {
14961       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14962         << VD << E->getSourceRange();
14963       return ExprError();
14964     }
14965
14966   //  - nothing else
14967   } else {
14968     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14969       << VD << E->getSourceRange();
14970     return ExprError();
14971   }
14972
14973   // Modifying the declaration like this is friendly to IR-gen but
14974   // also really dangerous.
14975   VD->setType(DestType);
14976   E->setType(Type);
14977   E->setValueKind(ValueKind);
14978   return E;
14979 }
14980
14981 /// Check a cast of an unknown-any type.  We intentionally only
14982 /// trigger this for C-style casts.
14983 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14984                                      Expr *CastExpr, CastKind &CastKind,
14985                                      ExprValueKind &VK, CXXCastPath &Path) {
14986   // The type we're casting to must be either void or complete.
14987   if (!CastType->isVoidType() &&
14988       RequireCompleteType(TypeRange.getBegin(), CastType,
14989                           diag::err_typecheck_cast_to_incomplete))
14990     return ExprError();
14991
14992   // Rewrite the casted expression from scratch.
14993   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14994   if (!result.isUsable()) return ExprError();
14995
14996   CastExpr = result.get();
14997   VK = CastExpr->getValueKind();
14998   CastKind = CK_NoOp;
14999
15000   return CastExpr;
15001 }
15002
15003 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15004   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15005 }
15006
15007 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15008                                     Expr *arg, QualType &paramType) {
15009   // If the syntactic form of the argument is not an explicit cast of
15010   // any sort, just do default argument promotion.
15011   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15012   if (!castArg) {
15013     ExprResult result = DefaultArgumentPromotion(arg);
15014     if (result.isInvalid()) return ExprError();
15015     paramType = result.get()->getType();
15016     return result;
15017   }
15018
15019   // Otherwise, use the type that was written in the explicit cast.
15020   assert(!arg->hasPlaceholderType());
15021   paramType = castArg->getTypeAsWritten();
15022
15023   // Copy-initialize a parameter of that type.
15024   InitializedEntity entity =
15025     InitializedEntity::InitializeParameter(Context, paramType,
15026                                            /*consumed*/ false);
15027   return PerformCopyInitialization(entity, callLoc, arg);
15028 }
15029
15030 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15031   Expr *orig = E;
15032   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15033   while (true) {
15034     E = E->IgnoreParenImpCasts();
15035     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15036       E = call->getCallee();
15037       diagID = diag::err_uncasted_call_of_unknown_any;
15038     } else {
15039       break;
15040     }
15041   }
15042
15043   SourceLocation loc;
15044   NamedDecl *d;
15045   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15046     loc = ref->getLocation();
15047     d = ref->getDecl();
15048   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15049     loc = mem->getMemberLoc();
15050     d = mem->getMemberDecl();
15051   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15052     diagID = diag::err_uncasted_call_of_unknown_any;
15053     loc = msg->getSelectorStartLoc();
15054     d = msg->getMethodDecl();
15055     if (!d) {
15056       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15057         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15058         << orig->getSourceRange();
15059       return ExprError();
15060     }
15061   } else {
15062     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15063       << E->getSourceRange();
15064     return ExprError();
15065   }
15066
15067   S.Diag(loc, diagID) << d << orig->getSourceRange();
15068
15069   // Never recoverable.
15070   return ExprError();
15071 }
15072
15073 /// Check for operands with placeholder types and complain if found.
15074 /// Returns true if there was an error and no recovery was possible.
15075 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15076   if (!getLangOpts().CPlusPlus) {
15077     // C cannot handle TypoExpr nodes on either side of a binop because it
15078     // doesn't handle dependent types properly, so make sure any TypoExprs have
15079     // been dealt with before checking the operands.
15080     ExprResult Result = CorrectDelayedTyposInExpr(E);
15081     if (!Result.isUsable()) return ExprError();
15082     E = Result.get();
15083   }
15084
15085   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15086   if (!placeholderType) return E;
15087
15088   switch (placeholderType->getKind()) {
15089
15090   // Overloaded expressions.
15091   case BuiltinType::Overload: {
15092     // Try to resolve a single function template specialization.
15093     // This is obligatory.
15094     ExprResult Result = E;
15095     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15096       return Result;
15097
15098     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15099     // leaves Result unchanged on failure.
15100     Result = E;
15101     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15102       return Result;
15103
15104     // If that failed, try to recover with a call.
15105     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15106                          /*complain*/ true);
15107     return Result;
15108   }
15109
15110   // Bound member functions.
15111   case BuiltinType::BoundMember: {
15112     ExprResult result = E;
15113     const Expr *BME = E->IgnoreParens();
15114     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15115     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15116     if (isa<CXXPseudoDestructorExpr>(BME)) {
15117       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15118     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15119       if (ME->getMemberNameInfo().getName().getNameKind() ==
15120           DeclarationName::CXXDestructorName)
15121         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15122     }
15123     tryToRecoverWithCall(result, PD,
15124                          /*complain*/ true);
15125     return result;
15126   }
15127
15128   // ARC unbridged casts.
15129   case BuiltinType::ARCUnbridgedCast: {
15130     Expr *realCast = stripARCUnbridgedCast(E);
15131     diagnoseARCUnbridgedCast(realCast);
15132     return realCast;
15133   }
15134
15135   // Expressions of unknown type.
15136   case BuiltinType::UnknownAny:
15137     return diagnoseUnknownAnyExpr(*this, E);
15138
15139   // Pseudo-objects.
15140   case BuiltinType::PseudoObject:
15141     return checkPseudoObjectRValue(E);
15142
15143   case BuiltinType::BuiltinFn: {
15144     // Accept __noop without parens by implicitly converting it to a call expr.
15145     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15146     if (DRE) {
15147       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15148       if (FD->getBuiltinID() == Builtin::BI__noop) {
15149         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15150                               CK_BuiltinFnToFnPtr).get();
15151         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15152                                       VK_RValue, SourceLocation());
15153       }
15154     }
15155
15156     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15157     return ExprError();
15158   }
15159
15160   // Expressions of unknown type.
15161   case BuiltinType::OMPArraySection:
15162     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15163     return ExprError();
15164
15165   // Everything else should be impossible.
15166 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15167   case BuiltinType::Id:
15168 #include "clang/Basic/OpenCLImageTypes.def"
15169 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15170 #define PLACEHOLDER_TYPE(Id, SingletonId)
15171 #include "clang/AST/BuiltinTypes.def"
15172     break;
15173   }
15174
15175   llvm_unreachable("invalid placeholder type!");
15176 }
15177
15178 bool Sema::CheckCaseExpression(Expr *E) {
15179   if (E->isTypeDependent())
15180     return true;
15181   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15182     return E->getType()->isIntegralOrEnumerationType();
15183   return false;
15184 }
15185
15186 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15187 ExprResult
15188 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15189   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15190          "Unknown Objective-C Boolean value!");
15191   QualType BoolT = Context.ObjCBuiltinBoolTy;
15192   if (!Context.getBOOLDecl()) {
15193     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15194                         Sema::LookupOrdinaryName);
15195     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15196       NamedDecl *ND = Result.getFoundDecl();
15197       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
15198         Context.setBOOLDecl(TD);
15199     }
15200   }
15201   if (Context.getBOOLDecl())
15202     BoolT = Context.getBOOLType();
15203   return new (Context)
15204       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15205 }
15206
15207 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15208     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15209     SourceLocation RParen) {
15210
15211   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15212
15213   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15214                            [&](const AvailabilitySpec &Spec) {
15215                              return Spec.getPlatform() == Platform;
15216                            });
15217
15218   VersionTuple Version;
15219   if (Spec != AvailSpecs.end())
15220     Version = Spec->getVersion();
15221
15222   return new (Context)
15223       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15224 }