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 Sema::ShouldDiagnoseAvailabilityOfDecl(
107     NamedDecl *&D, VersionTuple ContextVersion, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message, ContextVersion);
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, ContextVersion);
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, ContextVersion);
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, ContextVersion);
136     }
137 
138   switch (Result) {
139   case AR_Available:
140     return Result;
141 
142   case AR_Unavailable:
143   case AR_Deprecated:
144     return getCurContextAvailability() != Result ? Result : AR_Available;
145 
146   case AR_NotYetIntroduced: {
147     // Don't do this for enums, they can't be redeclared.
148     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
149       return AR_Available;
150 
151     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
152     // Objective-C method declarations in categories are not modelled as
153     // redeclarations, so manually look for a redeclaration in a category
154     // if necessary.
155     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
156       Warn = false;
157     // In general, D will point to the most recent redeclaration. However,
158     // for `@class A;` decls, this isn't true -- manually go through the
159     // redecl chain in that case.
160     if (Warn && isa<ObjCInterfaceDecl>(D))
161       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
162            Redecl = Redecl->getPreviousDecl())
163         if (!Redecl->hasAttr<AvailabilityAttr>() ||
164             Redecl->getAttr<AvailabilityAttr>()->isInherited())
165           Warn = false;
166 
167     return Warn ? AR_NotYetIntroduced : AR_Available;
168   }
169   }
170   llvm_unreachable("Unknown availability result!");
171 }
172 
173 static void
174 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
175                            const ObjCInterfaceDecl *UnknownObjCClass,
176                            bool ObjCPropertyAccess) {
177   VersionTuple ContextVersion;
178   if (const DeclContext *DC = S.getCurObjCLexicalContext())
179     ContextVersion = S.getVersionForDecl(cast<Decl>(DC));
180 
181   std::string Message;
182   // See if this declaration is unavailable, deprecated, or partial in the
183   // current context.
184   if (AvailabilityResult Result =
185           S.ShouldDiagnoseAvailabilityOfDecl(D, ContextVersion, &Message)) {
186 
187     if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
188       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
189       return;
190     }
191 
192     const ObjCPropertyDecl *ObjCPDecl = nullptr;
193     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
194       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
195         AvailabilityResult PDeclResult =
196             PD->getAvailability(nullptr, ContextVersion);
197         if (PDeclResult == Result)
198           ObjCPDecl = PD;
199       }
200     }
201 
202     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
203                               ObjCPDecl, ObjCPropertyAccess);
204   }
205 }
206 
207 /// \brief Emit a note explaining that this function is deleted.
208 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
209   assert(Decl->isDeleted());
210 
211   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
212 
213   if (Method && Method->isDeleted() && Method->isDefaulted()) {
214     // If the method was explicitly defaulted, point at that declaration.
215     if (!Method->isImplicit())
216       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
217 
218     // Try to diagnose why this special member function was implicitly
219     // deleted. This might fail, if that reason no longer applies.
220     CXXSpecialMember CSM = getSpecialMember(Method);
221     if (CSM != CXXInvalid)
222       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
223 
224     return;
225   }
226 
227   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
228   if (Ctor && Ctor->isInheritingConstructor())
229     return NoteDeletedInheritingConstructor(Ctor);
230 
231   Diag(Decl->getLocation(), diag::note_availability_specified_here)
232     << Decl << true;
233 }
234 
235 /// \brief Determine whether a FunctionDecl was ever declared with an
236 /// explicit storage class.
237 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
238   for (auto I : D->redecls()) {
239     if (I->getStorageClass() != SC_None)
240       return true;
241   }
242   return false;
243 }
244 
245 /// \brief Check whether we're in an extern inline function and referring to a
246 /// variable or function with internal linkage (C11 6.7.4p3).
247 ///
248 /// This is only a warning because we used to silently accept this code, but
249 /// in many cases it will not behave correctly. This is not enabled in C++ mode
250 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
251 /// and so while there may still be user mistakes, most of the time we can't
252 /// prove that there are errors.
253 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
254                                                       const NamedDecl *D,
255                                                       SourceLocation Loc) {
256   // This is disabled under C++; there are too many ways for this to fire in
257   // contexts where the warning is a false positive, or where it is technically
258   // correct but benign.
259   if (S.getLangOpts().CPlusPlus)
260     return;
261 
262   // Check if this is an inlined function or method.
263   FunctionDecl *Current = S.getCurFunctionDecl();
264   if (!Current)
265     return;
266   if (!Current->isInlined())
267     return;
268   if (!Current->isExternallyVisible())
269     return;
270 
271   // Check if the decl has internal linkage.
272   if (D->getFormalLinkage() != InternalLinkage)
273     return;
274 
275   // Downgrade from ExtWarn to Extension if
276   //  (1) the supposedly external inline function is in the main file,
277   //      and probably won't be included anywhere else.
278   //  (2) the thing we're referencing is a pure function.
279   //  (3) the thing we're referencing is another inline function.
280   // This last can give us false negatives, but it's better than warning on
281   // wrappers for simple C library functions.
282   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
283   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
284   if (!DowngradeWarning && UsedFn)
285     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
286 
287   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
288                                : diag::ext_internal_in_extern_inline)
289     << /*IsVar=*/!UsedFn << D;
290 
291   S.MaybeSuggestAddingStaticToDecl(Current);
292 
293   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
294       << D;
295 }
296 
297 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
298   const FunctionDecl *First = Cur->getFirstDecl();
299 
300   // Suggest "static" on the function, if possible.
301   if (!hasAnyExplicitStorageClass(First)) {
302     SourceLocation DeclBegin = First->getSourceRange().getBegin();
303     Diag(DeclBegin, diag::note_convert_inline_to_static)
304       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
305   }
306 }
307 
308 /// \brief Determine whether the use of this declaration is valid, and
309 /// emit any corresponding diagnostics.
310 ///
311 /// This routine diagnoses various problems with referencing
312 /// declarations that can occur when using a declaration. For example,
313 /// it might warn if a deprecated or unavailable declaration is being
314 /// used, or produce an error (and return true) if a C++0x deleted
315 /// function is being used.
316 ///
317 /// \returns true if there was an error (this declaration cannot be
318 /// referenced), false otherwise.
319 ///
320 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
321                              const ObjCInterfaceDecl *UnknownObjCClass,
322                              bool ObjCPropertyAccess) {
323   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
324     // If there were any diagnostics suppressed by template argument deduction,
325     // emit them now.
326     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
327     if (Pos != SuppressedDiagnostics.end()) {
328       for (const PartialDiagnosticAt &Suppressed : Pos->second)
329         Diag(Suppressed.first, Suppressed.second);
330 
331       // Clear out the list of suppressed diagnostics, so that we don't emit
332       // them again for this specialization. However, we don't obsolete this
333       // entry from the table, because we want to avoid ever emitting these
334       // diagnostics again.
335       Pos->second.clear();
336     }
337 
338     // C++ [basic.start.main]p3:
339     //   The function 'main' shall not be used within a program.
340     if (cast<FunctionDecl>(D)->isMain())
341       Diag(Loc, diag::ext_main_used);
342   }
343 
344   // See if this is an auto-typed variable whose initializer we are parsing.
345   if (ParsingInitForAutoVars.count(D)) {
346     if (isa<BindingDecl>(D)) {
347       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
348         << D->getDeclName();
349     } else {
350       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
351 
352       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
353         << D->getDeclName() << (unsigned)AT->getKeyword();
354     }
355     return true;
356   }
357 
358   // See if this is a deleted function.
359   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
360     if (FD->isDeleted()) {
361       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
362       if (Ctor && Ctor->isInheritingConstructor())
363         Diag(Loc, diag::err_deleted_inherited_ctor_use)
364             << Ctor->getParent()
365             << Ctor->getInheritedConstructor().getConstructor()->getParent();
366       else
367         Diag(Loc, diag::err_deleted_function_use);
368       NoteDeletedFunction(FD);
369       return true;
370     }
371 
372     // If the function has a deduced return type, and we can't deduce it,
373     // then we can't use it either.
374     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
375         DeduceReturnType(FD, Loc))
376       return true;
377 
378     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
379       return true;
380   }
381 
382   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
383   // Only the variables omp_in and omp_out are allowed in the combiner.
384   // Only the variables omp_priv and omp_orig are allowed in the
385   // initializer-clause.
386   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
387   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
388       isa<VarDecl>(D)) {
389     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
390         << getCurFunction()->HasOMPDeclareReductionCombiner;
391     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392     return true;
393   }
394   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
395                              ObjCPropertyAccess);
396 
397   DiagnoseUnusedOfDecl(*this, D, Loc);
398 
399   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
400 
401   return false;
402 }
403 
404 /// \brief Retrieve the message suffix that should be added to a
405 /// diagnostic complaining about the given function being deleted or
406 /// unavailable.
407 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
408   std::string Message;
409   if (FD->getAvailability(&Message))
410     return ": " + Message;
411 
412   return std::string();
413 }
414 
415 /// DiagnoseSentinelCalls - This routine checks whether a call or
416 /// message-send is to a declaration with the sentinel attribute, and
417 /// if so, it checks that the requirements of the sentinel are
418 /// satisfied.
419 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
420                                  ArrayRef<Expr *> Args) {
421   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
422   if (!attr)
423     return;
424 
425   // The number of formal parameters of the declaration.
426   unsigned numFormalParams;
427 
428   // The kind of declaration.  This is also an index into a %select in
429   // the diagnostic.
430   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
431 
432   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
433     numFormalParams = MD->param_size();
434     calleeType = CT_Method;
435   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
436     numFormalParams = FD->param_size();
437     calleeType = CT_Function;
438   } else if (isa<VarDecl>(D)) {
439     QualType type = cast<ValueDecl>(D)->getType();
440     const FunctionType *fn = nullptr;
441     if (const PointerType *ptr = type->getAs<PointerType>()) {
442       fn = ptr->getPointeeType()->getAs<FunctionType>();
443       if (!fn) return;
444       calleeType = CT_Function;
445     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
446       fn = ptr->getPointeeType()->castAs<FunctionType>();
447       calleeType = CT_Block;
448     } else {
449       return;
450     }
451 
452     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
453       numFormalParams = proto->getNumParams();
454     } else {
455       numFormalParams = 0;
456     }
457   } else {
458     return;
459   }
460 
461   // "nullPos" is the number of formal parameters at the end which
462   // effectively count as part of the variadic arguments.  This is
463   // useful if you would prefer to not have *any* formal parameters,
464   // but the language forces you to have at least one.
465   unsigned nullPos = attr->getNullPos();
466   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
467   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
468 
469   // The number of arguments which should follow the sentinel.
470   unsigned numArgsAfterSentinel = attr->getSentinel();
471 
472   // If there aren't enough arguments for all the formal parameters,
473   // the sentinel, and the args after the sentinel, complain.
474   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
475     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
476     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
477     return;
478   }
479 
480   // Otherwise, find the sentinel expression.
481   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
482   if (!sentinelExpr) return;
483   if (sentinelExpr->isValueDependent()) return;
484   if (Context.isSentinelNullExpr(sentinelExpr)) return;
485 
486   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
487   // or 'NULL' if those are actually defined in the context.  Only use
488   // 'nil' for ObjC methods, where it's much more likely that the
489   // variadic arguments form a list of object pointers.
490   SourceLocation MissingNilLoc
491     = getLocForEndOfToken(sentinelExpr->getLocEnd());
492   std::string NullValue;
493   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
494     NullValue = "nil";
495   else if (getLangOpts().CPlusPlus11)
496     NullValue = "nullptr";
497   else if (PP.isMacroDefined("NULL"))
498     NullValue = "NULL";
499   else
500     NullValue = "(void*) 0";
501 
502   if (MissingNilLoc.isInvalid())
503     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
504   else
505     Diag(MissingNilLoc, diag::warn_missing_sentinel)
506       << int(calleeType)
507       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
508   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
509 }
510 
511 SourceRange Sema::getExprRange(Expr *E) const {
512   return E ? E->getSourceRange() : SourceRange();
513 }
514 
515 //===----------------------------------------------------------------------===//
516 //  Standard Promotions and Conversions
517 //===----------------------------------------------------------------------===//
518 
519 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
520 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
521   // Handle any placeholder expressions which made it here.
522   if (E->getType()->isPlaceholderType()) {
523     ExprResult result = CheckPlaceholderExpr(E);
524     if (result.isInvalid()) return ExprError();
525     E = result.get();
526   }
527 
528   QualType Ty = E->getType();
529   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
530 
531   if (Ty->isFunctionType()) {
532     // If we are here, we are not calling a function but taking
533     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
534     if (getLangOpts().OpenCL) {
535       if (Diagnose)
536         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
537       return ExprError();
538     }
539 
540     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
541       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
542         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
543           return ExprError();
544 
545     E = ImpCastExprToType(E, Context.getPointerType(Ty),
546                           CK_FunctionToPointerDecay).get();
547   } else if (Ty->isArrayType()) {
548     // In C90 mode, arrays only promote to pointers if the array expression is
549     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
550     // type 'array of type' is converted to an expression that has type 'pointer
551     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
552     // that has type 'array of type' ...".  The relevant change is "an lvalue"
553     // (C90) to "an expression" (C99).
554     //
555     // C++ 4.2p1:
556     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
557     // T" can be converted to an rvalue of type "pointer to T".
558     //
559     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
560       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
561                             CK_ArrayToPointerDecay).get();
562   }
563   return E;
564 }
565 
566 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
567   // Check to see if we are dereferencing a null pointer.  If so,
568   // and if not volatile-qualified, this is undefined behavior that the
569   // optimizer will delete, so warn about it.  People sometimes try to use this
570   // to get a deterministic trap and are surprised by clang's behavior.  This
571   // only handles the pattern "*null", which is a very syntactic check.
572   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
573     if (UO->getOpcode() == UO_Deref &&
574         UO->getSubExpr()->IgnoreParenCasts()->
575           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
576         !UO->getType().isVolatileQualified()) {
577     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578                           S.PDiag(diag::warn_indirection_through_null)
579                             << UO->getSubExpr()->getSourceRange());
580     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
581                         S.PDiag(diag::note_indirection_through_null));
582   }
583 }
584 
585 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
586                                     SourceLocation AssignLoc,
587                                     const Expr* RHS) {
588   const ObjCIvarDecl *IV = OIRE->getDecl();
589   if (!IV)
590     return;
591 
592   DeclarationName MemberName = IV->getDeclName();
593   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
594   if (!Member || !Member->isStr("isa"))
595     return;
596 
597   const Expr *Base = OIRE->getBase();
598   QualType BaseType = Base->getType();
599   if (OIRE->isArrow())
600     BaseType = BaseType->getPointeeType();
601   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
602     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
603       ObjCInterfaceDecl *ClassDeclared = nullptr;
604       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
605       if (!ClassDeclared->getSuperClass()
606           && (*ClassDeclared->ivar_begin()) == IV) {
607         if (RHS) {
608           NamedDecl *ObjectSetClass =
609             S.LookupSingleName(S.TUScope,
610                                &S.Context.Idents.get("object_setClass"),
611                                SourceLocation(), S.LookupOrdinaryName);
612           if (ObjectSetClass) {
613             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
614             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
615             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
616             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
617                                                      AssignLoc), ",") <<
618             FixItHint::CreateInsertion(RHSLocEnd, ")");
619           }
620           else
621             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
622         } else {
623           NamedDecl *ObjectGetClass =
624             S.LookupSingleName(S.TUScope,
625                                &S.Context.Idents.get("object_getClass"),
626                                SourceLocation(), S.LookupOrdinaryName);
627           if (ObjectGetClass)
628             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
629             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
630             FixItHint::CreateReplacement(
631                                          SourceRange(OIRE->getOpLoc(),
632                                                      OIRE->getLocEnd()), ")");
633           else
634             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
635         }
636         S.Diag(IV->getLocation(), diag::note_ivar_decl);
637       }
638     }
639 }
640 
641 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
642   // Handle any placeholder expressions which made it here.
643   if (E->getType()->isPlaceholderType()) {
644     ExprResult result = CheckPlaceholderExpr(E);
645     if (result.isInvalid()) return ExprError();
646     E = result.get();
647   }
648 
649   // C++ [conv.lval]p1:
650   //   A glvalue of a non-function, non-array type T can be
651   //   converted to a prvalue.
652   if (!E->isGLValue()) return E;
653 
654   QualType T = E->getType();
655   assert(!T.isNull() && "r-value conversion on typeless expression?");
656 
657   // We don't want to throw lvalue-to-rvalue casts on top of
658   // expressions of certain types in C++.
659   if (getLangOpts().CPlusPlus &&
660       (E->getType() == Context.OverloadTy ||
661        T->isDependentType() ||
662        T->isRecordType()))
663     return E;
664 
665   // The C standard is actually really unclear on this point, and
666   // DR106 tells us what the result should be but not why.  It's
667   // generally best to say that void types just doesn't undergo
668   // lvalue-to-rvalue at all.  Note that expressions of unqualified
669   // 'void' type are never l-values, but qualified void can be.
670   if (T->isVoidType())
671     return E;
672 
673   // OpenCL usually rejects direct accesses to values of 'half' type.
674   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
675       T->isHalfType()) {
676     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
677       << 0 << T;
678     return ExprError();
679   }
680 
681   CheckForNullPointerDereference(*this, E);
682   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
683     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
684                                      &Context.Idents.get("object_getClass"),
685                                      SourceLocation(), LookupOrdinaryName);
686     if (ObjectGetClass)
687       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
688         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
689         FixItHint::CreateReplacement(
690                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
691     else
692       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
693   }
694   else if (const ObjCIvarRefExpr *OIRE =
695             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
696     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
697 
698   // C++ [conv.lval]p1:
699   //   [...] If T is a non-class type, the type of the prvalue is the
700   //   cv-unqualified version of T. Otherwise, the type of the
701   //   rvalue is T.
702   //
703   // C99 6.3.2.1p2:
704   //   If the lvalue has qualified type, the value has the unqualified
705   //   version of the type of the lvalue; otherwise, the value has the
706   //   type of the lvalue.
707   if (T.hasQualifiers())
708     T = T.getUnqualifiedType();
709 
710   // Under the MS ABI, lock down the inheritance model now.
711   if (T->isMemberPointerType() &&
712       Context.getTargetInfo().getCXXABI().isMicrosoft())
713     (void)isCompleteType(E->getExprLoc(), T);
714 
715   UpdateMarkingForLValueToRValue(E);
716 
717   // Loading a __weak object implicitly retains the value, so we need a cleanup to
718   // balance that.
719   if (getLangOpts().ObjCAutoRefCount &&
720       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
721     Cleanup.setExprNeedsCleanups(true);
722 
723   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
724                                             nullptr, VK_RValue);
725 
726   // C11 6.3.2.1p2:
727   //   ... if the lvalue has atomic type, the value has the non-atomic version
728   //   of the type of the lvalue ...
729   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
730     T = Atomic->getValueType().getUnqualifiedType();
731     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
732                                    nullptr, VK_RValue);
733   }
734 
735   return Res;
736 }
737 
738 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
739   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
740   if (Res.isInvalid())
741     return ExprError();
742   Res = DefaultLvalueConversion(Res.get());
743   if (Res.isInvalid())
744     return ExprError();
745   return Res;
746 }
747 
748 /// CallExprUnaryConversions - a special case of an unary conversion
749 /// performed on a function designator of a call expression.
750 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
751   QualType Ty = E->getType();
752   ExprResult Res = E;
753   // Only do implicit cast for a function type, but not for a pointer
754   // to function type.
755   if (Ty->isFunctionType()) {
756     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
757                             CK_FunctionToPointerDecay).get();
758     if (Res.isInvalid())
759       return ExprError();
760   }
761   Res = DefaultLvalueConversion(Res.get());
762   if (Res.isInvalid())
763     return ExprError();
764   return Res.get();
765 }
766 
767 /// UsualUnaryConversions - Performs various conversions that are common to most
768 /// operators (C99 6.3). The conversions of array and function types are
769 /// sometimes suppressed. For example, the array->pointer conversion doesn't
770 /// apply if the array is an argument to the sizeof or address (&) operators.
771 /// In these instances, this routine should *not* be called.
772 ExprResult Sema::UsualUnaryConversions(Expr *E) {
773   // First, convert to an r-value.
774   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
775   if (Res.isInvalid())
776     return ExprError();
777   E = Res.get();
778 
779   QualType Ty = E->getType();
780   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
781 
782   // Half FP have to be promoted to float unless it is natively supported
783   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
784     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
785 
786   // Try to perform integral promotions if the object has a theoretically
787   // promotable type.
788   if (Ty->isIntegralOrUnscopedEnumerationType()) {
789     // C99 6.3.1.1p2:
790     //
791     //   The following may be used in an expression wherever an int or
792     //   unsigned int may be used:
793     //     - an object or expression with an integer type whose integer
794     //       conversion rank is less than or equal to the rank of int
795     //       and unsigned int.
796     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
797     //
798     //   If an int can represent all values of the original type, the
799     //   value is converted to an int; otherwise, it is converted to an
800     //   unsigned int. These are called the integer promotions. All
801     //   other types are unchanged by the integer promotions.
802 
803     QualType PTy = Context.isPromotableBitField(E);
804     if (!PTy.isNull()) {
805       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
806       return E;
807     }
808     if (Ty->isPromotableIntegerType()) {
809       QualType PT = Context.getPromotedIntegerType(Ty);
810       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
811       return E;
812     }
813   }
814   return E;
815 }
816 
817 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
818 /// do not have a prototype. Arguments that have type float or __fp16
819 /// are promoted to double. All other argument types are converted by
820 /// UsualUnaryConversions().
821 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
822   QualType Ty = E->getType();
823   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
824 
825   ExprResult Res = UsualUnaryConversions(E);
826   if (Res.isInvalid())
827     return ExprError();
828   E = Res.get();
829 
830   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
831   // double.
832   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
833   if (BTy && (BTy->getKind() == BuiltinType::Half ||
834               BTy->getKind() == BuiltinType::Float))
835     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
836 
837   // C++ performs lvalue-to-rvalue conversion as a default argument
838   // promotion, even on class types, but note:
839   //   C++11 [conv.lval]p2:
840   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
841   //     operand or a subexpression thereof the value contained in the
842   //     referenced object is not accessed. Otherwise, if the glvalue
843   //     has a class type, the conversion copy-initializes a temporary
844   //     of type T from the glvalue and the result of the conversion
845   //     is a prvalue for the temporary.
846   // FIXME: add some way to gate this entire thing for correctness in
847   // potentially potentially evaluated contexts.
848   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
849     ExprResult Temp = PerformCopyInitialization(
850                        InitializedEntity::InitializeTemporary(E->getType()),
851                                                 E->getExprLoc(), E);
852     if (Temp.isInvalid())
853       return ExprError();
854     E = Temp.get();
855   }
856 
857   return E;
858 }
859 
860 /// Determine the degree of POD-ness for an expression.
861 /// Incomplete types are considered POD, since this check can be performed
862 /// when we're in an unevaluated context.
863 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
864   if (Ty->isIncompleteType()) {
865     // C++11 [expr.call]p7:
866     //   After these conversions, if the argument does not have arithmetic,
867     //   enumeration, pointer, pointer to member, or class type, the program
868     //   is ill-formed.
869     //
870     // Since we've already performed array-to-pointer and function-to-pointer
871     // decay, the only such type in C++ is cv void. This also handles
872     // initializer lists as variadic arguments.
873     if (Ty->isVoidType())
874       return VAK_Invalid;
875 
876     if (Ty->isObjCObjectType())
877       return VAK_Invalid;
878     return VAK_Valid;
879   }
880 
881   if (Ty.isCXX98PODType(Context))
882     return VAK_Valid;
883 
884   // C++11 [expr.call]p7:
885   //   Passing a potentially-evaluated argument of class type (Clause 9)
886   //   having a non-trivial copy constructor, a non-trivial move constructor,
887   //   or a non-trivial destructor, with no corresponding parameter,
888   //   is conditionally-supported with implementation-defined semantics.
889   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
890     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
891       if (!Record->hasNonTrivialCopyConstructor() &&
892           !Record->hasNonTrivialMoveConstructor() &&
893           !Record->hasNonTrivialDestructor())
894         return VAK_ValidInCXX11;
895 
896   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
897     return VAK_Valid;
898 
899   if (Ty->isObjCObjectType())
900     return VAK_Invalid;
901 
902   if (getLangOpts().MSVCCompat)
903     return VAK_MSVCUndefined;
904 
905   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
906   // permitted to reject them. We should consider doing so.
907   return VAK_Undefined;
908 }
909 
910 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
911   // Don't allow one to pass an Objective-C interface to a vararg.
912   const QualType &Ty = E->getType();
913   VarArgKind VAK = isValidVarArgType(Ty);
914 
915   // Complain about passing non-POD types through varargs.
916   switch (VAK) {
917   case VAK_ValidInCXX11:
918     DiagRuntimeBehavior(
919         E->getLocStart(), nullptr,
920         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
921           << Ty << CT);
922     // Fall through.
923   case VAK_Valid:
924     if (Ty->isRecordType()) {
925       // This is unlikely to be what the user intended. If the class has a
926       // 'c_str' member function, the user probably meant to call that.
927       DiagRuntimeBehavior(E->getLocStart(), nullptr,
928                           PDiag(diag::warn_pass_class_arg_to_vararg)
929                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
930     }
931     break;
932 
933   case VAK_Undefined:
934   case VAK_MSVCUndefined:
935     DiagRuntimeBehavior(
936         E->getLocStart(), nullptr,
937         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
938           << getLangOpts().CPlusPlus11 << Ty << CT);
939     break;
940 
941   case VAK_Invalid:
942     if (Ty->isObjCObjectType())
943       DiagRuntimeBehavior(
944           E->getLocStart(), nullptr,
945           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
946             << Ty << CT);
947     else
948       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
949         << isa<InitListExpr>(E) << Ty << CT;
950     break;
951   }
952 }
953 
954 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
955 /// will create a trap if the resulting type is not a POD type.
956 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
957                                                   FunctionDecl *FDecl) {
958   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
959     // Strip the unbridged-cast placeholder expression off, if applicable.
960     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
961         (CT == VariadicMethod ||
962          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
963       E = stripARCUnbridgedCast(E);
964 
965     // Otherwise, do normal placeholder checking.
966     } else {
967       ExprResult ExprRes = CheckPlaceholderExpr(E);
968       if (ExprRes.isInvalid())
969         return ExprError();
970       E = ExprRes.get();
971     }
972   }
973 
974   ExprResult ExprRes = DefaultArgumentPromotion(E);
975   if (ExprRes.isInvalid())
976     return ExprError();
977   E = ExprRes.get();
978 
979   // Diagnostics regarding non-POD argument types are
980   // emitted along with format string checking in Sema::CheckFunctionCall().
981   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
982     // Turn this into a trap.
983     CXXScopeSpec SS;
984     SourceLocation TemplateKWLoc;
985     UnqualifiedId Name;
986     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
987                        E->getLocStart());
988     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
989                                           Name, true, false);
990     if (TrapFn.isInvalid())
991       return ExprError();
992 
993     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
994                                     E->getLocStart(), None,
995                                     E->getLocEnd());
996     if (Call.isInvalid())
997       return ExprError();
998 
999     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1000                                   Call.get(), E);
1001     if (Comma.isInvalid())
1002       return ExprError();
1003     return Comma.get();
1004   }
1005 
1006   if (!getLangOpts().CPlusPlus &&
1007       RequireCompleteType(E->getExprLoc(), E->getType(),
1008                           diag::err_call_incomplete_argument))
1009     return ExprError();
1010 
1011   return E;
1012 }
1013 
1014 /// \brief Converts an integer to complex float type.  Helper function of
1015 /// UsualArithmeticConversions()
1016 ///
1017 /// \return false if the integer expression is an integer type and is
1018 /// successfully converted to the complex type.
1019 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1020                                                   ExprResult &ComplexExpr,
1021                                                   QualType IntTy,
1022                                                   QualType ComplexTy,
1023                                                   bool SkipCast) {
1024   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1025   if (SkipCast) return false;
1026   if (IntTy->isIntegerType()) {
1027     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1028     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1029     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1030                                   CK_FloatingRealToComplex);
1031   } else {
1032     assert(IntTy->isComplexIntegerType());
1033     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1034                                   CK_IntegralComplexToFloatingComplex);
1035   }
1036   return false;
1037 }
1038 
1039 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1040 /// UsualArithmeticConversions()
1041 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1042                                              ExprResult &RHS, QualType LHSType,
1043                                              QualType RHSType,
1044                                              bool IsCompAssign) {
1045   // if we have an integer operand, the result is the complex type.
1046   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1047                                              /*skipCast*/false))
1048     return LHSType;
1049   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1050                                              /*skipCast*/IsCompAssign))
1051     return RHSType;
1052 
1053   // This handles complex/complex, complex/float, or float/complex.
1054   // When both operands are complex, the shorter operand is converted to the
1055   // type of the longer, and that is the type of the result. This corresponds
1056   // to what is done when combining two real floating-point operands.
1057   // The fun begins when size promotion occur across type domains.
1058   // From H&S 6.3.4: When one operand is complex and the other is a real
1059   // floating-point type, the less precise type is converted, within it's
1060   // real or complex domain, to the precision of the other type. For example,
1061   // when combining a "long double" with a "double _Complex", the
1062   // "double _Complex" is promoted to "long double _Complex".
1063 
1064   // Compute the rank of the two types, regardless of whether they are complex.
1065   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1066 
1067   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1068   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1069   QualType LHSElementType =
1070       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1071   QualType RHSElementType =
1072       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1073 
1074   QualType ResultType = S.Context.getComplexType(LHSElementType);
1075   if (Order < 0) {
1076     // Promote the precision of the LHS if not an assignment.
1077     ResultType = S.Context.getComplexType(RHSElementType);
1078     if (!IsCompAssign) {
1079       if (LHSComplexType)
1080         LHS =
1081             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1082       else
1083         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1084     }
1085   } else if (Order > 0) {
1086     // Promote the precision of the RHS.
1087     if (RHSComplexType)
1088       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1089     else
1090       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1091   }
1092   return ResultType;
1093 }
1094 
1095 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1096 /// of UsualArithmeticConversions()
1097 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1098                                            ExprResult &IntExpr,
1099                                            QualType FloatTy, QualType IntTy,
1100                                            bool ConvertFloat, bool ConvertInt) {
1101   if (IntTy->isIntegerType()) {
1102     if (ConvertInt)
1103       // Convert intExpr to the lhs floating point type.
1104       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1105                                     CK_IntegralToFloating);
1106     return FloatTy;
1107   }
1108 
1109   // Convert both sides to the appropriate complex float.
1110   assert(IntTy->isComplexIntegerType());
1111   QualType result = S.Context.getComplexType(FloatTy);
1112 
1113   // _Complex int -> _Complex float
1114   if (ConvertInt)
1115     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1116                                   CK_IntegralComplexToFloatingComplex);
1117 
1118   // float -> _Complex float
1119   if (ConvertFloat)
1120     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1121                                     CK_FloatingRealToComplex);
1122 
1123   return result;
1124 }
1125 
1126 /// \brief Handle arithmethic conversion with floating point types.  Helper
1127 /// function of UsualArithmeticConversions()
1128 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1129                                       ExprResult &RHS, QualType LHSType,
1130                                       QualType RHSType, bool IsCompAssign) {
1131   bool LHSFloat = LHSType->isRealFloatingType();
1132   bool RHSFloat = RHSType->isRealFloatingType();
1133 
1134   // If we have two real floating types, convert the smaller operand
1135   // to the bigger result.
1136   if (LHSFloat && RHSFloat) {
1137     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1138     if (order > 0) {
1139       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1140       return LHSType;
1141     }
1142 
1143     assert(order < 0 && "illegal float comparison");
1144     if (!IsCompAssign)
1145       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1146     return RHSType;
1147   }
1148 
1149   if (LHSFloat) {
1150     // Half FP has to be promoted to float unless it is natively supported
1151     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1152       LHSType = S.Context.FloatTy;
1153 
1154     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1155                                       /*convertFloat=*/!IsCompAssign,
1156                                       /*convertInt=*/ true);
1157   }
1158   assert(RHSFloat);
1159   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1160                                     /*convertInt=*/ true,
1161                                     /*convertFloat=*/!IsCompAssign);
1162 }
1163 
1164 /// \brief Diagnose attempts to convert between __float128 and long double if
1165 /// there is no support for such conversion. Helper function of
1166 /// UsualArithmeticConversions().
1167 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1168                                       QualType RHSType) {
1169   /*  No issue converting if at least one of the types is not a floating point
1170       type or the two types have the same rank.
1171   */
1172   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1173       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1174     return false;
1175 
1176   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1177          "The remaining types must be floating point types.");
1178 
1179   auto *LHSComplex = LHSType->getAs<ComplexType>();
1180   auto *RHSComplex = RHSType->getAs<ComplexType>();
1181 
1182   QualType LHSElemType = LHSComplex ?
1183     LHSComplex->getElementType() : LHSType;
1184   QualType RHSElemType = RHSComplex ?
1185     RHSComplex->getElementType() : RHSType;
1186 
1187   // No issue if the two types have the same representation
1188   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1189       &S.Context.getFloatTypeSemantics(RHSElemType))
1190     return false;
1191 
1192   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1193                                 RHSElemType == S.Context.LongDoubleTy);
1194   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1195                             RHSElemType == S.Context.Float128Ty);
1196 
1197   /* We've handled the situation where __float128 and long double have the same
1198      representation. The only other allowable conversion is if long double is
1199      really just double.
1200   */
1201   return Float128AndLongDouble &&
1202     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1203      &llvm::APFloat::IEEEdouble);
1204 }
1205 
1206 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1207 
1208 namespace {
1209 /// These helper callbacks are placed in an anonymous namespace to
1210 /// permit their use as function template parameters.
1211 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1212   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1213 }
1214 
1215 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1216   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1217                              CK_IntegralComplexCast);
1218 }
1219 }
1220 
1221 /// \brief Handle integer arithmetic conversions.  Helper function of
1222 /// UsualArithmeticConversions()
1223 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1224 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1225                                         ExprResult &RHS, QualType LHSType,
1226                                         QualType RHSType, bool IsCompAssign) {
1227   // The rules for this case are in C99 6.3.1.8
1228   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1229   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1230   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1231   if (LHSSigned == RHSSigned) {
1232     // Same signedness; use the higher-ranked type
1233     if (order >= 0) {
1234       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1235       return LHSType;
1236     } else if (!IsCompAssign)
1237       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1238     return RHSType;
1239   } else if (order != (LHSSigned ? 1 : -1)) {
1240     // The unsigned type has greater than or equal rank to the
1241     // signed type, so use the unsigned type
1242     if (RHSSigned) {
1243       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1244       return LHSType;
1245     } else if (!IsCompAssign)
1246       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1247     return RHSType;
1248   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1249     // The two types are different widths; if we are here, that
1250     // means the signed type is larger than the unsigned type, so
1251     // use the signed type.
1252     if (LHSSigned) {
1253       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1254       return LHSType;
1255     } else if (!IsCompAssign)
1256       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1257     return RHSType;
1258   } else {
1259     // The signed type is higher-ranked than the unsigned type,
1260     // but isn't actually any bigger (like unsigned int and long
1261     // on most 32-bit systems).  Use the unsigned type corresponding
1262     // to the signed type.
1263     QualType result =
1264       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1265     RHS = (*doRHSCast)(S, RHS.get(), result);
1266     if (!IsCompAssign)
1267       LHS = (*doLHSCast)(S, LHS.get(), result);
1268     return result;
1269   }
1270 }
1271 
1272 /// \brief Handle conversions with GCC complex int extension.  Helper function
1273 /// of UsualArithmeticConversions()
1274 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1275                                            ExprResult &RHS, QualType LHSType,
1276                                            QualType RHSType,
1277                                            bool IsCompAssign) {
1278   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1279   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1280 
1281   if (LHSComplexInt && RHSComplexInt) {
1282     QualType LHSEltType = LHSComplexInt->getElementType();
1283     QualType RHSEltType = RHSComplexInt->getElementType();
1284     QualType ScalarType =
1285       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1286         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1287 
1288     return S.Context.getComplexType(ScalarType);
1289   }
1290 
1291   if (LHSComplexInt) {
1292     QualType LHSEltType = LHSComplexInt->getElementType();
1293     QualType ScalarType =
1294       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1295         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1296     QualType ComplexType = S.Context.getComplexType(ScalarType);
1297     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1298                               CK_IntegralRealToComplex);
1299 
1300     return ComplexType;
1301   }
1302 
1303   assert(RHSComplexInt);
1304 
1305   QualType RHSEltType = RHSComplexInt->getElementType();
1306   QualType ScalarType =
1307     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1308       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1309   QualType ComplexType = S.Context.getComplexType(ScalarType);
1310 
1311   if (!IsCompAssign)
1312     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1313                               CK_IntegralRealToComplex);
1314   return ComplexType;
1315 }
1316 
1317 /// UsualArithmeticConversions - Performs various conversions that are common to
1318 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1319 /// routine returns the first non-arithmetic type found. The client is
1320 /// responsible for emitting appropriate error diagnostics.
1321 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1322                                           bool IsCompAssign) {
1323   if (!IsCompAssign) {
1324     LHS = UsualUnaryConversions(LHS.get());
1325     if (LHS.isInvalid())
1326       return QualType();
1327   }
1328 
1329   RHS = UsualUnaryConversions(RHS.get());
1330   if (RHS.isInvalid())
1331     return QualType();
1332 
1333   // For conversion purposes, we ignore any qualifiers.
1334   // For example, "const float" and "float" are equivalent.
1335   QualType LHSType =
1336     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1337   QualType RHSType =
1338     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1339 
1340   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1341   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1342     LHSType = AtomicLHS->getValueType();
1343 
1344   // If both types are identical, no conversion is needed.
1345   if (LHSType == RHSType)
1346     return LHSType;
1347 
1348   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1349   // The caller can deal with this (e.g. pointer + int).
1350   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1351     return QualType();
1352 
1353   // Apply unary and bitfield promotions to the LHS's type.
1354   QualType LHSUnpromotedType = LHSType;
1355   if (LHSType->isPromotableIntegerType())
1356     LHSType = Context.getPromotedIntegerType(LHSType);
1357   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1358   if (!LHSBitfieldPromoteTy.isNull())
1359     LHSType = LHSBitfieldPromoteTy;
1360   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1361     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1362 
1363   // If both types are identical, no conversion is needed.
1364   if (LHSType == RHSType)
1365     return LHSType;
1366 
1367   // At this point, we have two different arithmetic types.
1368 
1369   // Diagnose attempts to convert between __float128 and long double where
1370   // such conversions currently can't be handled.
1371   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1372     return QualType();
1373 
1374   // Handle complex types first (C99 6.3.1.8p1).
1375   if (LHSType->isComplexType() || RHSType->isComplexType())
1376     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1377                                         IsCompAssign);
1378 
1379   // Now handle "real" floating types (i.e. float, double, long double).
1380   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1381     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1382                                  IsCompAssign);
1383 
1384   // Handle GCC complex int extension.
1385   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1386     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1387                                       IsCompAssign);
1388 
1389   // Finally, we have two differing integer types.
1390   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1391            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1392 }
1393 
1394 
1395 //===----------------------------------------------------------------------===//
1396 //  Semantic Analysis for various Expression Types
1397 //===----------------------------------------------------------------------===//
1398 
1399 
1400 ExprResult
1401 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1402                                 SourceLocation DefaultLoc,
1403                                 SourceLocation RParenLoc,
1404                                 Expr *ControllingExpr,
1405                                 ArrayRef<ParsedType> ArgTypes,
1406                                 ArrayRef<Expr *> ArgExprs) {
1407   unsigned NumAssocs = ArgTypes.size();
1408   assert(NumAssocs == ArgExprs.size());
1409 
1410   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1411   for (unsigned i = 0; i < NumAssocs; ++i) {
1412     if (ArgTypes[i])
1413       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1414     else
1415       Types[i] = nullptr;
1416   }
1417 
1418   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1419                                              ControllingExpr,
1420                                              llvm::makeArrayRef(Types, NumAssocs),
1421                                              ArgExprs);
1422   delete [] Types;
1423   return ER;
1424 }
1425 
1426 ExprResult
1427 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1428                                  SourceLocation DefaultLoc,
1429                                  SourceLocation RParenLoc,
1430                                  Expr *ControllingExpr,
1431                                  ArrayRef<TypeSourceInfo *> Types,
1432                                  ArrayRef<Expr *> Exprs) {
1433   unsigned NumAssocs = Types.size();
1434   assert(NumAssocs == Exprs.size());
1435 
1436   // Decay and strip qualifiers for the controlling expression type, and handle
1437   // placeholder type replacement. See committee discussion from WG14 DR423.
1438   {
1439     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1440     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1441     if (R.isInvalid())
1442       return ExprError();
1443     ControllingExpr = R.get();
1444   }
1445 
1446   // The controlling expression is an unevaluated operand, so side effects are
1447   // likely unintended.
1448   if (ActiveTemplateInstantiations.empty() &&
1449       ControllingExpr->HasSideEffects(Context, false))
1450     Diag(ControllingExpr->getExprLoc(),
1451          diag::warn_side_effects_unevaluated_context);
1452 
1453   bool TypeErrorFound = false,
1454        IsResultDependent = ControllingExpr->isTypeDependent(),
1455        ContainsUnexpandedParameterPack
1456          = ControllingExpr->containsUnexpandedParameterPack();
1457 
1458   for (unsigned i = 0; i < NumAssocs; ++i) {
1459     if (Exprs[i]->containsUnexpandedParameterPack())
1460       ContainsUnexpandedParameterPack = true;
1461 
1462     if (Types[i]) {
1463       if (Types[i]->getType()->containsUnexpandedParameterPack())
1464         ContainsUnexpandedParameterPack = true;
1465 
1466       if (Types[i]->getType()->isDependentType()) {
1467         IsResultDependent = true;
1468       } else {
1469         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1470         // complete object type other than a variably modified type."
1471         unsigned D = 0;
1472         if (Types[i]->getType()->isIncompleteType())
1473           D = diag::err_assoc_type_incomplete;
1474         else if (!Types[i]->getType()->isObjectType())
1475           D = diag::err_assoc_type_nonobject;
1476         else if (Types[i]->getType()->isVariablyModifiedType())
1477           D = diag::err_assoc_type_variably_modified;
1478 
1479         if (D != 0) {
1480           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1481             << Types[i]->getTypeLoc().getSourceRange()
1482             << Types[i]->getType();
1483           TypeErrorFound = true;
1484         }
1485 
1486         // C11 6.5.1.1p2 "No two generic associations in the same generic
1487         // selection shall specify compatible types."
1488         for (unsigned j = i+1; j < NumAssocs; ++j)
1489           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1490               Context.typesAreCompatible(Types[i]->getType(),
1491                                          Types[j]->getType())) {
1492             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1493                  diag::err_assoc_compatible_types)
1494               << Types[j]->getTypeLoc().getSourceRange()
1495               << Types[j]->getType()
1496               << Types[i]->getType();
1497             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1498                  diag::note_compat_assoc)
1499               << Types[i]->getTypeLoc().getSourceRange()
1500               << Types[i]->getType();
1501             TypeErrorFound = true;
1502           }
1503       }
1504     }
1505   }
1506   if (TypeErrorFound)
1507     return ExprError();
1508 
1509   // If we determined that the generic selection is result-dependent, don't
1510   // try to compute the result expression.
1511   if (IsResultDependent)
1512     return new (Context) GenericSelectionExpr(
1513         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1514         ContainsUnexpandedParameterPack);
1515 
1516   SmallVector<unsigned, 1> CompatIndices;
1517   unsigned DefaultIndex = -1U;
1518   for (unsigned i = 0; i < NumAssocs; ++i) {
1519     if (!Types[i])
1520       DefaultIndex = i;
1521     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1522                                         Types[i]->getType()))
1523       CompatIndices.push_back(i);
1524   }
1525 
1526   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1527   // type compatible with at most one of the types named in its generic
1528   // association list."
1529   if (CompatIndices.size() > 1) {
1530     // We strip parens here because the controlling expression is typically
1531     // parenthesized in macro definitions.
1532     ControllingExpr = ControllingExpr->IgnoreParens();
1533     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1534       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1535       << (unsigned) CompatIndices.size();
1536     for (unsigned I : CompatIndices) {
1537       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1538            diag::note_compat_assoc)
1539         << Types[I]->getTypeLoc().getSourceRange()
1540         << Types[I]->getType();
1541     }
1542     return ExprError();
1543   }
1544 
1545   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1546   // its controlling expression shall have type compatible with exactly one of
1547   // the types named in its generic association list."
1548   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1549     // We strip parens here because the controlling expression is typically
1550     // parenthesized in macro definitions.
1551     ControllingExpr = ControllingExpr->IgnoreParens();
1552     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1553       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1554     return ExprError();
1555   }
1556 
1557   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1558   // type name that is compatible with the type of the controlling expression,
1559   // then the result expression of the generic selection is the expression
1560   // in that generic association. Otherwise, the result expression of the
1561   // generic selection is the expression in the default generic association."
1562   unsigned ResultIndex =
1563     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1564 
1565   return new (Context) GenericSelectionExpr(
1566       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1567       ContainsUnexpandedParameterPack, ResultIndex);
1568 }
1569 
1570 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1571 /// location of the token and the offset of the ud-suffix within it.
1572 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1573                                      unsigned Offset) {
1574   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1575                                         S.getLangOpts());
1576 }
1577 
1578 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1579 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1580 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1581                                                  IdentifierInfo *UDSuffix,
1582                                                  SourceLocation UDSuffixLoc,
1583                                                  ArrayRef<Expr*> Args,
1584                                                  SourceLocation LitEndLoc) {
1585   assert(Args.size() <= 2 && "too many arguments for literal operator");
1586 
1587   QualType ArgTy[2];
1588   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1589     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1590     if (ArgTy[ArgIdx]->isArrayType())
1591       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1592   }
1593 
1594   DeclarationName OpName =
1595     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1596   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1597   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1598 
1599   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1600   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1601                               /*AllowRaw*/false, /*AllowTemplate*/false,
1602                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1603     return ExprError();
1604 
1605   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1606 }
1607 
1608 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1609 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1610 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1611 /// multiple tokens.  However, the common case is that StringToks points to one
1612 /// string.
1613 ///
1614 ExprResult
1615 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1616   assert(!StringToks.empty() && "Must have at least one string!");
1617 
1618   StringLiteralParser Literal(StringToks, PP);
1619   if (Literal.hadError)
1620     return ExprError();
1621 
1622   SmallVector<SourceLocation, 4> StringTokLocs;
1623   for (const Token &Tok : StringToks)
1624     StringTokLocs.push_back(Tok.getLocation());
1625 
1626   QualType CharTy = Context.CharTy;
1627   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1628   if (Literal.isWide()) {
1629     CharTy = Context.getWideCharType();
1630     Kind = StringLiteral::Wide;
1631   } else if (Literal.isUTF8()) {
1632     Kind = StringLiteral::UTF8;
1633   } else if (Literal.isUTF16()) {
1634     CharTy = Context.Char16Ty;
1635     Kind = StringLiteral::UTF16;
1636   } else if (Literal.isUTF32()) {
1637     CharTy = Context.Char32Ty;
1638     Kind = StringLiteral::UTF32;
1639   } else if (Literal.isPascal()) {
1640     CharTy = Context.UnsignedCharTy;
1641   }
1642 
1643   QualType CharTyConst = CharTy;
1644   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1645   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1646     CharTyConst.addConst();
1647 
1648   // Get an array type for the string, according to C99 6.4.5.  This includes
1649   // the nul terminator character as well as the string length for pascal
1650   // strings.
1651   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1652                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1653                                  ArrayType::Normal, 0);
1654 
1655   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1656   if (getLangOpts().OpenCL) {
1657     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1658   }
1659 
1660   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1661   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1662                                              Kind, Literal.Pascal, StrTy,
1663                                              &StringTokLocs[0],
1664                                              StringTokLocs.size());
1665   if (Literal.getUDSuffix().empty())
1666     return Lit;
1667 
1668   // We're building a user-defined literal.
1669   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1670   SourceLocation UDSuffixLoc =
1671     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1672                    Literal.getUDSuffixOffset());
1673 
1674   // Make sure we're allowed user-defined literals here.
1675   if (!UDLScope)
1676     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1677 
1678   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1679   //   operator "" X (str, len)
1680   QualType SizeType = Context.getSizeType();
1681 
1682   DeclarationName OpName =
1683     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1684   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1685   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1686 
1687   QualType ArgTy[] = {
1688     Context.getArrayDecayedType(StrTy), SizeType
1689   };
1690 
1691   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1692   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1693                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1694                                 /*AllowStringTemplate*/true)) {
1695 
1696   case LOLR_Cooked: {
1697     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1698     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1699                                                     StringTokLocs[0]);
1700     Expr *Args[] = { Lit, LenArg };
1701 
1702     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1703   }
1704 
1705   case LOLR_StringTemplate: {
1706     TemplateArgumentListInfo ExplicitArgs;
1707 
1708     unsigned CharBits = Context.getIntWidth(CharTy);
1709     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1710     llvm::APSInt Value(CharBits, CharIsUnsigned);
1711 
1712     TemplateArgument TypeArg(CharTy);
1713     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1714     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1715 
1716     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1717       Value = Lit->getCodeUnit(I);
1718       TemplateArgument Arg(Context, Value, CharTy);
1719       TemplateArgumentLocInfo ArgInfo;
1720       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1721     }
1722     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1723                                     &ExplicitArgs);
1724   }
1725   case LOLR_Raw:
1726   case LOLR_Template:
1727     llvm_unreachable("unexpected literal operator lookup result");
1728   case LOLR_Error:
1729     return ExprError();
1730   }
1731   llvm_unreachable("unexpected literal operator lookup result");
1732 }
1733 
1734 ExprResult
1735 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1736                        SourceLocation Loc,
1737                        const CXXScopeSpec *SS) {
1738   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1739   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1740 }
1741 
1742 /// BuildDeclRefExpr - Build an expression that references a
1743 /// declaration that does not require a closure capture.
1744 ExprResult
1745 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1746                        const DeclarationNameInfo &NameInfo,
1747                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1748                        const TemplateArgumentListInfo *TemplateArgs) {
1749   bool RefersToCapturedVariable =
1750       isa<VarDecl>(D) &&
1751       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1752 
1753   DeclRefExpr *E;
1754   if (isa<VarTemplateSpecializationDecl>(D)) {
1755     VarTemplateSpecializationDecl *VarSpec =
1756         cast<VarTemplateSpecializationDecl>(D);
1757 
1758     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1759                                         : NestedNameSpecifierLoc(),
1760                             VarSpec->getTemplateKeywordLoc(), D,
1761                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1762                             FoundD, TemplateArgs);
1763   } else {
1764     assert(!TemplateArgs && "No template arguments for non-variable"
1765                             " template specialization references");
1766     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1767                                         : NestedNameSpecifierLoc(),
1768                             SourceLocation(), D, RefersToCapturedVariable,
1769                             NameInfo, Ty, VK, FoundD);
1770   }
1771 
1772   MarkDeclRefReferenced(E);
1773 
1774   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1775       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1776       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1777       recordUseOfEvaluatedWeak(E);
1778 
1779   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1780     UnusedPrivateFields.remove(FD);
1781     // Just in case we're building an illegal pointer-to-member.
1782     if (FD->isBitField())
1783       E->setObjectKind(OK_BitField);
1784   }
1785 
1786   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1787   // designates a bit-field.
1788   if (auto *BD = dyn_cast<BindingDecl>(D))
1789     if (auto *BE = BD->getBinding())
1790       E->setObjectKind(BE->getObjectKind());
1791 
1792   return E;
1793 }
1794 
1795 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1796 /// possibly a list of template arguments.
1797 ///
1798 /// If this produces template arguments, it is permitted to call
1799 /// DecomposeTemplateName.
1800 ///
1801 /// This actually loses a lot of source location information for
1802 /// non-standard name kinds; we should consider preserving that in
1803 /// some way.
1804 void
1805 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1806                              TemplateArgumentListInfo &Buffer,
1807                              DeclarationNameInfo &NameInfo,
1808                              const TemplateArgumentListInfo *&TemplateArgs) {
1809   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1810     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1811     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1812 
1813     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1814                                        Id.TemplateId->NumArgs);
1815     translateTemplateArguments(TemplateArgsPtr, Buffer);
1816 
1817     TemplateName TName = Id.TemplateId->Template.get();
1818     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1819     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1820     TemplateArgs = &Buffer;
1821   } else {
1822     NameInfo = GetNameFromUnqualifiedId(Id);
1823     TemplateArgs = nullptr;
1824   }
1825 }
1826 
1827 static void emitEmptyLookupTypoDiagnostic(
1828     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1829     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1830     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1831   DeclContext *Ctx =
1832       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1833   if (!TC) {
1834     // Emit a special diagnostic for failed member lookups.
1835     // FIXME: computing the declaration context might fail here (?)
1836     if (Ctx)
1837       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1838                                                  << SS.getRange();
1839     else
1840       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1841     return;
1842   }
1843 
1844   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1845   bool DroppedSpecifier =
1846       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1847   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1848                         ? diag::note_implicit_param_decl
1849                         : diag::note_previous_decl;
1850   if (!Ctx)
1851     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1852                          SemaRef.PDiag(NoteID));
1853   else
1854     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1855                                  << Typo << Ctx << DroppedSpecifier
1856                                  << SS.getRange(),
1857                          SemaRef.PDiag(NoteID));
1858 }
1859 
1860 /// Diagnose an empty lookup.
1861 ///
1862 /// \return false if new lookup candidates were found
1863 bool
1864 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1865                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1866                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1867                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1868   DeclarationName Name = R.getLookupName();
1869 
1870   unsigned diagnostic = diag::err_undeclared_var_use;
1871   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1872   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1873       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1874       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1875     diagnostic = diag::err_undeclared_use;
1876     diagnostic_suggest = diag::err_undeclared_use_suggest;
1877   }
1878 
1879   // If the original lookup was an unqualified lookup, fake an
1880   // unqualified lookup.  This is useful when (for example) the
1881   // original lookup would not have found something because it was a
1882   // dependent name.
1883   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1884   while (DC) {
1885     if (isa<CXXRecordDecl>(DC)) {
1886       LookupQualifiedName(R, DC);
1887 
1888       if (!R.empty()) {
1889         // Don't give errors about ambiguities in this lookup.
1890         R.suppressDiagnostics();
1891 
1892         // During a default argument instantiation the CurContext points
1893         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1894         // function parameter list, hence add an explicit check.
1895         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1896                               ActiveTemplateInstantiations.back().Kind ==
1897             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1898         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1899         bool isInstance = CurMethod &&
1900                           CurMethod->isInstance() &&
1901                           DC == CurMethod->getParent() && !isDefaultArgument;
1902 
1903         // Give a code modification hint to insert 'this->'.
1904         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1905         // Actually quite difficult!
1906         if (getLangOpts().MSVCCompat)
1907           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1908         if (isInstance) {
1909           Diag(R.getNameLoc(), diagnostic) << Name
1910             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1911           CheckCXXThisCapture(R.getNameLoc());
1912         } else {
1913           Diag(R.getNameLoc(), diagnostic) << Name;
1914         }
1915 
1916         // Do we really want to note all of these?
1917         for (NamedDecl *D : R)
1918           Diag(D->getLocation(), diag::note_dependent_var_use);
1919 
1920         // Return true if we are inside a default argument instantiation
1921         // and the found name refers to an instance member function, otherwise
1922         // the function calling DiagnoseEmptyLookup will try to create an
1923         // implicit member call and this is wrong for default argument.
1924         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1925           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1926           return true;
1927         }
1928 
1929         // Tell the callee to try to recover.
1930         return false;
1931       }
1932 
1933       R.clear();
1934     }
1935 
1936     // In Microsoft mode, if we are performing lookup from within a friend
1937     // function definition declared at class scope then we must set
1938     // DC to the lexical parent to be able to search into the parent
1939     // class.
1940     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1941         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1942         DC->getLexicalParent()->isRecord())
1943       DC = DC->getLexicalParent();
1944     else
1945       DC = DC->getParent();
1946   }
1947 
1948   // We didn't find anything, so try to correct for a typo.
1949   TypoCorrection Corrected;
1950   if (S && Out) {
1951     SourceLocation TypoLoc = R.getNameLoc();
1952     assert(!ExplicitTemplateArgs &&
1953            "Diagnosing an empty lookup with explicit template args!");
1954     *Out = CorrectTypoDelayed(
1955         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1956         [=](const TypoCorrection &TC) {
1957           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1958                                         diagnostic, diagnostic_suggest);
1959         },
1960         nullptr, CTK_ErrorRecovery);
1961     if (*Out)
1962       return true;
1963   } else if (S && (Corrected =
1964                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1965                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1966     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1967     bool DroppedSpecifier =
1968         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1969     R.setLookupName(Corrected.getCorrection());
1970 
1971     bool AcceptableWithRecovery = false;
1972     bool AcceptableWithoutRecovery = false;
1973     NamedDecl *ND = Corrected.getFoundDecl();
1974     if (ND) {
1975       if (Corrected.isOverloaded()) {
1976         OverloadCandidateSet OCS(R.getNameLoc(),
1977                                  OverloadCandidateSet::CSK_Normal);
1978         OverloadCandidateSet::iterator Best;
1979         for (NamedDecl *CD : Corrected) {
1980           if (FunctionTemplateDecl *FTD =
1981                    dyn_cast<FunctionTemplateDecl>(CD))
1982             AddTemplateOverloadCandidate(
1983                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1984                 Args, OCS);
1985           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1986             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1987               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1988                                    Args, OCS);
1989         }
1990         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1991         case OR_Success:
1992           ND = Best->FoundDecl;
1993           Corrected.setCorrectionDecl(ND);
1994           break;
1995         default:
1996           // FIXME: Arbitrarily pick the first declaration for the note.
1997           Corrected.setCorrectionDecl(ND);
1998           break;
1999         }
2000       }
2001       R.addDecl(ND);
2002       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2003         CXXRecordDecl *Record = nullptr;
2004         if (Corrected.getCorrectionSpecifier()) {
2005           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2006           Record = Ty->getAsCXXRecordDecl();
2007         }
2008         if (!Record)
2009           Record = cast<CXXRecordDecl>(
2010               ND->getDeclContext()->getRedeclContext());
2011         R.setNamingClass(Record);
2012       }
2013 
2014       auto *UnderlyingND = ND->getUnderlyingDecl();
2015       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2016                                isa<FunctionTemplateDecl>(UnderlyingND);
2017       // FIXME: If we ended up with a typo for a type name or
2018       // Objective-C class name, we're in trouble because the parser
2019       // is in the wrong place to recover. Suggest the typo
2020       // correction, but don't make it a fix-it since we're not going
2021       // to recover well anyway.
2022       AcceptableWithoutRecovery =
2023           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2024     } else {
2025       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2026       // because we aren't able to recover.
2027       AcceptableWithoutRecovery = true;
2028     }
2029 
2030     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2031       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2032                             ? diag::note_implicit_param_decl
2033                             : diag::note_previous_decl;
2034       if (SS.isEmpty())
2035         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2036                      PDiag(NoteID), AcceptableWithRecovery);
2037       else
2038         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2039                                   << Name << computeDeclContext(SS, false)
2040                                   << DroppedSpecifier << SS.getRange(),
2041                      PDiag(NoteID), AcceptableWithRecovery);
2042 
2043       // Tell the callee whether to try to recover.
2044       return !AcceptableWithRecovery;
2045     }
2046   }
2047   R.clear();
2048 
2049   // Emit a special diagnostic for failed member lookups.
2050   // FIXME: computing the declaration context might fail here (?)
2051   if (!SS.isEmpty()) {
2052     Diag(R.getNameLoc(), diag::err_no_member)
2053       << Name << computeDeclContext(SS, false)
2054       << SS.getRange();
2055     return true;
2056   }
2057 
2058   // Give up, we can't recover.
2059   Diag(R.getNameLoc(), diagnostic) << Name;
2060   return true;
2061 }
2062 
2063 /// In Microsoft mode, if we are inside a template class whose parent class has
2064 /// dependent base classes, and we can't resolve an unqualified identifier, then
2065 /// assume the identifier is a member of a dependent base class.  We can only
2066 /// recover successfully in static methods, instance methods, and other contexts
2067 /// where 'this' is available.  This doesn't precisely match MSVC's
2068 /// instantiation model, but it's close enough.
2069 static Expr *
2070 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2071                                DeclarationNameInfo &NameInfo,
2072                                SourceLocation TemplateKWLoc,
2073                                const TemplateArgumentListInfo *TemplateArgs) {
2074   // Only try to recover from lookup into dependent bases in static methods or
2075   // contexts where 'this' is available.
2076   QualType ThisType = S.getCurrentThisType();
2077   const CXXRecordDecl *RD = nullptr;
2078   if (!ThisType.isNull())
2079     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2080   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2081     RD = MD->getParent();
2082   if (!RD || !RD->hasAnyDependentBases())
2083     return nullptr;
2084 
2085   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2086   // is available, suggest inserting 'this->' as a fixit.
2087   SourceLocation Loc = NameInfo.getLoc();
2088   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2089   DB << NameInfo.getName() << RD;
2090 
2091   if (!ThisType.isNull()) {
2092     DB << FixItHint::CreateInsertion(Loc, "this->");
2093     return CXXDependentScopeMemberExpr::Create(
2094         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2095         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2096         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2097   }
2098 
2099   // Synthesize a fake NNS that points to the derived class.  This will
2100   // perform name lookup during template instantiation.
2101   CXXScopeSpec SS;
2102   auto *NNS =
2103       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2104   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2105   return DependentScopeDeclRefExpr::Create(
2106       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2107       TemplateArgs);
2108 }
2109 
2110 ExprResult
2111 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2112                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2113                         bool HasTrailingLParen, bool IsAddressOfOperand,
2114                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2115                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2116   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2117          "cannot be direct & operand and have a trailing lparen");
2118   if (SS.isInvalid())
2119     return ExprError();
2120 
2121   TemplateArgumentListInfo TemplateArgsBuffer;
2122 
2123   // Decompose the UnqualifiedId into the following data.
2124   DeclarationNameInfo NameInfo;
2125   const TemplateArgumentListInfo *TemplateArgs;
2126   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2127 
2128   DeclarationName Name = NameInfo.getName();
2129   IdentifierInfo *II = Name.getAsIdentifierInfo();
2130   SourceLocation NameLoc = NameInfo.getLoc();
2131 
2132   // C++ [temp.dep.expr]p3:
2133   //   An id-expression is type-dependent if it contains:
2134   //     -- an identifier that was declared with a dependent type,
2135   //        (note: handled after lookup)
2136   //     -- a template-id that is dependent,
2137   //        (note: handled in BuildTemplateIdExpr)
2138   //     -- a conversion-function-id that specifies a dependent type,
2139   //     -- a nested-name-specifier that contains a class-name that
2140   //        names a dependent type.
2141   // Determine whether this is a member of an unknown specialization;
2142   // we need to handle these differently.
2143   bool DependentID = false;
2144   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2145       Name.getCXXNameType()->isDependentType()) {
2146     DependentID = true;
2147   } else if (SS.isSet()) {
2148     if (DeclContext *DC = computeDeclContext(SS, false)) {
2149       if (RequireCompleteDeclContext(SS, DC))
2150         return ExprError();
2151     } else {
2152       DependentID = true;
2153     }
2154   }
2155 
2156   if (DependentID)
2157     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2158                                       IsAddressOfOperand, TemplateArgs);
2159 
2160   // Perform the required lookup.
2161   LookupResult R(*this, NameInfo,
2162                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2163                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2164   if (TemplateArgs) {
2165     // Lookup the template name again to correctly establish the context in
2166     // which it was found. This is really unfortunate as we already did the
2167     // lookup to determine that it was a template name in the first place. If
2168     // this becomes a performance hit, we can work harder to preserve those
2169     // results until we get here but it's likely not worth it.
2170     bool MemberOfUnknownSpecialization;
2171     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2172                        MemberOfUnknownSpecialization);
2173 
2174     if (MemberOfUnknownSpecialization ||
2175         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2176       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2177                                         IsAddressOfOperand, TemplateArgs);
2178   } else {
2179     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2180     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2181 
2182     // If the result might be in a dependent base class, this is a dependent
2183     // id-expression.
2184     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2185       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2186                                         IsAddressOfOperand, TemplateArgs);
2187 
2188     // If this reference is in an Objective-C method, then we need to do
2189     // some special Objective-C lookup, too.
2190     if (IvarLookupFollowUp) {
2191       ExprResult E(LookupInObjCMethod(R, S, II, true));
2192       if (E.isInvalid())
2193         return ExprError();
2194 
2195       if (Expr *Ex = E.getAs<Expr>())
2196         return Ex;
2197     }
2198   }
2199 
2200   if (R.isAmbiguous())
2201     return ExprError();
2202 
2203   // This could be an implicitly declared function reference (legal in C90,
2204   // extension in C99, forbidden in C++).
2205   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2206     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2207     if (D) R.addDecl(D);
2208   }
2209 
2210   // Determine whether this name might be a candidate for
2211   // argument-dependent lookup.
2212   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2213 
2214   if (R.empty() && !ADL) {
2215     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2216       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2217                                                    TemplateKWLoc, TemplateArgs))
2218         return E;
2219     }
2220 
2221     // Don't diagnose an empty lookup for inline assembly.
2222     if (IsInlineAsmIdentifier)
2223       return ExprError();
2224 
2225     // If this name wasn't predeclared and if this is not a function
2226     // call, diagnose the problem.
2227     TypoExpr *TE = nullptr;
2228     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2229         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2230     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2231     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2232            "Typo correction callback misconfigured");
2233     if (CCC) {
2234       // Make sure the callback knows what the typo being diagnosed is.
2235       CCC->setTypoName(II);
2236       if (SS.isValid())
2237         CCC->setTypoNNS(SS.getScopeRep());
2238     }
2239     if (DiagnoseEmptyLookup(S, SS, R,
2240                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2241                             nullptr, None, &TE)) {
2242       if (TE && KeywordReplacement) {
2243         auto &State = getTypoExprState(TE);
2244         auto BestTC = State.Consumer->getNextCorrection();
2245         if (BestTC.isKeyword()) {
2246           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2247           if (State.DiagHandler)
2248             State.DiagHandler(BestTC);
2249           KeywordReplacement->startToken();
2250           KeywordReplacement->setKind(II->getTokenID());
2251           KeywordReplacement->setIdentifierInfo(II);
2252           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2253           // Clean up the state associated with the TypoExpr, since it has
2254           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2255           clearDelayedTypo(TE);
2256           // Signal that a correction to a keyword was performed by returning a
2257           // valid-but-null ExprResult.
2258           return (Expr*)nullptr;
2259         }
2260         State.Consumer->resetCorrectionStream();
2261       }
2262       return TE ? TE : ExprError();
2263     }
2264 
2265     assert(!R.empty() &&
2266            "DiagnoseEmptyLookup returned false but added no results");
2267 
2268     // If we found an Objective-C instance variable, let
2269     // LookupInObjCMethod build the appropriate expression to
2270     // reference the ivar.
2271     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2272       R.clear();
2273       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2274       // In a hopelessly buggy code, Objective-C instance variable
2275       // lookup fails and no expression will be built to reference it.
2276       if (!E.isInvalid() && !E.get())
2277         return ExprError();
2278       return E;
2279     }
2280   }
2281 
2282   // This is guaranteed from this point on.
2283   assert(!R.empty() || ADL);
2284 
2285   // Check whether this might be a C++ implicit instance member access.
2286   // C++ [class.mfct.non-static]p3:
2287   //   When an id-expression that is not part of a class member access
2288   //   syntax and not used to form a pointer to member is used in the
2289   //   body of a non-static member function of class X, if name lookup
2290   //   resolves the name in the id-expression to a non-static non-type
2291   //   member of some class C, the id-expression is transformed into a
2292   //   class member access expression using (*this) as the
2293   //   postfix-expression to the left of the . operator.
2294   //
2295   // But we don't actually need to do this for '&' operands if R
2296   // resolved to a function or overloaded function set, because the
2297   // expression is ill-formed if it actually works out to be a
2298   // non-static member function:
2299   //
2300   // C++ [expr.ref]p4:
2301   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2302   //   [t]he expression can be used only as the left-hand operand of a
2303   //   member function call.
2304   //
2305   // There are other safeguards against such uses, but it's important
2306   // to get this right here so that we don't end up making a
2307   // spuriously dependent expression if we're inside a dependent
2308   // instance method.
2309   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2310     bool MightBeImplicitMember;
2311     if (!IsAddressOfOperand)
2312       MightBeImplicitMember = true;
2313     else if (!SS.isEmpty())
2314       MightBeImplicitMember = false;
2315     else if (R.isOverloadedResult())
2316       MightBeImplicitMember = false;
2317     else if (R.isUnresolvableResult())
2318       MightBeImplicitMember = true;
2319     else
2320       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2321                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2322                               isa<MSPropertyDecl>(R.getFoundDecl());
2323 
2324     if (MightBeImplicitMember)
2325       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2326                                              R, TemplateArgs, S);
2327   }
2328 
2329   if (TemplateArgs || TemplateKWLoc.isValid()) {
2330 
2331     // In C++1y, if this is a variable template id, then check it
2332     // in BuildTemplateIdExpr().
2333     // The single lookup result must be a variable template declaration.
2334     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2335         Id.TemplateId->Kind == TNK_Var_template) {
2336       assert(R.getAsSingle<VarTemplateDecl>() &&
2337              "There should only be one declaration found.");
2338     }
2339 
2340     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2341   }
2342 
2343   return BuildDeclarationNameExpr(SS, R, ADL);
2344 }
2345 
2346 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2347 /// declaration name, generally during template instantiation.
2348 /// There's a large number of things which don't need to be done along
2349 /// this path.
2350 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2351     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2352     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2353   DeclContext *DC = computeDeclContext(SS, false);
2354   if (!DC)
2355     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2356                                      NameInfo, /*TemplateArgs=*/nullptr);
2357 
2358   if (RequireCompleteDeclContext(SS, DC))
2359     return ExprError();
2360 
2361   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2362   LookupQualifiedName(R, DC);
2363 
2364   if (R.isAmbiguous())
2365     return ExprError();
2366 
2367   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2368     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2369                                      NameInfo, /*TemplateArgs=*/nullptr);
2370 
2371   if (R.empty()) {
2372     Diag(NameInfo.getLoc(), diag::err_no_member)
2373       << NameInfo.getName() << DC << SS.getRange();
2374     return ExprError();
2375   }
2376 
2377   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2378     // Diagnose a missing typename if this resolved unambiguously to a type in
2379     // a dependent context.  If we can recover with a type, downgrade this to
2380     // a warning in Microsoft compatibility mode.
2381     unsigned DiagID = diag::err_typename_missing;
2382     if (RecoveryTSI && getLangOpts().MSVCCompat)
2383       DiagID = diag::ext_typename_missing;
2384     SourceLocation Loc = SS.getBeginLoc();
2385     auto D = Diag(Loc, DiagID);
2386     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2387       << SourceRange(Loc, NameInfo.getEndLoc());
2388 
2389     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2390     // context.
2391     if (!RecoveryTSI)
2392       return ExprError();
2393 
2394     // Only issue the fixit if we're prepared to recover.
2395     D << FixItHint::CreateInsertion(Loc, "typename ");
2396 
2397     // Recover by pretending this was an elaborated type.
2398     QualType Ty = Context.getTypeDeclType(TD);
2399     TypeLocBuilder TLB;
2400     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2401 
2402     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2403     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2404     QTL.setElaboratedKeywordLoc(SourceLocation());
2405     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2406 
2407     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2408 
2409     return ExprEmpty();
2410   }
2411 
2412   // Defend against this resolving to an implicit member access. We usually
2413   // won't get here if this might be a legitimate a class member (we end up in
2414   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2415   // a pointer-to-member or in an unevaluated context in C++11.
2416   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2417     return BuildPossibleImplicitMemberExpr(SS,
2418                                            /*TemplateKWLoc=*/SourceLocation(),
2419                                            R, /*TemplateArgs=*/nullptr, S);
2420 
2421   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2422 }
2423 
2424 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2425 /// detected that we're currently inside an ObjC method.  Perform some
2426 /// additional lookup.
2427 ///
2428 /// Ideally, most of this would be done by lookup, but there's
2429 /// actually quite a lot of extra work involved.
2430 ///
2431 /// Returns a null sentinel to indicate trivial success.
2432 ExprResult
2433 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2434                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2435   SourceLocation Loc = Lookup.getNameLoc();
2436   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2437 
2438   // Check for error condition which is already reported.
2439   if (!CurMethod)
2440     return ExprError();
2441 
2442   // There are two cases to handle here.  1) scoped lookup could have failed,
2443   // in which case we should look for an ivar.  2) scoped lookup could have
2444   // found a decl, but that decl is outside the current instance method (i.e.
2445   // a global variable).  In these two cases, we do a lookup for an ivar with
2446   // this name, if the lookup sucedes, we replace it our current decl.
2447 
2448   // If we're in a class method, we don't normally want to look for
2449   // ivars.  But if we don't find anything else, and there's an
2450   // ivar, that's an error.
2451   bool IsClassMethod = CurMethod->isClassMethod();
2452 
2453   bool LookForIvars;
2454   if (Lookup.empty())
2455     LookForIvars = true;
2456   else if (IsClassMethod)
2457     LookForIvars = false;
2458   else
2459     LookForIvars = (Lookup.isSingleResult() &&
2460                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2461   ObjCInterfaceDecl *IFace = nullptr;
2462   if (LookForIvars) {
2463     IFace = CurMethod->getClassInterface();
2464     ObjCInterfaceDecl *ClassDeclared;
2465     ObjCIvarDecl *IV = nullptr;
2466     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2467       // Diagnose using an ivar in a class method.
2468       if (IsClassMethod)
2469         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2470                          << IV->getDeclName());
2471 
2472       // If we're referencing an invalid decl, just return this as a silent
2473       // error node.  The error diagnostic was already emitted on the decl.
2474       if (IV->isInvalidDecl())
2475         return ExprError();
2476 
2477       // Check if referencing a field with __attribute__((deprecated)).
2478       if (DiagnoseUseOfDecl(IV, Loc))
2479         return ExprError();
2480 
2481       // Diagnose the use of an ivar outside of the declaring class.
2482       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2483           !declaresSameEntity(ClassDeclared, IFace) &&
2484           !getLangOpts().DebuggerSupport)
2485         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2486 
2487       // FIXME: This should use a new expr for a direct reference, don't
2488       // turn this into Self->ivar, just return a BareIVarExpr or something.
2489       IdentifierInfo &II = Context.Idents.get("self");
2490       UnqualifiedId SelfName;
2491       SelfName.setIdentifier(&II, SourceLocation());
2492       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2493       CXXScopeSpec SelfScopeSpec;
2494       SourceLocation TemplateKWLoc;
2495       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2496                                               SelfName, false, false);
2497       if (SelfExpr.isInvalid())
2498         return ExprError();
2499 
2500       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2501       if (SelfExpr.isInvalid())
2502         return ExprError();
2503 
2504       MarkAnyDeclReferenced(Loc, IV, true);
2505 
2506       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2507       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2508           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2509         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2510 
2511       ObjCIvarRefExpr *Result = new (Context)
2512           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2513                           IV->getLocation(), SelfExpr.get(), true, true);
2514 
2515       if (getLangOpts().ObjCAutoRefCount) {
2516         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2517           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2518             recordUseOfEvaluatedWeak(Result);
2519         }
2520         if (CurContext->isClosure())
2521           Diag(Loc, diag::warn_implicitly_retains_self)
2522             << FixItHint::CreateInsertion(Loc, "self->");
2523       }
2524 
2525       return Result;
2526     }
2527   } else if (CurMethod->isInstanceMethod()) {
2528     // We should warn if a local variable hides an ivar.
2529     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2530       ObjCInterfaceDecl *ClassDeclared;
2531       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2532         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2533             declaresSameEntity(IFace, ClassDeclared))
2534           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2535       }
2536     }
2537   } else if (Lookup.isSingleResult() &&
2538              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2539     // If accessing a stand-alone ivar in a class method, this is an error.
2540     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2541       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2542                        << IV->getDeclName());
2543   }
2544 
2545   if (Lookup.empty() && II && AllowBuiltinCreation) {
2546     // FIXME. Consolidate this with similar code in LookupName.
2547     if (unsigned BuiltinID = II->getBuiltinID()) {
2548       if (!(getLangOpts().CPlusPlus &&
2549             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2550         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2551                                            S, Lookup.isForRedeclaration(),
2552                                            Lookup.getNameLoc());
2553         if (D) Lookup.addDecl(D);
2554       }
2555     }
2556   }
2557   // Sentinel value saying that we didn't do anything special.
2558   return ExprResult((Expr *)nullptr);
2559 }
2560 
2561 /// \brief Cast a base object to a member's actual type.
2562 ///
2563 /// Logically this happens in three phases:
2564 ///
2565 /// * First we cast from the base type to the naming class.
2566 ///   The naming class is the class into which we were looking
2567 ///   when we found the member;  it's the qualifier type if a
2568 ///   qualifier was provided, and otherwise it's the base type.
2569 ///
2570 /// * Next we cast from the naming class to the declaring class.
2571 ///   If the member we found was brought into a class's scope by
2572 ///   a using declaration, this is that class;  otherwise it's
2573 ///   the class declaring the member.
2574 ///
2575 /// * Finally we cast from the declaring class to the "true"
2576 ///   declaring class of the member.  This conversion does not
2577 ///   obey access control.
2578 ExprResult
2579 Sema::PerformObjectMemberConversion(Expr *From,
2580                                     NestedNameSpecifier *Qualifier,
2581                                     NamedDecl *FoundDecl,
2582                                     NamedDecl *Member) {
2583   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2584   if (!RD)
2585     return From;
2586 
2587   QualType DestRecordType;
2588   QualType DestType;
2589   QualType FromRecordType;
2590   QualType FromType = From->getType();
2591   bool PointerConversions = false;
2592   if (isa<FieldDecl>(Member)) {
2593     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2594 
2595     if (FromType->getAs<PointerType>()) {
2596       DestType = Context.getPointerType(DestRecordType);
2597       FromRecordType = FromType->getPointeeType();
2598       PointerConversions = true;
2599     } else {
2600       DestType = DestRecordType;
2601       FromRecordType = FromType;
2602     }
2603   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2604     if (Method->isStatic())
2605       return From;
2606 
2607     DestType = Method->getThisType(Context);
2608     DestRecordType = DestType->getPointeeType();
2609 
2610     if (FromType->getAs<PointerType>()) {
2611       FromRecordType = FromType->getPointeeType();
2612       PointerConversions = true;
2613     } else {
2614       FromRecordType = FromType;
2615       DestType = DestRecordType;
2616     }
2617   } else {
2618     // No conversion necessary.
2619     return From;
2620   }
2621 
2622   if (DestType->isDependentType() || FromType->isDependentType())
2623     return From;
2624 
2625   // If the unqualified types are the same, no conversion is necessary.
2626   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2627     return From;
2628 
2629   SourceRange FromRange = From->getSourceRange();
2630   SourceLocation FromLoc = FromRange.getBegin();
2631 
2632   ExprValueKind VK = From->getValueKind();
2633 
2634   // C++ [class.member.lookup]p8:
2635   //   [...] Ambiguities can often be resolved by qualifying a name with its
2636   //   class name.
2637   //
2638   // If the member was a qualified name and the qualified referred to a
2639   // specific base subobject type, we'll cast to that intermediate type
2640   // first and then to the object in which the member is declared. That allows
2641   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2642   //
2643   //   class Base { public: int x; };
2644   //   class Derived1 : public Base { };
2645   //   class Derived2 : public Base { };
2646   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2647   //
2648   //   void VeryDerived::f() {
2649   //     x = 17; // error: ambiguous base subobjects
2650   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2651   //   }
2652   if (Qualifier && Qualifier->getAsType()) {
2653     QualType QType = QualType(Qualifier->getAsType(), 0);
2654     assert(QType->isRecordType() && "lookup done with non-record type");
2655 
2656     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2657 
2658     // In C++98, the qualifier type doesn't actually have to be a base
2659     // type of the object type, in which case we just ignore it.
2660     // Otherwise build the appropriate casts.
2661     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2662       CXXCastPath BasePath;
2663       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2664                                        FromLoc, FromRange, &BasePath))
2665         return ExprError();
2666 
2667       if (PointerConversions)
2668         QType = Context.getPointerType(QType);
2669       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2670                                VK, &BasePath).get();
2671 
2672       FromType = QType;
2673       FromRecordType = QRecordType;
2674 
2675       // If the qualifier type was the same as the destination type,
2676       // we're done.
2677       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2678         return From;
2679     }
2680   }
2681 
2682   bool IgnoreAccess = false;
2683 
2684   // If we actually found the member through a using declaration, cast
2685   // down to the using declaration's type.
2686   //
2687   // Pointer equality is fine here because only one declaration of a
2688   // class ever has member declarations.
2689   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2690     assert(isa<UsingShadowDecl>(FoundDecl));
2691     QualType URecordType = Context.getTypeDeclType(
2692                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2693 
2694     // We only need to do this if the naming-class to declaring-class
2695     // conversion is non-trivial.
2696     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2697       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2698       CXXCastPath BasePath;
2699       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2700                                        FromLoc, FromRange, &BasePath))
2701         return ExprError();
2702 
2703       QualType UType = URecordType;
2704       if (PointerConversions)
2705         UType = Context.getPointerType(UType);
2706       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2707                                VK, &BasePath).get();
2708       FromType = UType;
2709       FromRecordType = URecordType;
2710     }
2711 
2712     // We don't do access control for the conversion from the
2713     // declaring class to the true declaring class.
2714     IgnoreAccess = true;
2715   }
2716 
2717   CXXCastPath BasePath;
2718   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2719                                    FromLoc, FromRange, &BasePath,
2720                                    IgnoreAccess))
2721     return ExprError();
2722 
2723   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2724                            VK, &BasePath);
2725 }
2726 
2727 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2728                                       const LookupResult &R,
2729                                       bool HasTrailingLParen) {
2730   // Only when used directly as the postfix-expression of a call.
2731   if (!HasTrailingLParen)
2732     return false;
2733 
2734   // Never if a scope specifier was provided.
2735   if (SS.isSet())
2736     return false;
2737 
2738   // Only in C++ or ObjC++.
2739   if (!getLangOpts().CPlusPlus)
2740     return false;
2741 
2742   // Turn off ADL when we find certain kinds of declarations during
2743   // normal lookup:
2744   for (NamedDecl *D : R) {
2745     // C++0x [basic.lookup.argdep]p3:
2746     //     -- a declaration of a class member
2747     // Since using decls preserve this property, we check this on the
2748     // original decl.
2749     if (D->isCXXClassMember())
2750       return false;
2751 
2752     // C++0x [basic.lookup.argdep]p3:
2753     //     -- a block-scope function declaration that is not a
2754     //        using-declaration
2755     // NOTE: we also trigger this for function templates (in fact, we
2756     // don't check the decl type at all, since all other decl types
2757     // turn off ADL anyway).
2758     if (isa<UsingShadowDecl>(D))
2759       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2760     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2761       return false;
2762 
2763     // C++0x [basic.lookup.argdep]p3:
2764     //     -- a declaration that is neither a function or a function
2765     //        template
2766     // And also for builtin functions.
2767     if (isa<FunctionDecl>(D)) {
2768       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2769 
2770       // But also builtin functions.
2771       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2772         return false;
2773     } else if (!isa<FunctionTemplateDecl>(D))
2774       return false;
2775   }
2776 
2777   return true;
2778 }
2779 
2780 
2781 /// Diagnoses obvious problems with the use of the given declaration
2782 /// as an expression.  This is only actually called for lookups that
2783 /// were not overloaded, and it doesn't promise that the declaration
2784 /// will in fact be used.
2785 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2786   if (isa<TypedefNameDecl>(D)) {
2787     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2788     return true;
2789   }
2790 
2791   if (isa<ObjCInterfaceDecl>(D)) {
2792     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2793     return true;
2794   }
2795 
2796   if (isa<NamespaceDecl>(D)) {
2797     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2798     return true;
2799   }
2800 
2801   return false;
2802 }
2803 
2804 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2805                                           LookupResult &R, bool NeedsADL,
2806                                           bool AcceptInvalidDecl) {
2807   // If this is a single, fully-resolved result and we don't need ADL,
2808   // just build an ordinary singleton decl ref.
2809   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2810     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2811                                     R.getRepresentativeDecl(), nullptr,
2812                                     AcceptInvalidDecl);
2813 
2814   // We only need to check the declaration if there's exactly one
2815   // result, because in the overloaded case the results can only be
2816   // functions and function templates.
2817   if (R.isSingleResult() &&
2818       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2819     return ExprError();
2820 
2821   // Otherwise, just build an unresolved lookup expression.  Suppress
2822   // any lookup-related diagnostics; we'll hash these out later, when
2823   // we've picked a target.
2824   R.suppressDiagnostics();
2825 
2826   UnresolvedLookupExpr *ULE
2827     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2828                                    SS.getWithLocInContext(Context),
2829                                    R.getLookupNameInfo(),
2830                                    NeedsADL, R.isOverloadedResult(),
2831                                    R.begin(), R.end());
2832 
2833   return ULE;
2834 }
2835 
2836 static void
2837 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2838                                    ValueDecl *var, DeclContext *DC);
2839 
2840 /// \brief Complete semantic analysis for a reference to the given declaration.
2841 ExprResult Sema::BuildDeclarationNameExpr(
2842     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2843     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2844     bool AcceptInvalidDecl) {
2845   assert(D && "Cannot refer to a NULL declaration");
2846   assert(!isa<FunctionTemplateDecl>(D) &&
2847          "Cannot refer unambiguously to a function template");
2848 
2849   SourceLocation Loc = NameInfo.getLoc();
2850   if (CheckDeclInExpr(*this, Loc, D))
2851     return ExprError();
2852 
2853   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2854     // Specifically diagnose references to class templates that are missing
2855     // a template argument list.
2856     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2857                                            << Template << SS.getRange();
2858     Diag(Template->getLocation(), diag::note_template_decl_here);
2859     return ExprError();
2860   }
2861 
2862   // Make sure that we're referring to a value.
2863   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2864   if (!VD) {
2865     Diag(Loc, diag::err_ref_non_value)
2866       << D << SS.getRange();
2867     Diag(D->getLocation(), diag::note_declared_at);
2868     return ExprError();
2869   }
2870 
2871   // Check whether this declaration can be used. Note that we suppress
2872   // this check when we're going to perform argument-dependent lookup
2873   // on this function name, because this might not be the function
2874   // that overload resolution actually selects.
2875   if (DiagnoseUseOfDecl(VD, Loc))
2876     return ExprError();
2877 
2878   // Only create DeclRefExpr's for valid Decl's.
2879   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2880     return ExprError();
2881 
2882   // Handle members of anonymous structs and unions.  If we got here,
2883   // and the reference is to a class member indirect field, then this
2884   // must be the subject of a pointer-to-member expression.
2885   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2886     if (!indirectField->isCXXClassMember())
2887       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2888                                                       indirectField);
2889 
2890   {
2891     QualType type = VD->getType();
2892     ExprValueKind valueKind = VK_RValue;
2893 
2894     switch (D->getKind()) {
2895     // Ignore all the non-ValueDecl kinds.
2896 #define ABSTRACT_DECL(kind)
2897 #define VALUE(type, base)
2898 #define DECL(type, base) \
2899     case Decl::type:
2900 #include "clang/AST/DeclNodes.inc"
2901       llvm_unreachable("invalid value decl kind");
2902 
2903     // These shouldn't make it here.
2904     case Decl::ObjCAtDefsField:
2905     case Decl::ObjCIvar:
2906       llvm_unreachable("forming non-member reference to ivar?");
2907 
2908     // Enum constants are always r-values and never references.
2909     // Unresolved using declarations are dependent.
2910     case Decl::EnumConstant:
2911     case Decl::UnresolvedUsingValue:
2912     case Decl::OMPDeclareReduction:
2913       valueKind = VK_RValue;
2914       break;
2915 
2916     // Fields and indirect fields that got here must be for
2917     // pointer-to-member expressions; we just call them l-values for
2918     // internal consistency, because this subexpression doesn't really
2919     // exist in the high-level semantics.
2920     case Decl::Field:
2921     case Decl::IndirectField:
2922       assert(getLangOpts().CPlusPlus &&
2923              "building reference to field in C?");
2924 
2925       // These can't have reference type in well-formed programs, but
2926       // for internal consistency we do this anyway.
2927       type = type.getNonReferenceType();
2928       valueKind = VK_LValue;
2929       break;
2930 
2931     // Non-type template parameters are either l-values or r-values
2932     // depending on the type.
2933     case Decl::NonTypeTemplateParm: {
2934       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2935         type = reftype->getPointeeType();
2936         valueKind = VK_LValue; // even if the parameter is an r-value reference
2937         break;
2938       }
2939 
2940       // For non-references, we need to strip qualifiers just in case
2941       // the template parameter was declared as 'const int' or whatever.
2942       valueKind = VK_RValue;
2943       type = type.getUnqualifiedType();
2944       break;
2945     }
2946 
2947     case Decl::Var:
2948     case Decl::VarTemplateSpecialization:
2949     case Decl::VarTemplatePartialSpecialization:
2950     case Decl::Decomposition:
2951     case Decl::OMPCapturedExpr:
2952       // In C, "extern void blah;" is valid and is an r-value.
2953       if (!getLangOpts().CPlusPlus &&
2954           !type.hasQualifiers() &&
2955           type->isVoidType()) {
2956         valueKind = VK_RValue;
2957         break;
2958       }
2959       // fallthrough
2960 
2961     case Decl::ImplicitParam:
2962     case Decl::ParmVar: {
2963       // These are always l-values.
2964       valueKind = VK_LValue;
2965       type = type.getNonReferenceType();
2966 
2967       // FIXME: Does the addition of const really only apply in
2968       // potentially-evaluated contexts? Since the variable isn't actually
2969       // captured in an unevaluated context, it seems that the answer is no.
2970       if (!isUnevaluatedContext()) {
2971         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2972         if (!CapturedType.isNull())
2973           type = CapturedType;
2974       }
2975 
2976       break;
2977     }
2978 
2979     case Decl::Binding: {
2980       // These are always lvalues.
2981       valueKind = VK_LValue;
2982       type = type.getNonReferenceType();
2983       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2984       // decides how that's supposed to work.
2985       auto *BD = cast<BindingDecl>(VD);
2986       if (BD->getDeclContext()->isFunctionOrMethod() &&
2987           BD->getDeclContext() != CurContext)
2988         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2989       break;
2990     }
2991 
2992     case Decl::Function: {
2993       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2994         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2995           type = Context.BuiltinFnTy;
2996           valueKind = VK_RValue;
2997           break;
2998         }
2999       }
3000 
3001       const FunctionType *fty = type->castAs<FunctionType>();
3002 
3003       // If we're referring to a function with an __unknown_anytype
3004       // result type, make the entire expression __unknown_anytype.
3005       if (fty->getReturnType() == Context.UnknownAnyTy) {
3006         type = Context.UnknownAnyTy;
3007         valueKind = VK_RValue;
3008         break;
3009       }
3010 
3011       // Functions are l-values in C++.
3012       if (getLangOpts().CPlusPlus) {
3013         valueKind = VK_LValue;
3014         break;
3015       }
3016 
3017       // C99 DR 316 says that, if a function type comes from a
3018       // function definition (without a prototype), that type is only
3019       // used for checking compatibility. Therefore, when referencing
3020       // the function, we pretend that we don't have the full function
3021       // type.
3022       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3023           isa<FunctionProtoType>(fty))
3024         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3025                                               fty->getExtInfo());
3026 
3027       // Functions are r-values in C.
3028       valueKind = VK_RValue;
3029       break;
3030     }
3031 
3032     case Decl::MSProperty:
3033       valueKind = VK_LValue;
3034       break;
3035 
3036     case Decl::CXXMethod:
3037       // If we're referring to a method with an __unknown_anytype
3038       // result type, make the entire expression __unknown_anytype.
3039       // This should only be possible with a type written directly.
3040       if (const FunctionProtoType *proto
3041             = dyn_cast<FunctionProtoType>(VD->getType()))
3042         if (proto->getReturnType() == Context.UnknownAnyTy) {
3043           type = Context.UnknownAnyTy;
3044           valueKind = VK_RValue;
3045           break;
3046         }
3047 
3048       // C++ methods are l-values if static, r-values if non-static.
3049       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3050         valueKind = VK_LValue;
3051         break;
3052       }
3053       // fallthrough
3054 
3055     case Decl::CXXConversion:
3056     case Decl::CXXDestructor:
3057     case Decl::CXXConstructor:
3058       valueKind = VK_RValue;
3059       break;
3060     }
3061 
3062     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3063                             TemplateArgs);
3064   }
3065 }
3066 
3067 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3068                                     SmallString<32> &Target) {
3069   Target.resize(CharByteWidth * (Source.size() + 1));
3070   char *ResultPtr = &Target[0];
3071   const llvm::UTF8 *ErrorPtr;
3072   bool success =
3073       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3074   (void)success;
3075   assert(success);
3076   Target.resize(ResultPtr - &Target[0]);
3077 }
3078 
3079 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3080                                      PredefinedExpr::IdentType IT) {
3081   // Pick the current block, lambda, captured statement or function.
3082   Decl *currentDecl = nullptr;
3083   if (const BlockScopeInfo *BSI = getCurBlock())
3084     currentDecl = BSI->TheDecl;
3085   else if (const LambdaScopeInfo *LSI = getCurLambda())
3086     currentDecl = LSI->CallOperator;
3087   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3088     currentDecl = CSI->TheCapturedDecl;
3089   else
3090     currentDecl = getCurFunctionOrMethodDecl();
3091 
3092   if (!currentDecl) {
3093     Diag(Loc, diag::ext_predef_outside_function);
3094     currentDecl = Context.getTranslationUnitDecl();
3095   }
3096 
3097   QualType ResTy;
3098   StringLiteral *SL = nullptr;
3099   if (cast<DeclContext>(currentDecl)->isDependentContext())
3100     ResTy = Context.DependentTy;
3101   else {
3102     // Pre-defined identifiers are of type char[x], where x is the length of
3103     // the string.
3104     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3105     unsigned Length = Str.length();
3106 
3107     llvm::APInt LengthI(32, Length + 1);
3108     if (IT == PredefinedExpr::LFunction) {
3109       ResTy = Context.WideCharTy.withConst();
3110       SmallString<32> RawChars;
3111       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3112                               Str, RawChars);
3113       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3114                                            /*IndexTypeQuals*/ 0);
3115       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3116                                  /*Pascal*/ false, ResTy, Loc);
3117     } else {
3118       ResTy = Context.CharTy.withConst();
3119       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3120                                            /*IndexTypeQuals*/ 0);
3121       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3122                                  /*Pascal*/ false, ResTy, Loc);
3123     }
3124   }
3125 
3126   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3127 }
3128 
3129 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3130   PredefinedExpr::IdentType IT;
3131 
3132   switch (Kind) {
3133   default: llvm_unreachable("Unknown simple primary expr!");
3134   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3135   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3136   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3137   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3138   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3139   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3140   }
3141 
3142   return BuildPredefinedExpr(Loc, IT);
3143 }
3144 
3145 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3146   SmallString<16> CharBuffer;
3147   bool Invalid = false;
3148   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3149   if (Invalid)
3150     return ExprError();
3151 
3152   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3153                             PP, Tok.getKind());
3154   if (Literal.hadError())
3155     return ExprError();
3156 
3157   QualType Ty;
3158   if (Literal.isWide())
3159     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3160   else if (Literal.isUTF16())
3161     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3162   else if (Literal.isUTF32())
3163     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3164   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3165     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3166   else
3167     Ty = Context.CharTy;  // 'x' -> char in C++
3168 
3169   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3170   if (Literal.isWide())
3171     Kind = CharacterLiteral::Wide;
3172   else if (Literal.isUTF16())
3173     Kind = CharacterLiteral::UTF16;
3174   else if (Literal.isUTF32())
3175     Kind = CharacterLiteral::UTF32;
3176   else if (Literal.isUTF8())
3177     Kind = CharacterLiteral::UTF8;
3178 
3179   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3180                                              Tok.getLocation());
3181 
3182   if (Literal.getUDSuffix().empty())
3183     return Lit;
3184 
3185   // We're building a user-defined literal.
3186   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3187   SourceLocation UDSuffixLoc =
3188     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3189 
3190   // Make sure we're allowed user-defined literals here.
3191   if (!UDLScope)
3192     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3193 
3194   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3195   //   operator "" X (ch)
3196   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3197                                         Lit, Tok.getLocation());
3198 }
3199 
3200 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3201   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3202   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3203                                 Context.IntTy, Loc);
3204 }
3205 
3206 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3207                                   QualType Ty, SourceLocation Loc) {
3208   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3209 
3210   using llvm::APFloat;
3211   APFloat Val(Format);
3212 
3213   APFloat::opStatus result = Literal.GetFloatValue(Val);
3214 
3215   // Overflow is always an error, but underflow is only an error if
3216   // we underflowed to zero (APFloat reports denormals as underflow).
3217   if ((result & APFloat::opOverflow) ||
3218       ((result & APFloat::opUnderflow) && Val.isZero())) {
3219     unsigned diagnostic;
3220     SmallString<20> buffer;
3221     if (result & APFloat::opOverflow) {
3222       diagnostic = diag::warn_float_overflow;
3223       APFloat::getLargest(Format).toString(buffer);
3224     } else {
3225       diagnostic = diag::warn_float_underflow;
3226       APFloat::getSmallest(Format).toString(buffer);
3227     }
3228 
3229     S.Diag(Loc, diagnostic)
3230       << Ty
3231       << StringRef(buffer.data(), buffer.size());
3232   }
3233 
3234   bool isExact = (result == APFloat::opOK);
3235   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3236 }
3237 
3238 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3239   assert(E && "Invalid expression");
3240 
3241   if (E->isValueDependent())
3242     return false;
3243 
3244   QualType QT = E->getType();
3245   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3246     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3247     return true;
3248   }
3249 
3250   llvm::APSInt ValueAPS;
3251   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3252 
3253   if (R.isInvalid())
3254     return true;
3255 
3256   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3257   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3258     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3259         << ValueAPS.toString(10) << ValueIsPositive;
3260     return true;
3261   }
3262 
3263   return false;
3264 }
3265 
3266 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3267   // Fast path for a single digit (which is quite common).  A single digit
3268   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3269   if (Tok.getLength() == 1) {
3270     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3271     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3272   }
3273 
3274   SmallString<128> SpellingBuffer;
3275   // NumericLiteralParser wants to overread by one character.  Add padding to
3276   // the buffer in case the token is copied to the buffer.  If getSpelling()
3277   // returns a StringRef to the memory buffer, it should have a null char at
3278   // the EOF, so it is also safe.
3279   SpellingBuffer.resize(Tok.getLength() + 1);
3280 
3281   // Get the spelling of the token, which eliminates trigraphs, etc.
3282   bool Invalid = false;
3283   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3284   if (Invalid)
3285     return ExprError();
3286 
3287   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3288   if (Literal.hadError)
3289     return ExprError();
3290 
3291   if (Literal.hasUDSuffix()) {
3292     // We're building a user-defined literal.
3293     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3294     SourceLocation UDSuffixLoc =
3295       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3296 
3297     // Make sure we're allowed user-defined literals here.
3298     if (!UDLScope)
3299       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3300 
3301     QualType CookedTy;
3302     if (Literal.isFloatingLiteral()) {
3303       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3304       // long double, the literal is treated as a call of the form
3305       //   operator "" X (f L)
3306       CookedTy = Context.LongDoubleTy;
3307     } else {
3308       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3309       // unsigned long long, the literal is treated as a call of the form
3310       //   operator "" X (n ULL)
3311       CookedTy = Context.UnsignedLongLongTy;
3312     }
3313 
3314     DeclarationName OpName =
3315       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3316     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3317     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3318 
3319     SourceLocation TokLoc = Tok.getLocation();
3320 
3321     // Perform literal operator lookup to determine if we're building a raw
3322     // literal or a cooked one.
3323     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3324     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3325                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3326                                   /*AllowStringTemplate*/false)) {
3327     case LOLR_Error:
3328       return ExprError();
3329 
3330     case LOLR_Cooked: {
3331       Expr *Lit;
3332       if (Literal.isFloatingLiteral()) {
3333         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3334       } else {
3335         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3336         if (Literal.GetIntegerValue(ResultVal))
3337           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3338               << /* Unsigned */ 1;
3339         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3340                                      Tok.getLocation());
3341       }
3342       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3343     }
3344 
3345     case LOLR_Raw: {
3346       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3347       // literal is treated as a call of the form
3348       //   operator "" X ("n")
3349       unsigned Length = Literal.getUDSuffixOffset();
3350       QualType StrTy = Context.getConstantArrayType(
3351           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3352           ArrayType::Normal, 0);
3353       Expr *Lit = StringLiteral::Create(
3354           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3355           /*Pascal*/false, StrTy, &TokLoc, 1);
3356       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3357     }
3358 
3359     case LOLR_Template: {
3360       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3361       // template), L is treated as a call fo the form
3362       //   operator "" X <'c1', 'c2', ... 'ck'>()
3363       // where n is the source character sequence c1 c2 ... ck.
3364       TemplateArgumentListInfo ExplicitArgs;
3365       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3366       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3367       llvm::APSInt Value(CharBits, CharIsUnsigned);
3368       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3369         Value = TokSpelling[I];
3370         TemplateArgument Arg(Context, Value, Context.CharTy);
3371         TemplateArgumentLocInfo ArgInfo;
3372         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3373       }
3374       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3375                                       &ExplicitArgs);
3376     }
3377     case LOLR_StringTemplate:
3378       llvm_unreachable("unexpected literal operator lookup result");
3379     }
3380   }
3381 
3382   Expr *Res;
3383 
3384   if (Literal.isFloatingLiteral()) {
3385     QualType Ty;
3386     if (Literal.isHalf){
3387       if (getOpenCLOptions().cl_khr_fp16)
3388         Ty = Context.HalfTy;
3389       else {
3390         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3391         return ExprError();
3392       }
3393     } else if (Literal.isFloat)
3394       Ty = Context.FloatTy;
3395     else if (Literal.isLong)
3396       Ty = Context.LongDoubleTy;
3397     else if (Literal.isFloat128)
3398       Ty = Context.Float128Ty;
3399     else
3400       Ty = Context.DoubleTy;
3401 
3402     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3403 
3404     if (Ty == Context.DoubleTy) {
3405       if (getLangOpts().SinglePrecisionConstants) {
3406         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3407       } else if (getLangOpts().OpenCL &&
3408                  !((getLangOpts().OpenCLVersion >= 120) ||
3409                    getOpenCLOptions().cl_khr_fp64)) {
3410         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3411         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3412       }
3413     }
3414   } else if (!Literal.isIntegerLiteral()) {
3415     return ExprError();
3416   } else {
3417     QualType Ty;
3418 
3419     // 'long long' is a C99 or C++11 feature.
3420     if (!getLangOpts().C99 && Literal.isLongLong) {
3421       if (getLangOpts().CPlusPlus)
3422         Diag(Tok.getLocation(),
3423              getLangOpts().CPlusPlus11 ?
3424              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3425       else
3426         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3427     }
3428 
3429     // Get the value in the widest-possible width.
3430     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3431     llvm::APInt ResultVal(MaxWidth, 0);
3432 
3433     if (Literal.GetIntegerValue(ResultVal)) {
3434       // If this value didn't fit into uintmax_t, error and force to ull.
3435       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3436           << /* Unsigned */ 1;
3437       Ty = Context.UnsignedLongLongTy;
3438       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3439              "long long is not intmax_t?");
3440     } else {
3441       // If this value fits into a ULL, try to figure out what else it fits into
3442       // according to the rules of C99 6.4.4.1p5.
3443 
3444       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3445       // be an unsigned int.
3446       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3447 
3448       // Check from smallest to largest, picking the smallest type we can.
3449       unsigned Width = 0;
3450 
3451       // Microsoft specific integer suffixes are explicitly sized.
3452       if (Literal.MicrosoftInteger) {
3453         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3454           Width = 8;
3455           Ty = Context.CharTy;
3456         } else {
3457           Width = Literal.MicrosoftInteger;
3458           Ty = Context.getIntTypeForBitwidth(Width,
3459                                              /*Signed=*/!Literal.isUnsigned);
3460         }
3461       }
3462 
3463       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3464         // Are int/unsigned possibilities?
3465         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3466 
3467         // Does it fit in a unsigned int?
3468         if (ResultVal.isIntN(IntSize)) {
3469           // Does it fit in a signed int?
3470           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3471             Ty = Context.IntTy;
3472           else if (AllowUnsigned)
3473             Ty = Context.UnsignedIntTy;
3474           Width = IntSize;
3475         }
3476       }
3477 
3478       // Are long/unsigned long possibilities?
3479       if (Ty.isNull() && !Literal.isLongLong) {
3480         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3481 
3482         // Does it fit in a unsigned long?
3483         if (ResultVal.isIntN(LongSize)) {
3484           // Does it fit in a signed long?
3485           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3486             Ty = Context.LongTy;
3487           else if (AllowUnsigned)
3488             Ty = Context.UnsignedLongTy;
3489           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3490           // is compatible.
3491           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3492             const unsigned LongLongSize =
3493                 Context.getTargetInfo().getLongLongWidth();
3494             Diag(Tok.getLocation(),
3495                  getLangOpts().CPlusPlus
3496                      ? Literal.isLong
3497                            ? diag::warn_old_implicitly_unsigned_long_cxx
3498                            : /*C++98 UB*/ diag::
3499                                  ext_old_implicitly_unsigned_long_cxx
3500                      : diag::warn_old_implicitly_unsigned_long)
3501                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3502                                             : /*will be ill-formed*/ 1);
3503             Ty = Context.UnsignedLongTy;
3504           }
3505           Width = LongSize;
3506         }
3507       }
3508 
3509       // Check long long if needed.
3510       if (Ty.isNull()) {
3511         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3512 
3513         // Does it fit in a unsigned long long?
3514         if (ResultVal.isIntN(LongLongSize)) {
3515           // Does it fit in a signed long long?
3516           // To be compatible with MSVC, hex integer literals ending with the
3517           // LL or i64 suffix are always signed in Microsoft mode.
3518           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3519               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3520             Ty = Context.LongLongTy;
3521           else if (AllowUnsigned)
3522             Ty = Context.UnsignedLongLongTy;
3523           Width = LongLongSize;
3524         }
3525       }
3526 
3527       // If we still couldn't decide a type, we probably have something that
3528       // does not fit in a signed long long, but has no U suffix.
3529       if (Ty.isNull()) {
3530         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3531         Ty = Context.UnsignedLongLongTy;
3532         Width = Context.getTargetInfo().getLongLongWidth();
3533       }
3534 
3535       if (ResultVal.getBitWidth() != Width)
3536         ResultVal = ResultVal.trunc(Width);
3537     }
3538     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3539   }
3540 
3541   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3542   if (Literal.isImaginary)
3543     Res = new (Context) ImaginaryLiteral(Res,
3544                                         Context.getComplexType(Res->getType()));
3545 
3546   return Res;
3547 }
3548 
3549 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3550   assert(E && "ActOnParenExpr() missing expr");
3551   return new (Context) ParenExpr(L, R, E);
3552 }
3553 
3554 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3555                                          SourceLocation Loc,
3556                                          SourceRange ArgRange) {
3557   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3558   // scalar or vector data type argument..."
3559   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3560   // type (C99 6.2.5p18) or void.
3561   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3562     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3563       << T << ArgRange;
3564     return true;
3565   }
3566 
3567   assert((T->isVoidType() || !T->isIncompleteType()) &&
3568          "Scalar types should always be complete");
3569   return false;
3570 }
3571 
3572 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3573                                            SourceLocation Loc,
3574                                            SourceRange ArgRange,
3575                                            UnaryExprOrTypeTrait TraitKind) {
3576   // Invalid types must be hard errors for SFINAE in C++.
3577   if (S.LangOpts.CPlusPlus)
3578     return true;
3579 
3580   // C99 6.5.3.4p1:
3581   if (T->isFunctionType() &&
3582       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3583     // sizeof(function)/alignof(function) is allowed as an extension.
3584     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3585       << TraitKind << ArgRange;
3586     return false;
3587   }
3588 
3589   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3590   // this is an error (OpenCL v1.1 s6.3.k)
3591   if (T->isVoidType()) {
3592     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3593                                         : diag::ext_sizeof_alignof_void_type;
3594     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3595     return false;
3596   }
3597 
3598   return true;
3599 }
3600 
3601 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3602                                              SourceLocation Loc,
3603                                              SourceRange ArgRange,
3604                                              UnaryExprOrTypeTrait TraitKind) {
3605   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3606   // runtime doesn't allow it.
3607   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3608     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3609       << T << (TraitKind == UETT_SizeOf)
3610       << ArgRange;
3611     return true;
3612   }
3613 
3614   return false;
3615 }
3616 
3617 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3618 /// pointer type is equal to T) and emit a warning if it is.
3619 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3620                                      Expr *E) {
3621   // Don't warn if the operation changed the type.
3622   if (T != E->getType())
3623     return;
3624 
3625   // Now look for array decays.
3626   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3627   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3628     return;
3629 
3630   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3631                                              << ICE->getType()
3632                                              << ICE->getSubExpr()->getType();
3633 }
3634 
3635 /// \brief Check the constraints on expression operands to unary type expression
3636 /// and type traits.
3637 ///
3638 /// Completes any types necessary and validates the constraints on the operand
3639 /// expression. The logic mostly mirrors the type-based overload, but may modify
3640 /// the expression as it completes the type for that expression through template
3641 /// instantiation, etc.
3642 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3643                                             UnaryExprOrTypeTrait ExprKind) {
3644   QualType ExprTy = E->getType();
3645   assert(!ExprTy->isReferenceType());
3646 
3647   if (ExprKind == UETT_VecStep)
3648     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3649                                         E->getSourceRange());
3650 
3651   // Whitelist some types as extensions
3652   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3653                                       E->getSourceRange(), ExprKind))
3654     return false;
3655 
3656   // 'alignof' applied to an expression only requires the base element type of
3657   // the expression to be complete. 'sizeof' requires the expression's type to
3658   // be complete (and will attempt to complete it if it's an array of unknown
3659   // bound).
3660   if (ExprKind == UETT_AlignOf) {
3661     if (RequireCompleteType(E->getExprLoc(),
3662                             Context.getBaseElementType(E->getType()),
3663                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3664                             E->getSourceRange()))
3665       return true;
3666   } else {
3667     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3668                                 ExprKind, E->getSourceRange()))
3669       return true;
3670   }
3671 
3672   // Completing the expression's type may have changed it.
3673   ExprTy = E->getType();
3674   assert(!ExprTy->isReferenceType());
3675 
3676   if (ExprTy->isFunctionType()) {
3677     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3678       << ExprKind << E->getSourceRange();
3679     return true;
3680   }
3681 
3682   // The operand for sizeof and alignof is in an unevaluated expression context,
3683   // so side effects could result in unintended consequences.
3684   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3685       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3686     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3687 
3688   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3689                                        E->getSourceRange(), ExprKind))
3690     return true;
3691 
3692   if (ExprKind == UETT_SizeOf) {
3693     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3694       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3695         QualType OType = PVD->getOriginalType();
3696         QualType Type = PVD->getType();
3697         if (Type->isPointerType() && OType->isArrayType()) {
3698           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3699             << Type << OType;
3700           Diag(PVD->getLocation(), diag::note_declared_at);
3701         }
3702       }
3703     }
3704 
3705     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3706     // decays into a pointer and returns an unintended result. This is most
3707     // likely a typo for "sizeof(array) op x".
3708     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3709       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3710                                BO->getLHS());
3711       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3712                                BO->getRHS());
3713     }
3714   }
3715 
3716   return false;
3717 }
3718 
3719 /// \brief Check the constraints on operands to unary expression and type
3720 /// traits.
3721 ///
3722 /// This will complete any types necessary, and validate the various constraints
3723 /// on those operands.
3724 ///
3725 /// The UsualUnaryConversions() function is *not* called by this routine.
3726 /// C99 6.3.2.1p[2-4] all state:
3727 ///   Except when it is the operand of the sizeof operator ...
3728 ///
3729 /// C++ [expr.sizeof]p4
3730 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3731 ///   standard conversions are not applied to the operand of sizeof.
3732 ///
3733 /// This policy is followed for all of the unary trait expressions.
3734 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3735                                             SourceLocation OpLoc,
3736                                             SourceRange ExprRange,
3737                                             UnaryExprOrTypeTrait ExprKind) {
3738   if (ExprType->isDependentType())
3739     return false;
3740 
3741   // C++ [expr.sizeof]p2:
3742   //     When applied to a reference or a reference type, the result
3743   //     is the size of the referenced type.
3744   // C++11 [expr.alignof]p3:
3745   //     When alignof is applied to a reference type, the result
3746   //     shall be the alignment of the referenced type.
3747   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3748     ExprType = Ref->getPointeeType();
3749 
3750   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3751   //   When alignof or _Alignof is applied to an array type, the result
3752   //   is the alignment of the element type.
3753   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3754     ExprType = Context.getBaseElementType(ExprType);
3755 
3756   if (ExprKind == UETT_VecStep)
3757     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3758 
3759   // Whitelist some types as extensions
3760   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3761                                       ExprKind))
3762     return false;
3763 
3764   if (RequireCompleteType(OpLoc, ExprType,
3765                           diag::err_sizeof_alignof_incomplete_type,
3766                           ExprKind, ExprRange))
3767     return true;
3768 
3769   if (ExprType->isFunctionType()) {
3770     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3771       << ExprKind << ExprRange;
3772     return true;
3773   }
3774 
3775   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3776                                        ExprKind))
3777     return true;
3778 
3779   return false;
3780 }
3781 
3782 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3783   E = E->IgnoreParens();
3784 
3785   // Cannot know anything else if the expression is dependent.
3786   if (E->isTypeDependent())
3787     return false;
3788 
3789   if (E->getObjectKind() == OK_BitField) {
3790     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3791        << 1 << E->getSourceRange();
3792     return true;
3793   }
3794 
3795   ValueDecl *D = nullptr;
3796   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3797     D = DRE->getDecl();
3798   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3799     D = ME->getMemberDecl();
3800   }
3801 
3802   // If it's a field, require the containing struct to have a
3803   // complete definition so that we can compute the layout.
3804   //
3805   // This can happen in C++11 onwards, either by naming the member
3806   // in a way that is not transformed into a member access expression
3807   // (in an unevaluated operand, for instance), or by naming the member
3808   // in a trailing-return-type.
3809   //
3810   // For the record, since __alignof__ on expressions is a GCC
3811   // extension, GCC seems to permit this but always gives the
3812   // nonsensical answer 0.
3813   //
3814   // We don't really need the layout here --- we could instead just
3815   // directly check for all the appropriate alignment-lowing
3816   // attributes --- but that would require duplicating a lot of
3817   // logic that just isn't worth duplicating for such a marginal
3818   // use-case.
3819   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3820     // Fast path this check, since we at least know the record has a
3821     // definition if we can find a member of it.
3822     if (!FD->getParent()->isCompleteDefinition()) {
3823       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3824         << E->getSourceRange();
3825       return true;
3826     }
3827 
3828     // Otherwise, if it's a field, and the field doesn't have
3829     // reference type, then it must have a complete type (or be a
3830     // flexible array member, which we explicitly want to
3831     // white-list anyway), which makes the following checks trivial.
3832     if (!FD->getType()->isReferenceType())
3833       return false;
3834   }
3835 
3836   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3837 }
3838 
3839 bool Sema::CheckVecStepExpr(Expr *E) {
3840   E = E->IgnoreParens();
3841 
3842   // Cannot know anything else if the expression is dependent.
3843   if (E->isTypeDependent())
3844     return false;
3845 
3846   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3847 }
3848 
3849 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3850                                         CapturingScopeInfo *CSI) {
3851   assert(T->isVariablyModifiedType());
3852   assert(CSI != nullptr);
3853 
3854   // We're going to walk down into the type and look for VLA expressions.
3855   do {
3856     const Type *Ty = T.getTypePtr();
3857     switch (Ty->getTypeClass()) {
3858 #define TYPE(Class, Base)
3859 #define ABSTRACT_TYPE(Class, Base)
3860 #define NON_CANONICAL_TYPE(Class, Base)
3861 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3862 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3863 #include "clang/AST/TypeNodes.def"
3864       T = QualType();
3865       break;
3866     // These types are never variably-modified.
3867     case Type::Builtin:
3868     case Type::Complex:
3869     case Type::Vector:
3870     case Type::ExtVector:
3871     case Type::Record:
3872     case Type::Enum:
3873     case Type::Elaborated:
3874     case Type::TemplateSpecialization:
3875     case Type::ObjCObject:
3876     case Type::ObjCInterface:
3877     case Type::ObjCObjectPointer:
3878     case Type::ObjCTypeParam:
3879     case Type::Pipe:
3880       llvm_unreachable("type class is never variably-modified!");
3881     case Type::Adjusted:
3882       T = cast<AdjustedType>(Ty)->getOriginalType();
3883       break;
3884     case Type::Decayed:
3885       T = cast<DecayedType>(Ty)->getPointeeType();
3886       break;
3887     case Type::Pointer:
3888       T = cast<PointerType>(Ty)->getPointeeType();
3889       break;
3890     case Type::BlockPointer:
3891       T = cast<BlockPointerType>(Ty)->getPointeeType();
3892       break;
3893     case Type::LValueReference:
3894     case Type::RValueReference:
3895       T = cast<ReferenceType>(Ty)->getPointeeType();
3896       break;
3897     case Type::MemberPointer:
3898       T = cast<MemberPointerType>(Ty)->getPointeeType();
3899       break;
3900     case Type::ConstantArray:
3901     case Type::IncompleteArray:
3902       // Losing element qualification here is fine.
3903       T = cast<ArrayType>(Ty)->getElementType();
3904       break;
3905     case Type::VariableArray: {
3906       // Losing element qualification here is fine.
3907       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3908 
3909       // Unknown size indication requires no size computation.
3910       // Otherwise, evaluate and record it.
3911       if (auto Size = VAT->getSizeExpr()) {
3912         if (!CSI->isVLATypeCaptured(VAT)) {
3913           RecordDecl *CapRecord = nullptr;
3914           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3915             CapRecord = LSI->Lambda;
3916           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3917             CapRecord = CRSI->TheRecordDecl;
3918           }
3919           if (CapRecord) {
3920             auto ExprLoc = Size->getExprLoc();
3921             auto SizeType = Context.getSizeType();
3922             // Build the non-static data member.
3923             auto Field =
3924                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3925                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3926                                   /*BW*/ nullptr, /*Mutable*/ false,
3927                                   /*InitStyle*/ ICIS_NoInit);
3928             Field->setImplicit(true);
3929             Field->setAccess(AS_private);
3930             Field->setCapturedVLAType(VAT);
3931             CapRecord->addDecl(Field);
3932 
3933             CSI->addVLATypeCapture(ExprLoc, SizeType);
3934           }
3935         }
3936       }
3937       T = VAT->getElementType();
3938       break;
3939     }
3940     case Type::FunctionProto:
3941     case Type::FunctionNoProto:
3942       T = cast<FunctionType>(Ty)->getReturnType();
3943       break;
3944     case Type::Paren:
3945     case Type::TypeOf:
3946     case Type::UnaryTransform:
3947     case Type::Attributed:
3948     case Type::SubstTemplateTypeParm:
3949     case Type::PackExpansion:
3950       // Keep walking after single level desugaring.
3951       T = T.getSingleStepDesugaredType(Context);
3952       break;
3953     case Type::Typedef:
3954       T = cast<TypedefType>(Ty)->desugar();
3955       break;
3956     case Type::Decltype:
3957       T = cast<DecltypeType>(Ty)->desugar();
3958       break;
3959     case Type::Auto:
3960       T = cast<AutoType>(Ty)->getDeducedType();
3961       break;
3962     case Type::TypeOfExpr:
3963       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3964       break;
3965     case Type::Atomic:
3966       T = cast<AtomicType>(Ty)->getValueType();
3967       break;
3968     }
3969   } while (!T.isNull() && T->isVariablyModifiedType());
3970 }
3971 
3972 /// \brief Build a sizeof or alignof expression given a type operand.
3973 ExprResult
3974 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3975                                      SourceLocation OpLoc,
3976                                      UnaryExprOrTypeTrait ExprKind,
3977                                      SourceRange R) {
3978   if (!TInfo)
3979     return ExprError();
3980 
3981   QualType T = TInfo->getType();
3982 
3983   if (!T->isDependentType() &&
3984       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3985     return ExprError();
3986 
3987   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3988     if (auto *TT = T->getAs<TypedefType>()) {
3989       for (auto I = FunctionScopes.rbegin(),
3990                 E = std::prev(FunctionScopes.rend());
3991            I != E; ++I) {
3992         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3993         if (CSI == nullptr)
3994           break;
3995         DeclContext *DC = nullptr;
3996         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3997           DC = LSI->CallOperator;
3998         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3999           DC = CRSI->TheCapturedDecl;
4000         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4001           DC = BSI->TheDecl;
4002         if (DC) {
4003           if (DC->containsDecl(TT->getDecl()))
4004             break;
4005           captureVariablyModifiedType(Context, T, CSI);
4006         }
4007       }
4008     }
4009   }
4010 
4011   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4012   return new (Context) UnaryExprOrTypeTraitExpr(
4013       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4014 }
4015 
4016 /// \brief Build a sizeof or alignof expression given an expression
4017 /// operand.
4018 ExprResult
4019 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4020                                      UnaryExprOrTypeTrait ExprKind) {
4021   ExprResult PE = CheckPlaceholderExpr(E);
4022   if (PE.isInvalid())
4023     return ExprError();
4024 
4025   E = PE.get();
4026 
4027   // Verify that the operand is valid.
4028   bool isInvalid = false;
4029   if (E->isTypeDependent()) {
4030     // Delay type-checking for type-dependent expressions.
4031   } else if (ExprKind == UETT_AlignOf) {
4032     isInvalid = CheckAlignOfExpr(*this, E);
4033   } else if (ExprKind == UETT_VecStep) {
4034     isInvalid = CheckVecStepExpr(E);
4035   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4036       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4037       isInvalid = true;
4038   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4039     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4040     isInvalid = true;
4041   } else {
4042     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4043   }
4044 
4045   if (isInvalid)
4046     return ExprError();
4047 
4048   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4049     PE = TransformToPotentiallyEvaluated(E);
4050     if (PE.isInvalid()) return ExprError();
4051     E = PE.get();
4052   }
4053 
4054   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4055   return new (Context) UnaryExprOrTypeTraitExpr(
4056       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4057 }
4058 
4059 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4060 /// expr and the same for @c alignof and @c __alignof
4061 /// Note that the ArgRange is invalid if isType is false.
4062 ExprResult
4063 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4064                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4065                                     void *TyOrEx, SourceRange ArgRange) {
4066   // If error parsing type, ignore.
4067   if (!TyOrEx) return ExprError();
4068 
4069   if (IsType) {
4070     TypeSourceInfo *TInfo;
4071     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4072     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4073   }
4074 
4075   Expr *ArgEx = (Expr *)TyOrEx;
4076   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4077   return Result;
4078 }
4079 
4080 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4081                                      bool IsReal) {
4082   if (V.get()->isTypeDependent())
4083     return S.Context.DependentTy;
4084 
4085   // _Real and _Imag are only l-values for normal l-values.
4086   if (V.get()->getObjectKind() != OK_Ordinary) {
4087     V = S.DefaultLvalueConversion(V.get());
4088     if (V.isInvalid())
4089       return QualType();
4090   }
4091 
4092   // These operators return the element type of a complex type.
4093   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4094     return CT->getElementType();
4095 
4096   // Otherwise they pass through real integer and floating point types here.
4097   if (V.get()->getType()->isArithmeticType())
4098     return V.get()->getType();
4099 
4100   // Test for placeholders.
4101   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4102   if (PR.isInvalid()) return QualType();
4103   if (PR.get() != V.get()) {
4104     V = PR;
4105     return CheckRealImagOperand(S, V, Loc, IsReal);
4106   }
4107 
4108   // Reject anything else.
4109   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4110     << (IsReal ? "__real" : "__imag");
4111   return QualType();
4112 }
4113 
4114 
4115 
4116 ExprResult
4117 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4118                           tok::TokenKind Kind, Expr *Input) {
4119   UnaryOperatorKind Opc;
4120   switch (Kind) {
4121   default: llvm_unreachable("Unknown unary op!");
4122   case tok::plusplus:   Opc = UO_PostInc; break;
4123   case tok::minusminus: Opc = UO_PostDec; break;
4124   }
4125 
4126   // Since this might is a postfix expression, get rid of ParenListExprs.
4127   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4128   if (Result.isInvalid()) return ExprError();
4129   Input = Result.get();
4130 
4131   return BuildUnaryOp(S, OpLoc, Opc, Input);
4132 }
4133 
4134 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4135 ///
4136 /// \return true on error
4137 static bool checkArithmeticOnObjCPointer(Sema &S,
4138                                          SourceLocation opLoc,
4139                                          Expr *op) {
4140   assert(op->getType()->isObjCObjectPointerType());
4141   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4142       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4143     return false;
4144 
4145   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4146     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4147     << op->getSourceRange();
4148   return true;
4149 }
4150 
4151 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4152   auto *BaseNoParens = Base->IgnoreParens();
4153   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4154     return MSProp->getPropertyDecl()->getType()->isArrayType();
4155   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4156 }
4157 
4158 ExprResult
4159 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4160                               Expr *idx, SourceLocation rbLoc) {
4161   if (base && !base->getType().isNull() &&
4162       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4163     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4164                                     /*Length=*/nullptr, rbLoc);
4165 
4166   // Since this might be a postfix expression, get rid of ParenListExprs.
4167   if (isa<ParenListExpr>(base)) {
4168     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4169     if (result.isInvalid()) return ExprError();
4170     base = result.get();
4171   }
4172 
4173   // Handle any non-overload placeholder types in the base and index
4174   // expressions.  We can't handle overloads here because the other
4175   // operand might be an overloadable type, in which case the overload
4176   // resolution for the operator overload should get the first crack
4177   // at the overload.
4178   bool IsMSPropertySubscript = false;
4179   if (base->getType()->isNonOverloadPlaceholderType()) {
4180     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4181     if (!IsMSPropertySubscript) {
4182       ExprResult result = CheckPlaceholderExpr(base);
4183       if (result.isInvalid())
4184         return ExprError();
4185       base = result.get();
4186     }
4187   }
4188   if (idx->getType()->isNonOverloadPlaceholderType()) {
4189     ExprResult result = CheckPlaceholderExpr(idx);
4190     if (result.isInvalid()) return ExprError();
4191     idx = result.get();
4192   }
4193 
4194   // Build an unanalyzed expression if either operand is type-dependent.
4195   if (getLangOpts().CPlusPlus &&
4196       (base->isTypeDependent() || idx->isTypeDependent())) {
4197     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4198                                             VK_LValue, OK_Ordinary, rbLoc);
4199   }
4200 
4201   // MSDN, property (C++)
4202   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4203   // This attribute can also be used in the declaration of an empty array in a
4204   // class or structure definition. For example:
4205   // __declspec(property(get=GetX, put=PutX)) int x[];
4206   // The above statement indicates that x[] can be used with one or more array
4207   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4208   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4209   if (IsMSPropertySubscript) {
4210     // Build MS property subscript expression if base is MS property reference
4211     // or MS property subscript.
4212     return new (Context) MSPropertySubscriptExpr(
4213         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4214   }
4215 
4216   // Use C++ overloaded-operator rules if either operand has record
4217   // type.  The spec says to do this if either type is *overloadable*,
4218   // but enum types can't declare subscript operators or conversion
4219   // operators, so there's nothing interesting for overload resolution
4220   // to do if there aren't any record types involved.
4221   //
4222   // ObjC pointers have their own subscripting logic that is not tied
4223   // to overload resolution and so should not take this path.
4224   if (getLangOpts().CPlusPlus &&
4225       (base->getType()->isRecordType() ||
4226        (!base->getType()->isObjCObjectPointerType() &&
4227         idx->getType()->isRecordType()))) {
4228     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4229   }
4230 
4231   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4232 }
4233 
4234 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4235                                           Expr *LowerBound,
4236                                           SourceLocation ColonLoc, Expr *Length,
4237                                           SourceLocation RBLoc) {
4238   if (Base->getType()->isPlaceholderType() &&
4239       !Base->getType()->isSpecificPlaceholderType(
4240           BuiltinType::OMPArraySection)) {
4241     ExprResult Result = CheckPlaceholderExpr(Base);
4242     if (Result.isInvalid())
4243       return ExprError();
4244     Base = Result.get();
4245   }
4246   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4247     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4248     if (Result.isInvalid())
4249       return ExprError();
4250     Result = DefaultLvalueConversion(Result.get());
4251     if (Result.isInvalid())
4252       return ExprError();
4253     LowerBound = Result.get();
4254   }
4255   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4256     ExprResult Result = CheckPlaceholderExpr(Length);
4257     if (Result.isInvalid())
4258       return ExprError();
4259     Result = DefaultLvalueConversion(Result.get());
4260     if (Result.isInvalid())
4261       return ExprError();
4262     Length = Result.get();
4263   }
4264 
4265   // Build an unanalyzed expression if either operand is type-dependent.
4266   if (Base->isTypeDependent() ||
4267       (LowerBound &&
4268        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4269       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4270     return new (Context)
4271         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4272                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4273   }
4274 
4275   // Perform default conversions.
4276   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4277   QualType ResultTy;
4278   if (OriginalTy->isAnyPointerType()) {
4279     ResultTy = OriginalTy->getPointeeType();
4280   } else if (OriginalTy->isArrayType()) {
4281     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4282   } else {
4283     return ExprError(
4284         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4285         << Base->getSourceRange());
4286   }
4287   // C99 6.5.2.1p1
4288   if (LowerBound) {
4289     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4290                                                       LowerBound);
4291     if (Res.isInvalid())
4292       return ExprError(Diag(LowerBound->getExprLoc(),
4293                             diag::err_omp_typecheck_section_not_integer)
4294                        << 0 << LowerBound->getSourceRange());
4295     LowerBound = Res.get();
4296 
4297     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4298         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4299       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4300           << 0 << LowerBound->getSourceRange();
4301   }
4302   if (Length) {
4303     auto Res =
4304         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4305     if (Res.isInvalid())
4306       return ExprError(Diag(Length->getExprLoc(),
4307                             diag::err_omp_typecheck_section_not_integer)
4308                        << 1 << Length->getSourceRange());
4309     Length = Res.get();
4310 
4311     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4312         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4313       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4314           << 1 << Length->getSourceRange();
4315   }
4316 
4317   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4318   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4319   // type. Note that functions are not objects, and that (in C99 parlance)
4320   // incomplete types are not object types.
4321   if (ResultTy->isFunctionType()) {
4322     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4323         << ResultTy << Base->getSourceRange();
4324     return ExprError();
4325   }
4326 
4327   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4328                           diag::err_omp_section_incomplete_type, Base))
4329     return ExprError();
4330 
4331   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4332     llvm::APSInt LowerBoundValue;
4333     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4334       // OpenMP 4.5, [2.4 Array Sections]
4335       // The array section must be a subset of the original array.
4336       if (LowerBoundValue.isNegative()) {
4337         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4338             << LowerBound->getSourceRange();
4339         return ExprError();
4340       }
4341     }
4342   }
4343 
4344   if (Length) {
4345     llvm::APSInt LengthValue;
4346     if (Length->EvaluateAsInt(LengthValue, Context)) {
4347       // OpenMP 4.5, [2.4 Array Sections]
4348       // The length must evaluate to non-negative integers.
4349       if (LengthValue.isNegative()) {
4350         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4351             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4352             << Length->getSourceRange();
4353         return ExprError();
4354       }
4355     }
4356   } else if (ColonLoc.isValid() &&
4357              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4358                                       !OriginalTy->isVariableArrayType()))) {
4359     // OpenMP 4.5, [2.4 Array Sections]
4360     // When the size of the array dimension is not known, the length must be
4361     // specified explicitly.
4362     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4363         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4364     return ExprError();
4365   }
4366 
4367   if (!Base->getType()->isSpecificPlaceholderType(
4368           BuiltinType::OMPArraySection)) {
4369     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4370     if (Result.isInvalid())
4371       return ExprError();
4372     Base = Result.get();
4373   }
4374   return new (Context)
4375       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4376                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4377 }
4378 
4379 ExprResult
4380 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4381                                       Expr *Idx, SourceLocation RLoc) {
4382   Expr *LHSExp = Base;
4383   Expr *RHSExp = Idx;
4384 
4385   // Perform default conversions.
4386   if (!LHSExp->getType()->getAs<VectorType>()) {
4387     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4388     if (Result.isInvalid())
4389       return ExprError();
4390     LHSExp = Result.get();
4391   }
4392   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4393   if (Result.isInvalid())
4394     return ExprError();
4395   RHSExp = Result.get();
4396 
4397   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4398   ExprValueKind VK = VK_LValue;
4399   ExprObjectKind OK = OK_Ordinary;
4400 
4401   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4402   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4403   // in the subscript position. As a result, we need to derive the array base
4404   // and index from the expression types.
4405   Expr *BaseExpr, *IndexExpr;
4406   QualType ResultType;
4407   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4408     BaseExpr = LHSExp;
4409     IndexExpr = RHSExp;
4410     ResultType = Context.DependentTy;
4411   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4412     BaseExpr = LHSExp;
4413     IndexExpr = RHSExp;
4414     ResultType = PTy->getPointeeType();
4415   } else if (const ObjCObjectPointerType *PTy =
4416                LHSTy->getAs<ObjCObjectPointerType>()) {
4417     BaseExpr = LHSExp;
4418     IndexExpr = RHSExp;
4419 
4420     // Use custom logic if this should be the pseudo-object subscript
4421     // expression.
4422     if (!LangOpts.isSubscriptPointerArithmetic())
4423       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4424                                           nullptr);
4425 
4426     ResultType = PTy->getPointeeType();
4427   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4428      // Handle the uncommon case of "123[Ptr]".
4429     BaseExpr = RHSExp;
4430     IndexExpr = LHSExp;
4431     ResultType = PTy->getPointeeType();
4432   } else if (const ObjCObjectPointerType *PTy =
4433                RHSTy->getAs<ObjCObjectPointerType>()) {
4434      // Handle the uncommon case of "123[Ptr]".
4435     BaseExpr = RHSExp;
4436     IndexExpr = LHSExp;
4437     ResultType = PTy->getPointeeType();
4438     if (!LangOpts.isSubscriptPointerArithmetic()) {
4439       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4440         << ResultType << BaseExpr->getSourceRange();
4441       return ExprError();
4442     }
4443   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4444     BaseExpr = LHSExp;    // vectors: V[123]
4445     IndexExpr = RHSExp;
4446     VK = LHSExp->getValueKind();
4447     if (VK != VK_RValue)
4448       OK = OK_VectorComponent;
4449 
4450     // FIXME: need to deal with const...
4451     ResultType = VTy->getElementType();
4452   } else if (LHSTy->isArrayType()) {
4453     // If we see an array that wasn't promoted by
4454     // DefaultFunctionArrayLvalueConversion, it must be an array that
4455     // wasn't promoted because of the C90 rule that doesn't
4456     // allow promoting non-lvalue arrays.  Warn, then
4457     // force the promotion here.
4458     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4459         LHSExp->getSourceRange();
4460     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4461                                CK_ArrayToPointerDecay).get();
4462     LHSTy = LHSExp->getType();
4463 
4464     BaseExpr = LHSExp;
4465     IndexExpr = RHSExp;
4466     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4467   } else if (RHSTy->isArrayType()) {
4468     // Same as previous, except for 123[f().a] case
4469     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4470         RHSExp->getSourceRange();
4471     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4472                                CK_ArrayToPointerDecay).get();
4473     RHSTy = RHSExp->getType();
4474 
4475     BaseExpr = RHSExp;
4476     IndexExpr = LHSExp;
4477     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4478   } else {
4479     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4480        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4481   }
4482   // C99 6.5.2.1p1
4483   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4484     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4485                      << IndexExpr->getSourceRange());
4486 
4487   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4488        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4489          && !IndexExpr->isTypeDependent())
4490     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4491 
4492   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4493   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4494   // type. Note that Functions are not objects, and that (in C99 parlance)
4495   // incomplete types are not object types.
4496   if (ResultType->isFunctionType()) {
4497     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4498       << ResultType << BaseExpr->getSourceRange();
4499     return ExprError();
4500   }
4501 
4502   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4503     // GNU extension: subscripting on pointer to void
4504     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4505       << BaseExpr->getSourceRange();
4506 
4507     // C forbids expressions of unqualified void type from being l-values.
4508     // See IsCForbiddenLValueType.
4509     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4510   } else if (!ResultType->isDependentType() &&
4511       RequireCompleteType(LLoc, ResultType,
4512                           diag::err_subscript_incomplete_type, BaseExpr))
4513     return ExprError();
4514 
4515   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4516          !ResultType.isCForbiddenLValueType());
4517 
4518   return new (Context)
4519       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4520 }
4521 
4522 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4523                                         FunctionDecl *FD,
4524                                         ParmVarDecl *Param) {
4525   if (Param->hasUnparsedDefaultArg()) {
4526     Diag(CallLoc,
4527          diag::err_use_of_default_argument_to_function_declared_later) <<
4528       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4529     Diag(UnparsedDefaultArgLocs[Param],
4530          diag::note_default_argument_declared_here);
4531     return ExprError();
4532   }
4533 
4534   if (Param->hasUninstantiatedDefaultArg()) {
4535     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4536 
4537     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4538                                                  Param);
4539 
4540     // Instantiate the expression.
4541     MultiLevelTemplateArgumentList MutiLevelArgList
4542       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4543 
4544     InstantiatingTemplate Inst(*this, CallLoc, Param,
4545                                MutiLevelArgList.getInnermost());
4546     if (Inst.isInvalid())
4547       return ExprError();
4548     if (Inst.isAlreadyInstantiating()) {
4549       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4550       Param->setInvalidDecl();
4551       return ExprError();
4552     }
4553 
4554     ExprResult Result;
4555     {
4556       // C++ [dcl.fct.default]p5:
4557       //   The names in the [default argument] expression are bound, and
4558       //   the semantic constraints are checked, at the point where the
4559       //   default argument expression appears.
4560       ContextRAII SavedContext(*this, FD);
4561       LocalInstantiationScope Local(*this);
4562       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4563     }
4564     if (Result.isInvalid())
4565       return ExprError();
4566 
4567     // Check the expression as an initializer for the parameter.
4568     InitializedEntity Entity
4569       = InitializedEntity::InitializeParameter(Context, Param);
4570     InitializationKind Kind
4571       = InitializationKind::CreateCopy(Param->getLocation(),
4572              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4573     Expr *ResultE = Result.getAs<Expr>();
4574 
4575     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4576     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4577     if (Result.isInvalid())
4578       return ExprError();
4579 
4580     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4581                                  Param->getOuterLocStart());
4582     if (Result.isInvalid())
4583       return ExprError();
4584 
4585     // Remember the instantiated default argument.
4586     Param->setDefaultArg(Result.getAs<Expr>());
4587     if (ASTMutationListener *L = getASTMutationListener()) {
4588       L->DefaultArgumentInstantiated(Param);
4589     }
4590   }
4591 
4592   // If the default argument expression is not set yet, we are building it now.
4593   if (!Param->hasInit()) {
4594     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4595     Param->setInvalidDecl();
4596     return ExprError();
4597   }
4598 
4599   // If the default expression creates temporaries, we need to
4600   // push them to the current stack of expression temporaries so they'll
4601   // be properly destroyed.
4602   // FIXME: We should really be rebuilding the default argument with new
4603   // bound temporaries; see the comment in PR5810.
4604   // We don't need to do that with block decls, though, because
4605   // blocks in default argument expression can never capture anything.
4606   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4607     // Set the "needs cleanups" bit regardless of whether there are
4608     // any explicit objects.
4609     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4610 
4611     // Append all the objects to the cleanup list.  Right now, this
4612     // should always be a no-op, because blocks in default argument
4613     // expressions should never be able to capture anything.
4614     assert(!Init->getNumObjects() &&
4615            "default argument expression has capturing blocks?");
4616   }
4617 
4618   // We already type-checked the argument, so we know it works.
4619   // Just mark all of the declarations in this potentially-evaluated expression
4620   // as being "referenced".
4621   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4622                                    /*SkipLocalVariables=*/true);
4623   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4624 }
4625 
4626 
4627 Sema::VariadicCallType
4628 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4629                           Expr *Fn) {
4630   if (Proto && Proto->isVariadic()) {
4631     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4632       return VariadicConstructor;
4633     else if (Fn && Fn->getType()->isBlockPointerType())
4634       return VariadicBlock;
4635     else if (FDecl) {
4636       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4637         if (Method->isInstance())
4638           return VariadicMethod;
4639     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4640       return VariadicMethod;
4641     return VariadicFunction;
4642   }
4643   return VariadicDoesNotApply;
4644 }
4645 
4646 namespace {
4647 class FunctionCallCCC : public FunctionCallFilterCCC {
4648 public:
4649   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4650                   unsigned NumArgs, MemberExpr *ME)
4651       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4652         FunctionName(FuncName) {}
4653 
4654   bool ValidateCandidate(const TypoCorrection &candidate) override {
4655     if (!candidate.getCorrectionSpecifier() ||
4656         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4657       return false;
4658     }
4659 
4660     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4661   }
4662 
4663 private:
4664   const IdentifierInfo *const FunctionName;
4665 };
4666 }
4667 
4668 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4669                                                FunctionDecl *FDecl,
4670                                                ArrayRef<Expr *> Args) {
4671   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4672   DeclarationName FuncName = FDecl->getDeclName();
4673   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4674 
4675   if (TypoCorrection Corrected = S.CorrectTypo(
4676           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4677           S.getScopeForContext(S.CurContext), nullptr,
4678           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4679                                              Args.size(), ME),
4680           Sema::CTK_ErrorRecovery)) {
4681     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4682       if (Corrected.isOverloaded()) {
4683         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4684         OverloadCandidateSet::iterator Best;
4685         for (NamedDecl *CD : Corrected) {
4686           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4687             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4688                                    OCS);
4689         }
4690         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4691         case OR_Success:
4692           ND = Best->FoundDecl;
4693           Corrected.setCorrectionDecl(ND);
4694           break;
4695         default:
4696           break;
4697         }
4698       }
4699       ND = ND->getUnderlyingDecl();
4700       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4701         return Corrected;
4702     }
4703   }
4704   return TypoCorrection();
4705 }
4706 
4707 /// ConvertArgumentsForCall - Converts the arguments specified in
4708 /// Args/NumArgs to the parameter types of the function FDecl with
4709 /// function prototype Proto. Call is the call expression itself, and
4710 /// Fn is the function expression. For a C++ member function, this
4711 /// routine does not attempt to convert the object argument. Returns
4712 /// true if the call is ill-formed.
4713 bool
4714 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4715                               FunctionDecl *FDecl,
4716                               const FunctionProtoType *Proto,
4717                               ArrayRef<Expr *> Args,
4718                               SourceLocation RParenLoc,
4719                               bool IsExecConfig) {
4720   // Bail out early if calling a builtin with custom typechecking.
4721   if (FDecl)
4722     if (unsigned ID = FDecl->getBuiltinID())
4723       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4724         return false;
4725 
4726   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4727   // assignment, to the types of the corresponding parameter, ...
4728   unsigned NumParams = Proto->getNumParams();
4729   bool Invalid = false;
4730   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4731   unsigned FnKind = Fn->getType()->isBlockPointerType()
4732                        ? 1 /* block */
4733                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4734                                        : 0 /* function */);
4735 
4736   // If too few arguments are available (and we don't have default
4737   // arguments for the remaining parameters), don't make the call.
4738   if (Args.size() < NumParams) {
4739     if (Args.size() < MinArgs) {
4740       TypoCorrection TC;
4741       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4742         unsigned diag_id =
4743             MinArgs == NumParams && !Proto->isVariadic()
4744                 ? diag::err_typecheck_call_too_few_args_suggest
4745                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4746         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4747                                         << static_cast<unsigned>(Args.size())
4748                                         << TC.getCorrectionRange());
4749       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4750         Diag(RParenLoc,
4751              MinArgs == NumParams && !Proto->isVariadic()
4752                  ? diag::err_typecheck_call_too_few_args_one
4753                  : diag::err_typecheck_call_too_few_args_at_least_one)
4754             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4755       else
4756         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4757                             ? diag::err_typecheck_call_too_few_args
4758                             : diag::err_typecheck_call_too_few_args_at_least)
4759             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4760             << Fn->getSourceRange();
4761 
4762       // Emit the location of the prototype.
4763       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4764         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4765           << FDecl;
4766 
4767       return true;
4768     }
4769     Call->setNumArgs(Context, NumParams);
4770   }
4771 
4772   // If too many are passed and not variadic, error on the extras and drop
4773   // them.
4774   if (Args.size() > NumParams) {
4775     if (!Proto->isVariadic()) {
4776       TypoCorrection TC;
4777       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4778         unsigned diag_id =
4779             MinArgs == NumParams && !Proto->isVariadic()
4780                 ? diag::err_typecheck_call_too_many_args_suggest
4781                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4782         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4783                                         << static_cast<unsigned>(Args.size())
4784                                         << TC.getCorrectionRange());
4785       } else if (NumParams == 1 && FDecl &&
4786                  FDecl->getParamDecl(0)->getDeclName())
4787         Diag(Args[NumParams]->getLocStart(),
4788              MinArgs == NumParams
4789                  ? diag::err_typecheck_call_too_many_args_one
4790                  : diag::err_typecheck_call_too_many_args_at_most_one)
4791             << FnKind << FDecl->getParamDecl(0)
4792             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4793             << SourceRange(Args[NumParams]->getLocStart(),
4794                            Args.back()->getLocEnd());
4795       else
4796         Diag(Args[NumParams]->getLocStart(),
4797              MinArgs == NumParams
4798                  ? diag::err_typecheck_call_too_many_args
4799                  : diag::err_typecheck_call_too_many_args_at_most)
4800             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4801             << Fn->getSourceRange()
4802             << SourceRange(Args[NumParams]->getLocStart(),
4803                            Args.back()->getLocEnd());
4804 
4805       // Emit the location of the prototype.
4806       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4807         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4808           << FDecl;
4809 
4810       // This deletes the extra arguments.
4811       Call->setNumArgs(Context, NumParams);
4812       return true;
4813     }
4814   }
4815   SmallVector<Expr *, 8> AllArgs;
4816   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4817 
4818   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4819                                    Proto, 0, Args, AllArgs, CallType);
4820   if (Invalid)
4821     return true;
4822   unsigned TotalNumArgs = AllArgs.size();
4823   for (unsigned i = 0; i < TotalNumArgs; ++i)
4824     Call->setArg(i, AllArgs[i]);
4825 
4826   return false;
4827 }
4828 
4829 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4830                                   const FunctionProtoType *Proto,
4831                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4832                                   SmallVectorImpl<Expr *> &AllArgs,
4833                                   VariadicCallType CallType, bool AllowExplicit,
4834                                   bool IsListInitialization) {
4835   unsigned NumParams = Proto->getNumParams();
4836   bool Invalid = false;
4837   size_t ArgIx = 0;
4838   // Continue to check argument types (even if we have too few/many args).
4839   for (unsigned i = FirstParam; i < NumParams; i++) {
4840     QualType ProtoArgType = Proto->getParamType(i);
4841 
4842     Expr *Arg;
4843     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4844     if (ArgIx < Args.size()) {
4845       Arg = Args[ArgIx++];
4846 
4847       if (RequireCompleteType(Arg->getLocStart(),
4848                               ProtoArgType,
4849                               diag::err_call_incomplete_argument, Arg))
4850         return true;
4851 
4852       // Strip the unbridged-cast placeholder expression off, if applicable.
4853       bool CFAudited = false;
4854       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4855           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4856           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4857         Arg = stripARCUnbridgedCast(Arg);
4858       else if (getLangOpts().ObjCAutoRefCount &&
4859                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4860                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4861         CFAudited = true;
4862 
4863       InitializedEntity Entity =
4864           Param ? InitializedEntity::InitializeParameter(Context, Param,
4865                                                          ProtoArgType)
4866                 : InitializedEntity::InitializeParameter(
4867                       Context, ProtoArgType, Proto->isParamConsumed(i));
4868 
4869       // Remember that parameter belongs to a CF audited API.
4870       if (CFAudited)
4871         Entity.setParameterCFAudited();
4872 
4873       ExprResult ArgE = PerformCopyInitialization(
4874           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4875       if (ArgE.isInvalid())
4876         return true;
4877 
4878       Arg = ArgE.getAs<Expr>();
4879     } else {
4880       assert(Param && "can't use default arguments without a known callee");
4881 
4882       ExprResult ArgExpr =
4883         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4884       if (ArgExpr.isInvalid())
4885         return true;
4886 
4887       Arg = ArgExpr.getAs<Expr>();
4888     }
4889 
4890     // Check for array bounds violations for each argument to the call. This
4891     // check only triggers warnings when the argument isn't a more complex Expr
4892     // with its own checking, such as a BinaryOperator.
4893     CheckArrayAccess(Arg);
4894 
4895     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4896     CheckStaticArrayArgument(CallLoc, Param, Arg);
4897 
4898     AllArgs.push_back(Arg);
4899   }
4900 
4901   // If this is a variadic call, handle args passed through "...".
4902   if (CallType != VariadicDoesNotApply) {
4903     // Assume that extern "C" functions with variadic arguments that
4904     // return __unknown_anytype aren't *really* variadic.
4905     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4906         FDecl->isExternC()) {
4907       for (Expr *A : Args.slice(ArgIx)) {
4908         QualType paramType; // ignored
4909         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4910         Invalid |= arg.isInvalid();
4911         AllArgs.push_back(arg.get());
4912       }
4913 
4914     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4915     } else {
4916       for (Expr *A : Args.slice(ArgIx)) {
4917         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4918         Invalid |= Arg.isInvalid();
4919         AllArgs.push_back(Arg.get());
4920       }
4921     }
4922 
4923     // Check for array bounds violations.
4924     for (Expr *A : Args.slice(ArgIx))
4925       CheckArrayAccess(A);
4926   }
4927   return Invalid;
4928 }
4929 
4930 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4931   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4932   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4933     TL = DTL.getOriginalLoc();
4934   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4935     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4936       << ATL.getLocalSourceRange();
4937 }
4938 
4939 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4940 /// array parameter, check that it is non-null, and that if it is formed by
4941 /// array-to-pointer decay, the underlying array is sufficiently large.
4942 ///
4943 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4944 /// array type derivation, then for each call to the function, the value of the
4945 /// corresponding actual argument shall provide access to the first element of
4946 /// an array with at least as many elements as specified by the size expression.
4947 void
4948 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4949                                ParmVarDecl *Param,
4950                                const Expr *ArgExpr) {
4951   // Static array parameters are not supported in C++.
4952   if (!Param || getLangOpts().CPlusPlus)
4953     return;
4954 
4955   QualType OrigTy = Param->getOriginalType();
4956 
4957   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4958   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4959     return;
4960 
4961   if (ArgExpr->isNullPointerConstant(Context,
4962                                      Expr::NPC_NeverValueDependent)) {
4963     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4964     DiagnoseCalleeStaticArrayParam(*this, Param);
4965     return;
4966   }
4967 
4968   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4969   if (!CAT)
4970     return;
4971 
4972   const ConstantArrayType *ArgCAT =
4973     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4974   if (!ArgCAT)
4975     return;
4976 
4977   if (ArgCAT->getSize().ult(CAT->getSize())) {
4978     Diag(CallLoc, diag::warn_static_array_too_small)
4979       << ArgExpr->getSourceRange()
4980       << (unsigned) ArgCAT->getSize().getZExtValue()
4981       << (unsigned) CAT->getSize().getZExtValue();
4982     DiagnoseCalleeStaticArrayParam(*this, Param);
4983   }
4984 }
4985 
4986 /// Given a function expression of unknown-any type, try to rebuild it
4987 /// to have a function type.
4988 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4989 
4990 /// Is the given type a placeholder that we need to lower out
4991 /// immediately during argument processing?
4992 static bool isPlaceholderToRemoveAsArg(QualType type) {
4993   // Placeholders are never sugared.
4994   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4995   if (!placeholder) return false;
4996 
4997   switch (placeholder->getKind()) {
4998   // Ignore all the non-placeholder types.
4999 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5000   case BuiltinType::Id:
5001 #include "clang/Basic/OpenCLImageTypes.def"
5002 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5003 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5004 #include "clang/AST/BuiltinTypes.def"
5005     return false;
5006 
5007   // We cannot lower out overload sets; they might validly be resolved
5008   // by the call machinery.
5009   case BuiltinType::Overload:
5010     return false;
5011 
5012   // Unbridged casts in ARC can be handled in some call positions and
5013   // should be left in place.
5014   case BuiltinType::ARCUnbridgedCast:
5015     return false;
5016 
5017   // Pseudo-objects should be converted as soon as possible.
5018   case BuiltinType::PseudoObject:
5019     return true;
5020 
5021   // The debugger mode could theoretically but currently does not try
5022   // to resolve unknown-typed arguments based on known parameter types.
5023   case BuiltinType::UnknownAny:
5024     return true;
5025 
5026   // These are always invalid as call arguments and should be reported.
5027   case BuiltinType::BoundMember:
5028   case BuiltinType::BuiltinFn:
5029   case BuiltinType::OMPArraySection:
5030     return true;
5031 
5032   }
5033   llvm_unreachable("bad builtin type kind");
5034 }
5035 
5036 /// Check an argument list for placeholders that we won't try to
5037 /// handle later.
5038 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5039   // Apply this processing to all the arguments at once instead of
5040   // dying at the first failure.
5041   bool hasInvalid = false;
5042   for (size_t i = 0, e = args.size(); i != e; i++) {
5043     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5044       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5045       if (result.isInvalid()) hasInvalid = true;
5046       else args[i] = result.get();
5047     } else if (hasInvalid) {
5048       (void)S.CorrectDelayedTyposInExpr(args[i]);
5049     }
5050   }
5051   return hasInvalid;
5052 }
5053 
5054 /// If a builtin function has a pointer argument with no explicit address
5055 /// space, then it should be able to accept a pointer to any address
5056 /// space as input.  In order to do this, we need to replace the
5057 /// standard builtin declaration with one that uses the same address space
5058 /// as the call.
5059 ///
5060 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5061 ///                  it does not contain any pointer arguments without
5062 ///                  an address space qualifer.  Otherwise the rewritten
5063 ///                  FunctionDecl is returned.
5064 /// TODO: Handle pointer return types.
5065 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5066                                                 const FunctionDecl *FDecl,
5067                                                 MultiExprArg ArgExprs) {
5068 
5069   QualType DeclType = FDecl->getType();
5070   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5071 
5072   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5073       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5074     return nullptr;
5075 
5076   bool NeedsNewDecl = false;
5077   unsigned i = 0;
5078   SmallVector<QualType, 8> OverloadParams;
5079 
5080   for (QualType ParamType : FT->param_types()) {
5081 
5082     // Convert array arguments to pointer to simplify type lookup.
5083     ExprResult ArgRes =
5084         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5085     if (ArgRes.isInvalid())
5086       return nullptr;
5087     Expr *Arg = ArgRes.get();
5088     QualType ArgType = Arg->getType();
5089     if (!ParamType->isPointerType() ||
5090         ParamType.getQualifiers().hasAddressSpace() ||
5091         !ArgType->isPointerType() ||
5092         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5093       OverloadParams.push_back(ParamType);
5094       continue;
5095     }
5096 
5097     NeedsNewDecl = true;
5098     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5099 
5100     QualType PointeeType = ParamType->getPointeeType();
5101     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5102     OverloadParams.push_back(Context.getPointerType(PointeeType));
5103   }
5104 
5105   if (!NeedsNewDecl)
5106     return nullptr;
5107 
5108   FunctionProtoType::ExtProtoInfo EPI;
5109   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5110                                                 OverloadParams, EPI);
5111   DeclContext *Parent = Context.getTranslationUnitDecl();
5112   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5113                                                     FDecl->getLocation(),
5114                                                     FDecl->getLocation(),
5115                                                     FDecl->getIdentifier(),
5116                                                     OverloadTy,
5117                                                     /*TInfo=*/nullptr,
5118                                                     SC_Extern, false,
5119                                                     /*hasPrototype=*/true);
5120   SmallVector<ParmVarDecl*, 16> Params;
5121   FT = cast<FunctionProtoType>(OverloadTy);
5122   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5123     QualType ParamType = FT->getParamType(i);
5124     ParmVarDecl *Parm =
5125         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5126                                 SourceLocation(), nullptr, ParamType,
5127                                 /*TInfo=*/nullptr, SC_None, nullptr);
5128     Parm->setScopeInfo(0, i);
5129     Params.push_back(Parm);
5130   }
5131   OverloadDecl->setParams(Params);
5132   return OverloadDecl;
5133 }
5134 
5135 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5136                                        std::size_t NumArgs) {
5137   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5138                          /*PartialOverloading=*/false))
5139     return Callee->isVariadic();
5140   return Callee->getMinRequiredArguments() <= NumArgs;
5141 }
5142 
5143 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5144 /// This provides the location of the left/right parens and a list of comma
5145 /// locations.
5146 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5147                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5148                                Expr *ExecConfig, bool IsExecConfig) {
5149   // Since this might be a postfix expression, get rid of ParenListExprs.
5150   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5151   if (Result.isInvalid()) return ExprError();
5152   Fn = Result.get();
5153 
5154   if (checkArgsForPlaceholders(*this, ArgExprs))
5155     return ExprError();
5156 
5157   if (getLangOpts().CPlusPlus) {
5158     // If this is a pseudo-destructor expression, build the call immediately.
5159     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5160       if (!ArgExprs.empty()) {
5161         // Pseudo-destructor calls should not have any arguments.
5162         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5163             << FixItHint::CreateRemoval(
5164                    SourceRange(ArgExprs.front()->getLocStart(),
5165                                ArgExprs.back()->getLocEnd()));
5166       }
5167 
5168       return new (Context)
5169           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5170     }
5171     if (Fn->getType() == Context.PseudoObjectTy) {
5172       ExprResult result = CheckPlaceholderExpr(Fn);
5173       if (result.isInvalid()) return ExprError();
5174       Fn = result.get();
5175     }
5176 
5177     // Determine whether this is a dependent call inside a C++ template,
5178     // in which case we won't do any semantic analysis now.
5179     bool Dependent = false;
5180     if (Fn->isTypeDependent())
5181       Dependent = true;
5182     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5183       Dependent = true;
5184 
5185     if (Dependent) {
5186       if (ExecConfig) {
5187         return new (Context) CUDAKernelCallExpr(
5188             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5189             Context.DependentTy, VK_RValue, RParenLoc);
5190       } else {
5191         return new (Context) CallExpr(
5192             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5193       }
5194     }
5195 
5196     // Determine whether this is a call to an object (C++ [over.call.object]).
5197     if (Fn->getType()->isRecordType())
5198       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5199                                           RParenLoc);
5200 
5201     if (Fn->getType() == Context.UnknownAnyTy) {
5202       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5203       if (result.isInvalid()) return ExprError();
5204       Fn = result.get();
5205     }
5206 
5207     if (Fn->getType() == Context.BoundMemberTy) {
5208       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5209                                        RParenLoc);
5210     }
5211   }
5212 
5213   // Check for overloaded calls.  This can happen even in C due to extensions.
5214   if (Fn->getType() == Context.OverloadTy) {
5215     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5216 
5217     // We aren't supposed to apply this logic for if there'Scope an '&'
5218     // involved.
5219     if (!find.HasFormOfMemberPointer) {
5220       OverloadExpr *ovl = find.Expression;
5221       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5222         return BuildOverloadedCallExpr(
5223             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5224             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5225       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5226                                        RParenLoc);
5227     }
5228   }
5229 
5230   // If we're directly calling a function, get the appropriate declaration.
5231   if (Fn->getType() == Context.UnknownAnyTy) {
5232     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5233     if (result.isInvalid()) return ExprError();
5234     Fn = result.get();
5235   }
5236 
5237   Expr *NakedFn = Fn->IgnoreParens();
5238 
5239   bool CallingNDeclIndirectly = false;
5240   NamedDecl *NDecl = nullptr;
5241   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5242     if (UnOp->getOpcode() == UO_AddrOf) {
5243       CallingNDeclIndirectly = true;
5244       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5245     }
5246   }
5247 
5248   if (isa<DeclRefExpr>(NakedFn)) {
5249     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5250 
5251     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5252     if (FDecl && FDecl->getBuiltinID()) {
5253       // Rewrite the function decl for this builtin by replacing parameters
5254       // with no explicit address space with the address space of the arguments
5255       // in ArgExprs.
5256       if ((FDecl =
5257                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5258         NDecl = FDecl;
5259         Fn = DeclRefExpr::Create(
5260             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5261             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5262       }
5263     }
5264   } else if (isa<MemberExpr>(NakedFn))
5265     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5266 
5267   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5268     if (CallingNDeclIndirectly &&
5269         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5270                                            Fn->getLocStart()))
5271       return ExprError();
5272 
5273     // CheckEnableIf assumes that the we're passing in a sane number of args for
5274     // FD, but that doesn't always hold true here. This is because, in some
5275     // cases, we'll emit a diag about an ill-formed function call, but then
5276     // we'll continue on as if the function call wasn't ill-formed. So, if the
5277     // number of args looks incorrect, don't do enable_if checks; we should've
5278     // already emitted an error about the bad call.
5279     if (FD->hasAttr<EnableIfAttr>() &&
5280         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5281       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5282         Diag(Fn->getLocStart(),
5283              isa<CXXMethodDecl>(FD)
5284                  ? diag::err_ovl_no_viable_member_function_in_call
5285                  : diag::err_ovl_no_viable_function_in_call)
5286             << FD << FD->getSourceRange();
5287         Diag(FD->getLocation(),
5288              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5289             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5290       }
5291     }
5292   }
5293 
5294   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5295                                ExecConfig, IsExecConfig);
5296 }
5297 
5298 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5299 ///
5300 /// __builtin_astype( value, dst type )
5301 ///
5302 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5303                                  SourceLocation BuiltinLoc,
5304                                  SourceLocation RParenLoc) {
5305   ExprValueKind VK = VK_RValue;
5306   ExprObjectKind OK = OK_Ordinary;
5307   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5308   QualType SrcTy = E->getType();
5309   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5310     return ExprError(Diag(BuiltinLoc,
5311                           diag::err_invalid_astype_of_different_size)
5312                      << DstTy
5313                      << SrcTy
5314                      << E->getSourceRange());
5315   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5316 }
5317 
5318 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5319 /// provided arguments.
5320 ///
5321 /// __builtin_convertvector( value, dst type )
5322 ///
5323 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5324                                         SourceLocation BuiltinLoc,
5325                                         SourceLocation RParenLoc) {
5326   TypeSourceInfo *TInfo;
5327   GetTypeFromParser(ParsedDestTy, &TInfo);
5328   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5329 }
5330 
5331 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5332 /// i.e. an expression not of \p OverloadTy.  The expression should
5333 /// unary-convert to an expression of function-pointer or
5334 /// block-pointer type.
5335 ///
5336 /// \param NDecl the declaration being called, if available
5337 ExprResult
5338 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5339                             SourceLocation LParenLoc,
5340                             ArrayRef<Expr *> Args,
5341                             SourceLocation RParenLoc,
5342                             Expr *Config, bool IsExecConfig) {
5343   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5344   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5345 
5346   // Functions with 'interrupt' attribute cannot be called directly.
5347   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5348     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5349     return ExprError();
5350   }
5351 
5352   // Promote the function operand.
5353   // We special-case function promotion here because we only allow promoting
5354   // builtin functions to function pointers in the callee of a call.
5355   ExprResult Result;
5356   if (BuiltinID &&
5357       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5358     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5359                                CK_BuiltinFnToFnPtr).get();
5360   } else {
5361     Result = CallExprUnaryConversions(Fn);
5362   }
5363   if (Result.isInvalid())
5364     return ExprError();
5365   Fn = Result.get();
5366 
5367   // Make the call expr early, before semantic checks.  This guarantees cleanup
5368   // of arguments and function on error.
5369   CallExpr *TheCall;
5370   if (Config)
5371     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5372                                                cast<CallExpr>(Config), Args,
5373                                                Context.BoolTy, VK_RValue,
5374                                                RParenLoc);
5375   else
5376     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5377                                      VK_RValue, RParenLoc);
5378 
5379   if (!getLangOpts().CPlusPlus) {
5380     // C cannot always handle TypoExpr nodes in builtin calls and direct
5381     // function calls as their argument checking don't necessarily handle
5382     // dependent types properly, so make sure any TypoExprs have been
5383     // dealt with.
5384     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5385     if (!Result.isUsable()) return ExprError();
5386     TheCall = dyn_cast<CallExpr>(Result.get());
5387     if (!TheCall) return Result;
5388     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5389   }
5390 
5391   // Bail out early if calling a builtin with custom typechecking.
5392   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5393     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5394 
5395  retry:
5396   const FunctionType *FuncT;
5397   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5398     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5399     // have type pointer to function".
5400     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5401     if (!FuncT)
5402       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5403                          << Fn->getType() << Fn->getSourceRange());
5404   } else if (const BlockPointerType *BPT =
5405                Fn->getType()->getAs<BlockPointerType>()) {
5406     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5407   } else {
5408     // Handle calls to expressions of unknown-any type.
5409     if (Fn->getType() == Context.UnknownAnyTy) {
5410       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5411       if (rewrite.isInvalid()) return ExprError();
5412       Fn = rewrite.get();
5413       TheCall->setCallee(Fn);
5414       goto retry;
5415     }
5416 
5417     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5418       << Fn->getType() << Fn->getSourceRange());
5419   }
5420 
5421   if (getLangOpts().CUDA) {
5422     if (Config) {
5423       // CUDA: Kernel calls must be to global functions
5424       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5425         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5426             << FDecl->getName() << Fn->getSourceRange());
5427 
5428       // CUDA: Kernel function must have 'void' return type
5429       if (!FuncT->getReturnType()->isVoidType())
5430         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5431             << Fn->getType() << Fn->getSourceRange());
5432     } else {
5433       // CUDA: Calls to global functions must be configured
5434       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5435         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5436             << FDecl->getName() << Fn->getSourceRange());
5437     }
5438   }
5439 
5440   // Check for a valid return type
5441   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5442                           FDecl))
5443     return ExprError();
5444 
5445   // We know the result type of the call, set it.
5446   TheCall->setType(FuncT->getCallResultType(Context));
5447   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5448 
5449   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5450   if (Proto) {
5451     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5452                                 IsExecConfig))
5453       return ExprError();
5454   } else {
5455     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5456 
5457     if (FDecl) {
5458       // Check if we have too few/too many template arguments, based
5459       // on our knowledge of the function definition.
5460       const FunctionDecl *Def = nullptr;
5461       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5462         Proto = Def->getType()->getAs<FunctionProtoType>();
5463        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5464           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5465           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5466       }
5467 
5468       // If the function we're calling isn't a function prototype, but we have
5469       // a function prototype from a prior declaratiom, use that prototype.
5470       if (!FDecl->hasPrototype())
5471         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5472     }
5473 
5474     // Promote the arguments (C99 6.5.2.2p6).
5475     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5476       Expr *Arg = Args[i];
5477 
5478       if (Proto && i < Proto->getNumParams()) {
5479         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5480             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5481         ExprResult ArgE =
5482             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5483         if (ArgE.isInvalid())
5484           return true;
5485 
5486         Arg = ArgE.getAs<Expr>();
5487 
5488       } else {
5489         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5490 
5491         if (ArgE.isInvalid())
5492           return true;
5493 
5494         Arg = ArgE.getAs<Expr>();
5495       }
5496 
5497       if (RequireCompleteType(Arg->getLocStart(),
5498                               Arg->getType(),
5499                               diag::err_call_incomplete_argument, Arg))
5500         return ExprError();
5501 
5502       TheCall->setArg(i, Arg);
5503     }
5504   }
5505 
5506   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5507     if (!Method->isStatic())
5508       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5509         << Fn->getSourceRange());
5510 
5511   // Check for sentinels
5512   if (NDecl)
5513     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5514 
5515   // Do special checking on direct calls to functions.
5516   if (FDecl) {
5517     if (CheckFunctionCall(FDecl, TheCall, Proto))
5518       return ExprError();
5519 
5520     if (BuiltinID)
5521       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5522   } else if (NDecl) {
5523     if (CheckPointerCall(NDecl, TheCall, Proto))
5524       return ExprError();
5525   } else {
5526     if (CheckOtherCall(TheCall, Proto))
5527       return ExprError();
5528   }
5529 
5530   return MaybeBindToTemporary(TheCall);
5531 }
5532 
5533 ExprResult
5534 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5535                            SourceLocation RParenLoc, Expr *InitExpr) {
5536   assert(Ty && "ActOnCompoundLiteral(): missing type");
5537   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5538 
5539   TypeSourceInfo *TInfo;
5540   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5541   if (!TInfo)
5542     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5543 
5544   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5545 }
5546 
5547 ExprResult
5548 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5549                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5550   QualType literalType = TInfo->getType();
5551 
5552   if (literalType->isArrayType()) {
5553     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5554           diag::err_illegal_decl_array_incomplete_type,
5555           SourceRange(LParenLoc,
5556                       LiteralExpr->getSourceRange().getEnd())))
5557       return ExprError();
5558     if (literalType->isVariableArrayType())
5559       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5560         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5561   } else if (!literalType->isDependentType() &&
5562              RequireCompleteType(LParenLoc, literalType,
5563                diag::err_typecheck_decl_incomplete_type,
5564                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5565     return ExprError();
5566 
5567   InitializedEntity Entity
5568     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5569   InitializationKind Kind
5570     = InitializationKind::CreateCStyleCast(LParenLoc,
5571                                            SourceRange(LParenLoc, RParenLoc),
5572                                            /*InitList=*/true);
5573   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5574   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5575                                       &literalType);
5576   if (Result.isInvalid())
5577     return ExprError();
5578   LiteralExpr = Result.get();
5579 
5580   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5581   if (isFileScope &&
5582       !LiteralExpr->isTypeDependent() &&
5583       !LiteralExpr->isValueDependent() &&
5584       !literalType->isDependentType()) { // 6.5.2.5p3
5585     if (CheckForConstantInitializer(LiteralExpr, literalType))
5586       return ExprError();
5587   }
5588 
5589   // In C, compound literals are l-values for some reason.
5590   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5591 
5592   return MaybeBindToTemporary(
5593            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5594                                              VK, LiteralExpr, isFileScope));
5595 }
5596 
5597 ExprResult
5598 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5599                     SourceLocation RBraceLoc) {
5600   // Immediately handle non-overload placeholders.  Overloads can be
5601   // resolved contextually, but everything else here can't.
5602   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5603     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5604       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5605 
5606       // Ignore failures; dropping the entire initializer list because
5607       // of one failure would be terrible for indexing/etc.
5608       if (result.isInvalid()) continue;
5609 
5610       InitArgList[I] = result.get();
5611     }
5612   }
5613 
5614   // Semantic analysis for initializers is done by ActOnDeclarator() and
5615   // CheckInitializer() - it requires knowledge of the object being intialized.
5616 
5617   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5618                                                RBraceLoc);
5619   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5620   return E;
5621 }
5622 
5623 /// Do an explicit extend of the given block pointer if we're in ARC.
5624 void Sema::maybeExtendBlockObject(ExprResult &E) {
5625   assert(E.get()->getType()->isBlockPointerType());
5626   assert(E.get()->isRValue());
5627 
5628   // Only do this in an r-value context.
5629   if (!getLangOpts().ObjCAutoRefCount) return;
5630 
5631   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5632                                CK_ARCExtendBlockObject, E.get(),
5633                                /*base path*/ nullptr, VK_RValue);
5634   Cleanup.setExprNeedsCleanups(true);
5635 }
5636 
5637 /// Prepare a conversion of the given expression to an ObjC object
5638 /// pointer type.
5639 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5640   QualType type = E.get()->getType();
5641   if (type->isObjCObjectPointerType()) {
5642     return CK_BitCast;
5643   } else if (type->isBlockPointerType()) {
5644     maybeExtendBlockObject(E);
5645     return CK_BlockPointerToObjCPointerCast;
5646   } else {
5647     assert(type->isPointerType());
5648     return CK_CPointerToObjCPointerCast;
5649   }
5650 }
5651 
5652 /// Prepares for a scalar cast, performing all the necessary stages
5653 /// except the final cast and returning the kind required.
5654 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5655   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5656   // Also, callers should have filtered out the invalid cases with
5657   // pointers.  Everything else should be possible.
5658 
5659   QualType SrcTy = Src.get()->getType();
5660   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5661     return CK_NoOp;
5662 
5663   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5664   case Type::STK_MemberPointer:
5665     llvm_unreachable("member pointer type in C");
5666 
5667   case Type::STK_CPointer:
5668   case Type::STK_BlockPointer:
5669   case Type::STK_ObjCObjectPointer:
5670     switch (DestTy->getScalarTypeKind()) {
5671     case Type::STK_CPointer: {
5672       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5673       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5674       if (SrcAS != DestAS)
5675         return CK_AddressSpaceConversion;
5676       return CK_BitCast;
5677     }
5678     case Type::STK_BlockPointer:
5679       return (SrcKind == Type::STK_BlockPointer
5680                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5681     case Type::STK_ObjCObjectPointer:
5682       if (SrcKind == Type::STK_ObjCObjectPointer)
5683         return CK_BitCast;
5684       if (SrcKind == Type::STK_CPointer)
5685         return CK_CPointerToObjCPointerCast;
5686       maybeExtendBlockObject(Src);
5687       return CK_BlockPointerToObjCPointerCast;
5688     case Type::STK_Bool:
5689       return CK_PointerToBoolean;
5690     case Type::STK_Integral:
5691       return CK_PointerToIntegral;
5692     case Type::STK_Floating:
5693     case Type::STK_FloatingComplex:
5694     case Type::STK_IntegralComplex:
5695     case Type::STK_MemberPointer:
5696       llvm_unreachable("illegal cast from pointer");
5697     }
5698     llvm_unreachable("Should have returned before this");
5699 
5700   case Type::STK_Bool: // casting from bool is like casting from an integer
5701   case Type::STK_Integral:
5702     switch (DestTy->getScalarTypeKind()) {
5703     case Type::STK_CPointer:
5704     case Type::STK_ObjCObjectPointer:
5705     case Type::STK_BlockPointer:
5706       if (Src.get()->isNullPointerConstant(Context,
5707                                            Expr::NPC_ValueDependentIsNull))
5708         return CK_NullToPointer;
5709       return CK_IntegralToPointer;
5710     case Type::STK_Bool:
5711       return CK_IntegralToBoolean;
5712     case Type::STK_Integral:
5713       return CK_IntegralCast;
5714     case Type::STK_Floating:
5715       return CK_IntegralToFloating;
5716     case Type::STK_IntegralComplex:
5717       Src = ImpCastExprToType(Src.get(),
5718                       DestTy->castAs<ComplexType>()->getElementType(),
5719                       CK_IntegralCast);
5720       return CK_IntegralRealToComplex;
5721     case Type::STK_FloatingComplex:
5722       Src = ImpCastExprToType(Src.get(),
5723                       DestTy->castAs<ComplexType>()->getElementType(),
5724                       CK_IntegralToFloating);
5725       return CK_FloatingRealToComplex;
5726     case Type::STK_MemberPointer:
5727       llvm_unreachable("member pointer type in C");
5728     }
5729     llvm_unreachable("Should have returned before this");
5730 
5731   case Type::STK_Floating:
5732     switch (DestTy->getScalarTypeKind()) {
5733     case Type::STK_Floating:
5734       return CK_FloatingCast;
5735     case Type::STK_Bool:
5736       return CK_FloatingToBoolean;
5737     case Type::STK_Integral:
5738       return CK_FloatingToIntegral;
5739     case Type::STK_FloatingComplex:
5740       Src = ImpCastExprToType(Src.get(),
5741                               DestTy->castAs<ComplexType>()->getElementType(),
5742                               CK_FloatingCast);
5743       return CK_FloatingRealToComplex;
5744     case Type::STK_IntegralComplex:
5745       Src = ImpCastExprToType(Src.get(),
5746                               DestTy->castAs<ComplexType>()->getElementType(),
5747                               CK_FloatingToIntegral);
5748       return CK_IntegralRealToComplex;
5749     case Type::STK_CPointer:
5750     case Type::STK_ObjCObjectPointer:
5751     case Type::STK_BlockPointer:
5752       llvm_unreachable("valid float->pointer cast?");
5753     case Type::STK_MemberPointer:
5754       llvm_unreachable("member pointer type in C");
5755     }
5756     llvm_unreachable("Should have returned before this");
5757 
5758   case Type::STK_FloatingComplex:
5759     switch (DestTy->getScalarTypeKind()) {
5760     case Type::STK_FloatingComplex:
5761       return CK_FloatingComplexCast;
5762     case Type::STK_IntegralComplex:
5763       return CK_FloatingComplexToIntegralComplex;
5764     case Type::STK_Floating: {
5765       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5766       if (Context.hasSameType(ET, DestTy))
5767         return CK_FloatingComplexToReal;
5768       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5769       return CK_FloatingCast;
5770     }
5771     case Type::STK_Bool:
5772       return CK_FloatingComplexToBoolean;
5773     case Type::STK_Integral:
5774       Src = ImpCastExprToType(Src.get(),
5775                               SrcTy->castAs<ComplexType>()->getElementType(),
5776                               CK_FloatingComplexToReal);
5777       return CK_FloatingToIntegral;
5778     case Type::STK_CPointer:
5779     case Type::STK_ObjCObjectPointer:
5780     case Type::STK_BlockPointer:
5781       llvm_unreachable("valid complex float->pointer cast?");
5782     case Type::STK_MemberPointer:
5783       llvm_unreachable("member pointer type in C");
5784     }
5785     llvm_unreachable("Should have returned before this");
5786 
5787   case Type::STK_IntegralComplex:
5788     switch (DestTy->getScalarTypeKind()) {
5789     case Type::STK_FloatingComplex:
5790       return CK_IntegralComplexToFloatingComplex;
5791     case Type::STK_IntegralComplex:
5792       return CK_IntegralComplexCast;
5793     case Type::STK_Integral: {
5794       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5795       if (Context.hasSameType(ET, DestTy))
5796         return CK_IntegralComplexToReal;
5797       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5798       return CK_IntegralCast;
5799     }
5800     case Type::STK_Bool:
5801       return CK_IntegralComplexToBoolean;
5802     case Type::STK_Floating:
5803       Src = ImpCastExprToType(Src.get(),
5804                               SrcTy->castAs<ComplexType>()->getElementType(),
5805                               CK_IntegralComplexToReal);
5806       return CK_IntegralToFloating;
5807     case Type::STK_CPointer:
5808     case Type::STK_ObjCObjectPointer:
5809     case Type::STK_BlockPointer:
5810       llvm_unreachable("valid complex int->pointer cast?");
5811     case Type::STK_MemberPointer:
5812       llvm_unreachable("member pointer type in C");
5813     }
5814     llvm_unreachable("Should have returned before this");
5815   }
5816 
5817   llvm_unreachable("Unhandled scalar cast");
5818 }
5819 
5820 static bool breakDownVectorType(QualType type, uint64_t &len,
5821                                 QualType &eltType) {
5822   // Vectors are simple.
5823   if (const VectorType *vecType = type->getAs<VectorType>()) {
5824     len = vecType->getNumElements();
5825     eltType = vecType->getElementType();
5826     assert(eltType->isScalarType());
5827     return true;
5828   }
5829 
5830   // We allow lax conversion to and from non-vector types, but only if
5831   // they're real types (i.e. non-complex, non-pointer scalar types).
5832   if (!type->isRealType()) return false;
5833 
5834   len = 1;
5835   eltType = type;
5836   return true;
5837 }
5838 
5839 /// Are the two types lax-compatible vector types?  That is, given
5840 /// that one of them is a vector, do they have equal storage sizes,
5841 /// where the storage size is the number of elements times the element
5842 /// size?
5843 ///
5844 /// This will also return false if either of the types is neither a
5845 /// vector nor a real type.
5846 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5847   assert(destTy->isVectorType() || srcTy->isVectorType());
5848 
5849   // Disallow lax conversions between scalars and ExtVectors (these
5850   // conversions are allowed for other vector types because common headers
5851   // depend on them).  Most scalar OP ExtVector cases are handled by the
5852   // splat path anyway, which does what we want (convert, not bitcast).
5853   // What this rules out for ExtVectors is crazy things like char4*float.
5854   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5855   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5856 
5857   uint64_t srcLen, destLen;
5858   QualType srcEltTy, destEltTy;
5859   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5860   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5861 
5862   // ASTContext::getTypeSize will return the size rounded up to a
5863   // power of 2, so instead of using that, we need to use the raw
5864   // element size multiplied by the element count.
5865   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5866   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5867 
5868   return (srcLen * srcEltSize == destLen * destEltSize);
5869 }
5870 
5871 /// Is this a legal conversion between two types, one of which is
5872 /// known to be a vector type?
5873 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5874   assert(destTy->isVectorType() || srcTy->isVectorType());
5875 
5876   if (!Context.getLangOpts().LaxVectorConversions)
5877     return false;
5878   return areLaxCompatibleVectorTypes(srcTy, destTy);
5879 }
5880 
5881 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5882                            CastKind &Kind) {
5883   assert(VectorTy->isVectorType() && "Not a vector type!");
5884 
5885   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5886     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5887       return Diag(R.getBegin(),
5888                   Ty->isVectorType() ?
5889                   diag::err_invalid_conversion_between_vectors :
5890                   diag::err_invalid_conversion_between_vector_and_integer)
5891         << VectorTy << Ty << R;
5892   } else
5893     return Diag(R.getBegin(),
5894                 diag::err_invalid_conversion_between_vector_and_scalar)
5895       << VectorTy << Ty << R;
5896 
5897   Kind = CK_BitCast;
5898   return false;
5899 }
5900 
5901 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5902   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5903 
5904   if (DestElemTy == SplattedExpr->getType())
5905     return SplattedExpr;
5906 
5907   assert(DestElemTy->isFloatingType() ||
5908          DestElemTy->isIntegralOrEnumerationType());
5909 
5910   CastKind CK;
5911   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5912     // OpenCL requires that we convert `true` boolean expressions to -1, but
5913     // only when splatting vectors.
5914     if (DestElemTy->isFloatingType()) {
5915       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5916       // in two steps: boolean to signed integral, then to floating.
5917       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5918                                                  CK_BooleanToSignedIntegral);
5919       SplattedExpr = CastExprRes.get();
5920       CK = CK_IntegralToFloating;
5921     } else {
5922       CK = CK_BooleanToSignedIntegral;
5923     }
5924   } else {
5925     ExprResult CastExprRes = SplattedExpr;
5926     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5927     if (CastExprRes.isInvalid())
5928       return ExprError();
5929     SplattedExpr = CastExprRes.get();
5930   }
5931   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5932 }
5933 
5934 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5935                                     Expr *CastExpr, CastKind &Kind) {
5936   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5937 
5938   QualType SrcTy = CastExpr->getType();
5939 
5940   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5941   // an ExtVectorType.
5942   // In OpenCL, casts between vectors of different types are not allowed.
5943   // (See OpenCL 6.2).
5944   if (SrcTy->isVectorType()) {
5945     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5946         || (getLangOpts().OpenCL &&
5947             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5948       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5949         << DestTy << SrcTy << R;
5950       return ExprError();
5951     }
5952     Kind = CK_BitCast;
5953     return CastExpr;
5954   }
5955 
5956   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5957   // conversion will take place first from scalar to elt type, and then
5958   // splat from elt type to vector.
5959   if (SrcTy->isPointerType())
5960     return Diag(R.getBegin(),
5961                 diag::err_invalid_conversion_between_vector_and_scalar)
5962       << DestTy << SrcTy << R;
5963 
5964   Kind = CK_VectorSplat;
5965   return prepareVectorSplat(DestTy, CastExpr);
5966 }
5967 
5968 ExprResult
5969 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5970                     Declarator &D, ParsedType &Ty,
5971                     SourceLocation RParenLoc, Expr *CastExpr) {
5972   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5973          "ActOnCastExpr(): missing type or expr");
5974 
5975   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5976   if (D.isInvalidType())
5977     return ExprError();
5978 
5979   if (getLangOpts().CPlusPlus) {
5980     // Check that there are no default arguments (C++ only).
5981     CheckExtraCXXDefaultArguments(D);
5982   } else {
5983     // Make sure any TypoExprs have been dealt with.
5984     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5985     if (!Res.isUsable())
5986       return ExprError();
5987     CastExpr = Res.get();
5988   }
5989 
5990   checkUnusedDeclAttributes(D);
5991 
5992   QualType castType = castTInfo->getType();
5993   Ty = CreateParsedType(castType, castTInfo);
5994 
5995   bool isVectorLiteral = false;
5996 
5997   // Check for an altivec or OpenCL literal,
5998   // i.e. all the elements are integer constants.
5999   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6000   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6001   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6002        && castType->isVectorType() && (PE || PLE)) {
6003     if (PLE && PLE->getNumExprs() == 0) {
6004       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6005       return ExprError();
6006     }
6007     if (PE || PLE->getNumExprs() == 1) {
6008       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6009       if (!E->getType()->isVectorType())
6010         isVectorLiteral = true;
6011     }
6012     else
6013       isVectorLiteral = true;
6014   }
6015 
6016   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6017   // then handle it as such.
6018   if (isVectorLiteral)
6019     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6020 
6021   // If the Expr being casted is a ParenListExpr, handle it specially.
6022   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6023   // sequence of BinOp comma operators.
6024   if (isa<ParenListExpr>(CastExpr)) {
6025     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6026     if (Result.isInvalid()) return ExprError();
6027     CastExpr = Result.get();
6028   }
6029 
6030   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6031       !getSourceManager().isInSystemMacro(LParenLoc))
6032     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6033 
6034   CheckTollFreeBridgeCast(castType, CastExpr);
6035 
6036   CheckObjCBridgeRelatedCast(castType, CastExpr);
6037 
6038   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6039 
6040   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6041 }
6042 
6043 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6044                                     SourceLocation RParenLoc, Expr *E,
6045                                     TypeSourceInfo *TInfo) {
6046   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6047          "Expected paren or paren list expression");
6048 
6049   Expr **exprs;
6050   unsigned numExprs;
6051   Expr *subExpr;
6052   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6053   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6054     LiteralLParenLoc = PE->getLParenLoc();
6055     LiteralRParenLoc = PE->getRParenLoc();
6056     exprs = PE->getExprs();
6057     numExprs = PE->getNumExprs();
6058   } else { // isa<ParenExpr> by assertion at function entrance
6059     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6060     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6061     subExpr = cast<ParenExpr>(E)->getSubExpr();
6062     exprs = &subExpr;
6063     numExprs = 1;
6064   }
6065 
6066   QualType Ty = TInfo->getType();
6067   assert(Ty->isVectorType() && "Expected vector type");
6068 
6069   SmallVector<Expr *, 8> initExprs;
6070   const VectorType *VTy = Ty->getAs<VectorType>();
6071   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6072 
6073   // '(...)' form of vector initialization in AltiVec: the number of
6074   // initializers must be one or must match the size of the vector.
6075   // If a single value is specified in the initializer then it will be
6076   // replicated to all the components of the vector
6077   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6078     // The number of initializers must be one or must match the size of the
6079     // vector. If a single value is specified in the initializer then it will
6080     // be replicated to all the components of the vector
6081     if (numExprs == 1) {
6082       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6083       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6084       if (Literal.isInvalid())
6085         return ExprError();
6086       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6087                                   PrepareScalarCast(Literal, ElemTy));
6088       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6089     }
6090     else if (numExprs < numElems) {
6091       Diag(E->getExprLoc(),
6092            diag::err_incorrect_number_of_vector_initializers);
6093       return ExprError();
6094     }
6095     else
6096       initExprs.append(exprs, exprs + numExprs);
6097   }
6098   else {
6099     // For OpenCL, when the number of initializers is a single value,
6100     // it will be replicated to all components of the vector.
6101     if (getLangOpts().OpenCL &&
6102         VTy->getVectorKind() == VectorType::GenericVector &&
6103         numExprs == 1) {
6104         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6105         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6106         if (Literal.isInvalid())
6107           return ExprError();
6108         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6109                                     PrepareScalarCast(Literal, ElemTy));
6110         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6111     }
6112 
6113     initExprs.append(exprs, exprs + numExprs);
6114   }
6115   // FIXME: This means that pretty-printing the final AST will produce curly
6116   // braces instead of the original commas.
6117   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6118                                                    initExprs, LiteralRParenLoc);
6119   initE->setType(Ty);
6120   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6121 }
6122 
6123 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6124 /// the ParenListExpr into a sequence of comma binary operators.
6125 ExprResult
6126 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6127   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6128   if (!E)
6129     return OrigExpr;
6130 
6131   ExprResult Result(E->getExpr(0));
6132 
6133   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6134     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6135                         E->getExpr(i));
6136 
6137   if (Result.isInvalid()) return ExprError();
6138 
6139   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6140 }
6141 
6142 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6143                                     SourceLocation R,
6144                                     MultiExprArg Val) {
6145   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6146   return expr;
6147 }
6148 
6149 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6150 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6151 /// emitted.
6152 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6153                                       SourceLocation QuestionLoc) {
6154   Expr *NullExpr = LHSExpr;
6155   Expr *NonPointerExpr = RHSExpr;
6156   Expr::NullPointerConstantKind NullKind =
6157       NullExpr->isNullPointerConstant(Context,
6158                                       Expr::NPC_ValueDependentIsNotNull);
6159 
6160   if (NullKind == Expr::NPCK_NotNull) {
6161     NullExpr = RHSExpr;
6162     NonPointerExpr = LHSExpr;
6163     NullKind =
6164         NullExpr->isNullPointerConstant(Context,
6165                                         Expr::NPC_ValueDependentIsNotNull);
6166   }
6167 
6168   if (NullKind == Expr::NPCK_NotNull)
6169     return false;
6170 
6171   if (NullKind == Expr::NPCK_ZeroExpression)
6172     return false;
6173 
6174   if (NullKind == Expr::NPCK_ZeroLiteral) {
6175     // In this case, check to make sure that we got here from a "NULL"
6176     // string in the source code.
6177     NullExpr = NullExpr->IgnoreParenImpCasts();
6178     SourceLocation loc = NullExpr->getExprLoc();
6179     if (!findMacroSpelling(loc, "NULL"))
6180       return false;
6181   }
6182 
6183   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6184   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6185       << NonPointerExpr->getType() << DiagType
6186       << NonPointerExpr->getSourceRange();
6187   return true;
6188 }
6189 
6190 /// \brief Return false if the condition expression is valid, true otherwise.
6191 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6192   QualType CondTy = Cond->getType();
6193 
6194   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6195   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6196     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6197       << CondTy << Cond->getSourceRange();
6198     return true;
6199   }
6200 
6201   // C99 6.5.15p2
6202   if (CondTy->isScalarType()) return false;
6203 
6204   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6205     << CondTy << Cond->getSourceRange();
6206   return true;
6207 }
6208 
6209 /// \brief Handle when one or both operands are void type.
6210 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6211                                          ExprResult &RHS) {
6212     Expr *LHSExpr = LHS.get();
6213     Expr *RHSExpr = RHS.get();
6214 
6215     if (!LHSExpr->getType()->isVoidType())
6216       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6217         << RHSExpr->getSourceRange();
6218     if (!RHSExpr->getType()->isVoidType())
6219       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6220         << LHSExpr->getSourceRange();
6221     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6222     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6223     return S.Context.VoidTy;
6224 }
6225 
6226 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6227 /// true otherwise.
6228 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6229                                         QualType PointerTy) {
6230   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6231       !NullExpr.get()->isNullPointerConstant(S.Context,
6232                                             Expr::NPC_ValueDependentIsNull))
6233     return true;
6234 
6235   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6236   return false;
6237 }
6238 
6239 /// \brief Checks compatibility between two pointers and return the resulting
6240 /// type.
6241 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6242                                                      ExprResult &RHS,
6243                                                      SourceLocation Loc) {
6244   QualType LHSTy = LHS.get()->getType();
6245   QualType RHSTy = RHS.get()->getType();
6246 
6247   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6248     // Two identical pointers types are always compatible.
6249     return LHSTy;
6250   }
6251 
6252   QualType lhptee, rhptee;
6253 
6254   // Get the pointee types.
6255   bool IsBlockPointer = false;
6256   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6257     lhptee = LHSBTy->getPointeeType();
6258     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6259     IsBlockPointer = true;
6260   } else {
6261     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6262     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6263   }
6264 
6265   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6266   // differently qualified versions of compatible types, the result type is
6267   // a pointer to an appropriately qualified version of the composite
6268   // type.
6269 
6270   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6271   // clause doesn't make sense for our extensions. E.g. address space 2 should
6272   // be incompatible with address space 3: they may live on different devices or
6273   // anything.
6274   Qualifiers lhQual = lhptee.getQualifiers();
6275   Qualifiers rhQual = rhptee.getQualifiers();
6276 
6277   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6278   lhQual.removeCVRQualifiers();
6279   rhQual.removeCVRQualifiers();
6280 
6281   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6282   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6283 
6284   // For OpenCL:
6285   // 1. If LHS and RHS types match exactly and:
6286   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6287   //  (b) AS overlap => generate addrspacecast
6288   //  (c) AS don't overlap => give an error
6289   // 2. if LHS and RHS types don't match:
6290   //  (a) AS match => use standard C rules, generate bitcast
6291   //  (b) AS overlap => generate addrspacecast instead of bitcast
6292   //  (c) AS don't overlap => give an error
6293 
6294   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6295   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6296 
6297   // OpenCL cases 1c, 2a, 2b, and 2c.
6298   if (CompositeTy.isNull()) {
6299     // In this situation, we assume void* type. No especially good
6300     // reason, but this is what gcc does, and we do have to pick
6301     // to get a consistent AST.
6302     QualType incompatTy;
6303     if (S.getLangOpts().OpenCL) {
6304       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6305       // spaces is disallowed.
6306       unsigned ResultAddrSpace;
6307       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6308         // Cases 2a and 2b.
6309         ResultAddrSpace = lhQual.getAddressSpace();
6310       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6311         // Cases 2a and 2b.
6312         ResultAddrSpace = rhQual.getAddressSpace();
6313       } else {
6314         // Cases 1c and 2c.
6315         S.Diag(Loc,
6316                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6317             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6318             << RHS.get()->getSourceRange();
6319         return QualType();
6320       }
6321 
6322       // Continue handling cases 2a and 2b.
6323       incompatTy = S.Context.getPointerType(
6324           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6325       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6326                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6327                                     ? CK_AddressSpaceConversion /* 2b */
6328                                     : CK_BitCast /* 2a */);
6329       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6330                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6331                                     ? CK_AddressSpaceConversion /* 2b */
6332                                     : CK_BitCast /* 2a */);
6333     } else {
6334       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6335           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6336           << RHS.get()->getSourceRange();
6337       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6338       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6339       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6340     }
6341     return incompatTy;
6342   }
6343 
6344   // The pointer types are compatible.
6345   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6346   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6347   if (IsBlockPointer)
6348     ResultTy = S.Context.getBlockPointerType(ResultTy);
6349   else {
6350     // Cases 1a and 1b for OpenCL.
6351     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6352     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6353                       ? CK_BitCast /* 1a */
6354                       : CK_AddressSpaceConversion /* 1b */;
6355     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6356                       ? CK_BitCast /* 1a */
6357                       : CK_AddressSpaceConversion /* 1b */;
6358     ResultTy = S.Context.getPointerType(ResultTy);
6359   }
6360 
6361   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6362   // if the target type does not change.
6363   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6364   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6365   return ResultTy;
6366 }
6367 
6368 /// \brief Return the resulting type when the operands are both block pointers.
6369 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6370                                                           ExprResult &LHS,
6371                                                           ExprResult &RHS,
6372                                                           SourceLocation Loc) {
6373   QualType LHSTy = LHS.get()->getType();
6374   QualType RHSTy = RHS.get()->getType();
6375 
6376   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6377     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6378       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6379       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6380       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6381       return destType;
6382     }
6383     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6384       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6385       << RHS.get()->getSourceRange();
6386     return QualType();
6387   }
6388 
6389   // We have 2 block pointer types.
6390   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6391 }
6392 
6393 /// \brief Return the resulting type when the operands are both pointers.
6394 static QualType
6395 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6396                                             ExprResult &RHS,
6397                                             SourceLocation Loc) {
6398   // get the pointer types
6399   QualType LHSTy = LHS.get()->getType();
6400   QualType RHSTy = RHS.get()->getType();
6401 
6402   // get the "pointed to" types
6403   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6404   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6405 
6406   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6407   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6408     // Figure out necessary qualifiers (C99 6.5.15p6)
6409     QualType destPointee
6410       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6411     QualType destType = S.Context.getPointerType(destPointee);
6412     // Add qualifiers if necessary.
6413     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6414     // Promote to void*.
6415     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6416     return destType;
6417   }
6418   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6419     QualType destPointee
6420       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6421     QualType destType = S.Context.getPointerType(destPointee);
6422     // Add qualifiers if necessary.
6423     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6424     // Promote to void*.
6425     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6426     return destType;
6427   }
6428 
6429   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6430 }
6431 
6432 /// \brief Return false if the first expression is not an integer and the second
6433 /// expression is not a pointer, true otherwise.
6434 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6435                                         Expr* PointerExpr, SourceLocation Loc,
6436                                         bool IsIntFirstExpr) {
6437   if (!PointerExpr->getType()->isPointerType() ||
6438       !Int.get()->getType()->isIntegerType())
6439     return false;
6440 
6441   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6442   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6443 
6444   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6445     << Expr1->getType() << Expr2->getType()
6446     << Expr1->getSourceRange() << Expr2->getSourceRange();
6447   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6448                             CK_IntegralToPointer);
6449   return true;
6450 }
6451 
6452 /// \brief Simple conversion between integer and floating point types.
6453 ///
6454 /// Used when handling the OpenCL conditional operator where the
6455 /// condition is a vector while the other operands are scalar.
6456 ///
6457 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6458 /// types are either integer or floating type. Between the two
6459 /// operands, the type with the higher rank is defined as the "result
6460 /// type". The other operand needs to be promoted to the same type. No
6461 /// other type promotion is allowed. We cannot use
6462 /// UsualArithmeticConversions() for this purpose, since it always
6463 /// promotes promotable types.
6464 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6465                                             ExprResult &RHS,
6466                                             SourceLocation QuestionLoc) {
6467   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6468   if (LHS.isInvalid())
6469     return QualType();
6470   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6471   if (RHS.isInvalid())
6472     return QualType();
6473 
6474   // For conversion purposes, we ignore any qualifiers.
6475   // For example, "const float" and "float" are equivalent.
6476   QualType LHSType =
6477     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6478   QualType RHSType =
6479     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6480 
6481   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6482     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6483       << LHSType << LHS.get()->getSourceRange();
6484     return QualType();
6485   }
6486 
6487   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6488     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6489       << RHSType << RHS.get()->getSourceRange();
6490     return QualType();
6491   }
6492 
6493   // If both types are identical, no conversion is needed.
6494   if (LHSType == RHSType)
6495     return LHSType;
6496 
6497   // Now handle "real" floating types (i.e. float, double, long double).
6498   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6499     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6500                                  /*IsCompAssign = */ false);
6501 
6502   // Finally, we have two differing integer types.
6503   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6504   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6505 }
6506 
6507 /// \brief Convert scalar operands to a vector that matches the
6508 ///        condition in length.
6509 ///
6510 /// Used when handling the OpenCL conditional operator where the
6511 /// condition is a vector while the other operands are scalar.
6512 ///
6513 /// We first compute the "result type" for the scalar operands
6514 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6515 /// into a vector of that type where the length matches the condition
6516 /// vector type. s6.11.6 requires that the element types of the result
6517 /// and the condition must have the same number of bits.
6518 static QualType
6519 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6520                               QualType CondTy, SourceLocation QuestionLoc) {
6521   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6522   if (ResTy.isNull()) return QualType();
6523 
6524   const VectorType *CV = CondTy->getAs<VectorType>();
6525   assert(CV);
6526 
6527   // Determine the vector result type
6528   unsigned NumElements = CV->getNumElements();
6529   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6530 
6531   // Ensure that all types have the same number of bits
6532   if (S.Context.getTypeSize(CV->getElementType())
6533       != S.Context.getTypeSize(ResTy)) {
6534     // Since VectorTy is created internally, it does not pretty print
6535     // with an OpenCL name. Instead, we just print a description.
6536     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6537     SmallString<64> Str;
6538     llvm::raw_svector_ostream OS(Str);
6539     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6540     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6541       << CondTy << OS.str();
6542     return QualType();
6543   }
6544 
6545   // Convert operands to the vector result type
6546   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6547   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6548 
6549   return VectorTy;
6550 }
6551 
6552 /// \brief Return false if this is a valid OpenCL condition vector
6553 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6554                                        SourceLocation QuestionLoc) {
6555   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6556   // integral type.
6557   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6558   assert(CondTy);
6559   QualType EleTy = CondTy->getElementType();
6560   if (EleTy->isIntegerType()) return false;
6561 
6562   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6563     << Cond->getType() << Cond->getSourceRange();
6564   return true;
6565 }
6566 
6567 /// \brief Return false if the vector condition type and the vector
6568 ///        result type are compatible.
6569 ///
6570 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6571 /// number of elements, and their element types have the same number
6572 /// of bits.
6573 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6574                               SourceLocation QuestionLoc) {
6575   const VectorType *CV = CondTy->getAs<VectorType>();
6576   const VectorType *RV = VecResTy->getAs<VectorType>();
6577   assert(CV && RV);
6578 
6579   if (CV->getNumElements() != RV->getNumElements()) {
6580     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6581       << CondTy << VecResTy;
6582     return true;
6583   }
6584 
6585   QualType CVE = CV->getElementType();
6586   QualType RVE = RV->getElementType();
6587 
6588   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6589     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6590       << CondTy << VecResTy;
6591     return true;
6592   }
6593 
6594   return false;
6595 }
6596 
6597 /// \brief Return the resulting type for the conditional operator in
6598 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6599 ///        s6.3.i) when the condition is a vector type.
6600 static QualType
6601 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6602                              ExprResult &LHS, ExprResult &RHS,
6603                              SourceLocation QuestionLoc) {
6604   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6605   if (Cond.isInvalid())
6606     return QualType();
6607   QualType CondTy = Cond.get()->getType();
6608 
6609   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6610     return QualType();
6611 
6612   // If either operand is a vector then find the vector type of the
6613   // result as specified in OpenCL v1.1 s6.3.i.
6614   if (LHS.get()->getType()->isVectorType() ||
6615       RHS.get()->getType()->isVectorType()) {
6616     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6617                                               /*isCompAssign*/false,
6618                                               /*AllowBothBool*/true,
6619                                               /*AllowBoolConversions*/false);
6620     if (VecResTy.isNull()) return QualType();
6621     // The result type must match the condition type as specified in
6622     // OpenCL v1.1 s6.11.6.
6623     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6624       return QualType();
6625     return VecResTy;
6626   }
6627 
6628   // Both operands are scalar.
6629   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6630 }
6631 
6632 /// \brief Return true if the Expr is block type
6633 static bool checkBlockType(Sema &S, const Expr *E) {
6634   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6635     QualType Ty = CE->getCallee()->getType();
6636     if (Ty->isBlockPointerType()) {
6637       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6638       return true;
6639     }
6640   }
6641   return false;
6642 }
6643 
6644 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6645 /// In that case, LHS = cond.
6646 /// C99 6.5.15
6647 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6648                                         ExprResult &RHS, ExprValueKind &VK,
6649                                         ExprObjectKind &OK,
6650                                         SourceLocation QuestionLoc) {
6651 
6652   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6653   if (!LHSResult.isUsable()) return QualType();
6654   LHS = LHSResult;
6655 
6656   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6657   if (!RHSResult.isUsable()) return QualType();
6658   RHS = RHSResult;
6659 
6660   // C++ is sufficiently different to merit its own checker.
6661   if (getLangOpts().CPlusPlus)
6662     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6663 
6664   VK = VK_RValue;
6665   OK = OK_Ordinary;
6666 
6667   // The OpenCL operator with a vector condition is sufficiently
6668   // different to merit its own checker.
6669   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6670     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6671 
6672   // First, check the condition.
6673   Cond = UsualUnaryConversions(Cond.get());
6674   if (Cond.isInvalid())
6675     return QualType();
6676   if (checkCondition(*this, Cond.get(), QuestionLoc))
6677     return QualType();
6678 
6679   // Now check the two expressions.
6680   if (LHS.get()->getType()->isVectorType() ||
6681       RHS.get()->getType()->isVectorType())
6682     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6683                                /*AllowBothBool*/true,
6684                                /*AllowBoolConversions*/false);
6685 
6686   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6687   if (LHS.isInvalid() || RHS.isInvalid())
6688     return QualType();
6689 
6690   QualType LHSTy = LHS.get()->getType();
6691   QualType RHSTy = RHS.get()->getType();
6692 
6693   // Diagnose attempts to convert between __float128 and long double where
6694   // such conversions currently can't be handled.
6695   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6696     Diag(QuestionLoc,
6697          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6698       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6699     return QualType();
6700   }
6701 
6702   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6703   // selection operator (?:).
6704   if (getLangOpts().OpenCL &&
6705       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6706     return QualType();
6707   }
6708 
6709   // If both operands have arithmetic type, do the usual arithmetic conversions
6710   // to find a common type: C99 6.5.15p3,5.
6711   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6712     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6713     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6714 
6715     return ResTy;
6716   }
6717 
6718   // If both operands are the same structure or union type, the result is that
6719   // type.
6720   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6721     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6722       if (LHSRT->getDecl() == RHSRT->getDecl())
6723         // "If both the operands have structure or union type, the result has
6724         // that type."  This implies that CV qualifiers are dropped.
6725         return LHSTy.getUnqualifiedType();
6726     // FIXME: Type of conditional expression must be complete in C mode.
6727   }
6728 
6729   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6730   // The following || allows only one side to be void (a GCC-ism).
6731   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6732     return checkConditionalVoidType(*this, LHS, RHS);
6733   }
6734 
6735   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6736   // the type of the other operand."
6737   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6738   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6739 
6740   // All objective-c pointer type analysis is done here.
6741   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6742                                                         QuestionLoc);
6743   if (LHS.isInvalid() || RHS.isInvalid())
6744     return QualType();
6745   if (!compositeType.isNull())
6746     return compositeType;
6747 
6748 
6749   // Handle block pointer types.
6750   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6751     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6752                                                      QuestionLoc);
6753 
6754   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6755   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6756     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6757                                                        QuestionLoc);
6758 
6759   // GCC compatibility: soften pointer/integer mismatch.  Note that
6760   // null pointers have been filtered out by this point.
6761   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6762       /*isIntFirstExpr=*/true))
6763     return RHSTy;
6764   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6765       /*isIntFirstExpr=*/false))
6766     return LHSTy;
6767 
6768   // Emit a better diagnostic if one of the expressions is a null pointer
6769   // constant and the other is not a pointer type. In this case, the user most
6770   // likely forgot to take the address of the other expression.
6771   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6772     return QualType();
6773 
6774   // Otherwise, the operands are not compatible.
6775   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6776     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6777     << RHS.get()->getSourceRange();
6778   return QualType();
6779 }
6780 
6781 /// FindCompositeObjCPointerType - Helper method to find composite type of
6782 /// two objective-c pointer types of the two input expressions.
6783 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6784                                             SourceLocation QuestionLoc) {
6785   QualType LHSTy = LHS.get()->getType();
6786   QualType RHSTy = RHS.get()->getType();
6787 
6788   // Handle things like Class and struct objc_class*.  Here we case the result
6789   // to the pseudo-builtin, because that will be implicitly cast back to the
6790   // redefinition type if an attempt is made to access its fields.
6791   if (LHSTy->isObjCClassType() &&
6792       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6793     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6794     return LHSTy;
6795   }
6796   if (RHSTy->isObjCClassType() &&
6797       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6798     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6799     return RHSTy;
6800   }
6801   // And the same for struct objc_object* / id
6802   if (LHSTy->isObjCIdType() &&
6803       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6804     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6805     return LHSTy;
6806   }
6807   if (RHSTy->isObjCIdType() &&
6808       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6809     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6810     return RHSTy;
6811   }
6812   // And the same for struct objc_selector* / SEL
6813   if (Context.isObjCSelType(LHSTy) &&
6814       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6815     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6816     return LHSTy;
6817   }
6818   if (Context.isObjCSelType(RHSTy) &&
6819       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6820     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6821     return RHSTy;
6822   }
6823   // Check constraints for Objective-C object pointers types.
6824   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6825 
6826     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6827       // Two identical object pointer types are always compatible.
6828       return LHSTy;
6829     }
6830     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6831     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6832     QualType compositeType = LHSTy;
6833 
6834     // If both operands are interfaces and either operand can be
6835     // assigned to the other, use that type as the composite
6836     // type. This allows
6837     //   xxx ? (A*) a : (B*) b
6838     // where B is a subclass of A.
6839     //
6840     // Additionally, as for assignment, if either type is 'id'
6841     // allow silent coercion. Finally, if the types are
6842     // incompatible then make sure to use 'id' as the composite
6843     // type so the result is acceptable for sending messages to.
6844 
6845     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6846     // It could return the composite type.
6847     if (!(compositeType =
6848           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6849       // Nothing more to do.
6850     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6851       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6852     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6853       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6854     } else if ((LHSTy->isObjCQualifiedIdType() ||
6855                 RHSTy->isObjCQualifiedIdType()) &&
6856                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6857       // Need to handle "id<xx>" explicitly.
6858       // GCC allows qualified id and any Objective-C type to devolve to
6859       // id. Currently localizing to here until clear this should be
6860       // part of ObjCQualifiedIdTypesAreCompatible.
6861       compositeType = Context.getObjCIdType();
6862     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6863       compositeType = Context.getObjCIdType();
6864     } else {
6865       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6866       << LHSTy << RHSTy
6867       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6868       QualType incompatTy = Context.getObjCIdType();
6869       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6870       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6871       return incompatTy;
6872     }
6873     // The object pointer types are compatible.
6874     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6875     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6876     return compositeType;
6877   }
6878   // Check Objective-C object pointer types and 'void *'
6879   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6880     if (getLangOpts().ObjCAutoRefCount) {
6881       // ARC forbids the implicit conversion of object pointers to 'void *',
6882       // so these types are not compatible.
6883       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6884           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6885       LHS = RHS = true;
6886       return QualType();
6887     }
6888     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6889     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6890     QualType destPointee
6891     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6892     QualType destType = Context.getPointerType(destPointee);
6893     // Add qualifiers if necessary.
6894     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6895     // Promote to void*.
6896     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6897     return destType;
6898   }
6899   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6900     if (getLangOpts().ObjCAutoRefCount) {
6901       // ARC forbids the implicit conversion of object pointers to 'void *',
6902       // so these types are not compatible.
6903       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6904           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6905       LHS = RHS = true;
6906       return QualType();
6907     }
6908     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6909     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6910     QualType destPointee
6911     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6912     QualType destType = Context.getPointerType(destPointee);
6913     // Add qualifiers if necessary.
6914     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6915     // Promote to void*.
6916     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6917     return destType;
6918   }
6919   return QualType();
6920 }
6921 
6922 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6923 /// ParenRange in parentheses.
6924 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6925                                const PartialDiagnostic &Note,
6926                                SourceRange ParenRange) {
6927   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6928   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6929       EndLoc.isValid()) {
6930     Self.Diag(Loc, Note)
6931       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6932       << FixItHint::CreateInsertion(EndLoc, ")");
6933   } else {
6934     // We can't display the parentheses, so just show the bare note.
6935     Self.Diag(Loc, Note) << ParenRange;
6936   }
6937 }
6938 
6939 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6940   return BinaryOperator::isAdditiveOp(Opc) ||
6941          BinaryOperator::isMultiplicativeOp(Opc) ||
6942          BinaryOperator::isShiftOp(Opc);
6943 }
6944 
6945 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6946 /// expression, either using a built-in or overloaded operator,
6947 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6948 /// expression.
6949 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6950                                    Expr **RHSExprs) {
6951   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6952   E = E->IgnoreImpCasts();
6953   E = E->IgnoreConversionOperator();
6954   E = E->IgnoreImpCasts();
6955 
6956   // Built-in binary operator.
6957   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6958     if (IsArithmeticOp(OP->getOpcode())) {
6959       *Opcode = OP->getOpcode();
6960       *RHSExprs = OP->getRHS();
6961       return true;
6962     }
6963   }
6964 
6965   // Overloaded operator.
6966   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6967     if (Call->getNumArgs() != 2)
6968       return false;
6969 
6970     // Make sure this is really a binary operator that is safe to pass into
6971     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6972     OverloadedOperatorKind OO = Call->getOperator();
6973     if (OO < OO_Plus || OO > OO_Arrow ||
6974         OO == OO_PlusPlus || OO == OO_MinusMinus)
6975       return false;
6976 
6977     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6978     if (IsArithmeticOp(OpKind)) {
6979       *Opcode = OpKind;
6980       *RHSExprs = Call->getArg(1);
6981       return true;
6982     }
6983   }
6984 
6985   return false;
6986 }
6987 
6988 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6989 /// or is a logical expression such as (x==y) which has int type, but is
6990 /// commonly interpreted as boolean.
6991 static bool ExprLooksBoolean(Expr *E) {
6992   E = E->IgnoreParenImpCasts();
6993 
6994   if (E->getType()->isBooleanType())
6995     return true;
6996   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6997     return OP->isComparisonOp() || OP->isLogicalOp();
6998   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6999     return OP->getOpcode() == UO_LNot;
7000   if (E->getType()->isPointerType())
7001     return true;
7002 
7003   return false;
7004 }
7005 
7006 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7007 /// and binary operator are mixed in a way that suggests the programmer assumed
7008 /// the conditional operator has higher precedence, for example:
7009 /// "int x = a + someBinaryCondition ? 1 : 2".
7010 static void DiagnoseConditionalPrecedence(Sema &Self,
7011                                           SourceLocation OpLoc,
7012                                           Expr *Condition,
7013                                           Expr *LHSExpr,
7014                                           Expr *RHSExpr) {
7015   BinaryOperatorKind CondOpcode;
7016   Expr *CondRHS;
7017 
7018   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7019     return;
7020   if (!ExprLooksBoolean(CondRHS))
7021     return;
7022 
7023   // The condition is an arithmetic binary expression, with a right-
7024   // hand side that looks boolean, so warn.
7025 
7026   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7027       << Condition->getSourceRange()
7028       << BinaryOperator::getOpcodeStr(CondOpcode);
7029 
7030   SuggestParentheses(Self, OpLoc,
7031     Self.PDiag(diag::note_precedence_silence)
7032       << BinaryOperator::getOpcodeStr(CondOpcode),
7033     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7034 
7035   SuggestParentheses(Self, OpLoc,
7036     Self.PDiag(diag::note_precedence_conditional_first),
7037     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7038 }
7039 
7040 /// Compute the nullability of a conditional expression.
7041 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7042                                               QualType LHSTy, QualType RHSTy,
7043                                               ASTContext &Ctx) {
7044   if (!ResTy->isAnyPointerType())
7045     return ResTy;
7046 
7047   auto GetNullability = [&Ctx](QualType Ty) {
7048     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7049     if (Kind)
7050       return *Kind;
7051     return NullabilityKind::Unspecified;
7052   };
7053 
7054   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7055   NullabilityKind MergedKind;
7056 
7057   // Compute nullability of a binary conditional expression.
7058   if (IsBin) {
7059     if (LHSKind == NullabilityKind::NonNull)
7060       MergedKind = NullabilityKind::NonNull;
7061     else
7062       MergedKind = RHSKind;
7063   // Compute nullability of a normal conditional expression.
7064   } else {
7065     if (LHSKind == NullabilityKind::Nullable ||
7066         RHSKind == NullabilityKind::Nullable)
7067       MergedKind = NullabilityKind::Nullable;
7068     else if (LHSKind == NullabilityKind::NonNull)
7069       MergedKind = RHSKind;
7070     else if (RHSKind == NullabilityKind::NonNull)
7071       MergedKind = LHSKind;
7072     else
7073       MergedKind = NullabilityKind::Unspecified;
7074   }
7075 
7076   // Return if ResTy already has the correct nullability.
7077   if (GetNullability(ResTy) == MergedKind)
7078     return ResTy;
7079 
7080   // Strip all nullability from ResTy.
7081   while (ResTy->getNullability(Ctx))
7082     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7083 
7084   // Create a new AttributedType with the new nullability kind.
7085   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7086   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7087 }
7088 
7089 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7090 /// in the case of a the GNU conditional expr extension.
7091 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7092                                     SourceLocation ColonLoc,
7093                                     Expr *CondExpr, Expr *LHSExpr,
7094                                     Expr *RHSExpr) {
7095   if (!getLangOpts().CPlusPlus) {
7096     // C cannot handle TypoExpr nodes in the condition because it
7097     // doesn't handle dependent types properly, so make sure any TypoExprs have
7098     // been dealt with before checking the operands.
7099     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7100     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7101     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7102 
7103     if (!CondResult.isUsable())
7104       return ExprError();
7105 
7106     if (LHSExpr) {
7107       if (!LHSResult.isUsable())
7108         return ExprError();
7109     }
7110 
7111     if (!RHSResult.isUsable())
7112       return ExprError();
7113 
7114     CondExpr = CondResult.get();
7115     LHSExpr = LHSResult.get();
7116     RHSExpr = RHSResult.get();
7117   }
7118 
7119   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7120   // was the condition.
7121   OpaqueValueExpr *opaqueValue = nullptr;
7122   Expr *commonExpr = nullptr;
7123   if (!LHSExpr) {
7124     commonExpr = CondExpr;
7125     // Lower out placeholder types first.  This is important so that we don't
7126     // try to capture a placeholder. This happens in few cases in C++; such
7127     // as Objective-C++'s dictionary subscripting syntax.
7128     if (commonExpr->hasPlaceholderType()) {
7129       ExprResult result = CheckPlaceholderExpr(commonExpr);
7130       if (!result.isUsable()) return ExprError();
7131       commonExpr = result.get();
7132     }
7133     // We usually want to apply unary conversions *before* saving, except
7134     // in the special case of a C++ l-value conditional.
7135     if (!(getLangOpts().CPlusPlus
7136           && !commonExpr->isTypeDependent()
7137           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7138           && commonExpr->isGLValue()
7139           && commonExpr->isOrdinaryOrBitFieldObject()
7140           && RHSExpr->isOrdinaryOrBitFieldObject()
7141           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7142       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7143       if (commonRes.isInvalid())
7144         return ExprError();
7145       commonExpr = commonRes.get();
7146     }
7147 
7148     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7149                                                 commonExpr->getType(),
7150                                                 commonExpr->getValueKind(),
7151                                                 commonExpr->getObjectKind(),
7152                                                 commonExpr);
7153     LHSExpr = CondExpr = opaqueValue;
7154   }
7155 
7156   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7157   ExprValueKind VK = VK_RValue;
7158   ExprObjectKind OK = OK_Ordinary;
7159   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7160   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7161                                              VK, OK, QuestionLoc);
7162   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7163       RHS.isInvalid())
7164     return ExprError();
7165 
7166   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7167                                 RHS.get());
7168 
7169   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7170 
7171   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7172                                          Context);
7173 
7174   if (!commonExpr)
7175     return new (Context)
7176         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7177                             RHS.get(), result, VK, OK);
7178 
7179   return new (Context) BinaryConditionalOperator(
7180       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7181       ColonLoc, result, VK, OK);
7182 }
7183 
7184 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7185 // being closely modeled after the C99 spec:-). The odd characteristic of this
7186 // routine is it effectively iqnores the qualifiers on the top level pointee.
7187 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7188 // FIXME: add a couple examples in this comment.
7189 static Sema::AssignConvertType
7190 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7191   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7192   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7193 
7194   // get the "pointed to" type (ignoring qualifiers at the top level)
7195   const Type *lhptee, *rhptee;
7196   Qualifiers lhq, rhq;
7197   std::tie(lhptee, lhq) =
7198       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7199   std::tie(rhptee, rhq) =
7200       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7201 
7202   Sema::AssignConvertType ConvTy = Sema::Compatible;
7203 
7204   // C99 6.5.16.1p1: This following citation is common to constraints
7205   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7206   // qualifiers of the type *pointed to* by the right;
7207 
7208   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7209   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7210       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7211     // Ignore lifetime for further calculation.
7212     lhq.removeObjCLifetime();
7213     rhq.removeObjCLifetime();
7214   }
7215 
7216   if (!lhq.compatiblyIncludes(rhq)) {
7217     // Treat address-space mismatches as fatal.  TODO: address subspaces
7218     if (!lhq.isAddressSpaceSupersetOf(rhq))
7219       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7220 
7221     // It's okay to add or remove GC or lifetime qualifiers when converting to
7222     // and from void*.
7223     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7224                         .compatiblyIncludes(
7225                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7226              && (lhptee->isVoidType() || rhptee->isVoidType()))
7227       ; // keep old
7228 
7229     // Treat lifetime mismatches as fatal.
7230     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7231       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7232 
7233     // For GCC/MS compatibility, other qualifier mismatches are treated
7234     // as still compatible in C.
7235     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7236   }
7237 
7238   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7239   // incomplete type and the other is a pointer to a qualified or unqualified
7240   // version of void...
7241   if (lhptee->isVoidType()) {
7242     if (rhptee->isIncompleteOrObjectType())
7243       return ConvTy;
7244 
7245     // As an extension, we allow cast to/from void* to function pointer.
7246     assert(rhptee->isFunctionType());
7247     return Sema::FunctionVoidPointer;
7248   }
7249 
7250   if (rhptee->isVoidType()) {
7251     if (lhptee->isIncompleteOrObjectType())
7252       return ConvTy;
7253 
7254     // As an extension, we allow cast to/from void* to function pointer.
7255     assert(lhptee->isFunctionType());
7256     return Sema::FunctionVoidPointer;
7257   }
7258 
7259   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7260   // unqualified versions of compatible types, ...
7261   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7262   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7263     // Check if the pointee types are compatible ignoring the sign.
7264     // We explicitly check for char so that we catch "char" vs
7265     // "unsigned char" on systems where "char" is unsigned.
7266     if (lhptee->isCharType())
7267       ltrans = S.Context.UnsignedCharTy;
7268     else if (lhptee->hasSignedIntegerRepresentation())
7269       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7270 
7271     if (rhptee->isCharType())
7272       rtrans = S.Context.UnsignedCharTy;
7273     else if (rhptee->hasSignedIntegerRepresentation())
7274       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7275 
7276     if (ltrans == rtrans) {
7277       // Types are compatible ignoring the sign. Qualifier incompatibility
7278       // takes priority over sign incompatibility because the sign
7279       // warning can be disabled.
7280       if (ConvTy != Sema::Compatible)
7281         return ConvTy;
7282 
7283       return Sema::IncompatiblePointerSign;
7284     }
7285 
7286     // If we are a multi-level pointer, it's possible that our issue is simply
7287     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7288     // the eventual target type is the same and the pointers have the same
7289     // level of indirection, this must be the issue.
7290     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7291       do {
7292         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7293         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7294       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7295 
7296       if (lhptee == rhptee)
7297         return Sema::IncompatibleNestedPointerQualifiers;
7298     }
7299 
7300     // General pointer incompatibility takes priority over qualifiers.
7301     return Sema::IncompatiblePointer;
7302   }
7303   if (!S.getLangOpts().CPlusPlus &&
7304       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7305     return Sema::IncompatiblePointer;
7306   return ConvTy;
7307 }
7308 
7309 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7310 /// block pointer types are compatible or whether a block and normal pointer
7311 /// are compatible. It is more restrict than comparing two function pointer
7312 // types.
7313 static Sema::AssignConvertType
7314 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7315                                     QualType RHSType) {
7316   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7317   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7318 
7319   QualType lhptee, rhptee;
7320 
7321   // get the "pointed to" type (ignoring qualifiers at the top level)
7322   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7323   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7324 
7325   // In C++, the types have to match exactly.
7326   if (S.getLangOpts().CPlusPlus)
7327     return Sema::IncompatibleBlockPointer;
7328 
7329   Sema::AssignConvertType ConvTy = Sema::Compatible;
7330 
7331   // For blocks we enforce that qualifiers are identical.
7332   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7333     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7334 
7335   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7336     return Sema::IncompatibleBlockPointer;
7337 
7338   return ConvTy;
7339 }
7340 
7341 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7342 /// for assignment compatibility.
7343 static Sema::AssignConvertType
7344 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7345                                    QualType RHSType) {
7346   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7347   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7348 
7349   if (LHSType->isObjCBuiltinType()) {
7350     // Class is not compatible with ObjC object pointers.
7351     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7352         !RHSType->isObjCQualifiedClassType())
7353       return Sema::IncompatiblePointer;
7354     return Sema::Compatible;
7355   }
7356   if (RHSType->isObjCBuiltinType()) {
7357     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7358         !LHSType->isObjCQualifiedClassType())
7359       return Sema::IncompatiblePointer;
7360     return Sema::Compatible;
7361   }
7362   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7363   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7364 
7365   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7366       // make an exception for id<P>
7367       !LHSType->isObjCQualifiedIdType())
7368     return Sema::CompatiblePointerDiscardsQualifiers;
7369 
7370   if (S.Context.typesAreCompatible(LHSType, RHSType))
7371     return Sema::Compatible;
7372   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7373     return Sema::IncompatibleObjCQualifiedId;
7374   return Sema::IncompatiblePointer;
7375 }
7376 
7377 Sema::AssignConvertType
7378 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7379                                  QualType LHSType, QualType RHSType) {
7380   // Fake up an opaque expression.  We don't actually care about what
7381   // cast operations are required, so if CheckAssignmentConstraints
7382   // adds casts to this they'll be wasted, but fortunately that doesn't
7383   // usually happen on valid code.
7384   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7385   ExprResult RHSPtr = &RHSExpr;
7386   CastKind K = CK_Invalid;
7387 
7388   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7389 }
7390 
7391 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7392 /// has code to accommodate several GCC extensions when type checking
7393 /// pointers. Here are some objectionable examples that GCC considers warnings:
7394 ///
7395 ///  int a, *pint;
7396 ///  short *pshort;
7397 ///  struct foo *pfoo;
7398 ///
7399 ///  pint = pshort; // warning: assignment from incompatible pointer type
7400 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7401 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7402 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7403 ///
7404 /// As a result, the code for dealing with pointers is more complex than the
7405 /// C99 spec dictates.
7406 ///
7407 /// Sets 'Kind' for any result kind except Incompatible.
7408 Sema::AssignConvertType
7409 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7410                                  CastKind &Kind, bool ConvertRHS) {
7411   QualType RHSType = RHS.get()->getType();
7412   QualType OrigLHSType = LHSType;
7413 
7414   // Get canonical types.  We're not formatting these types, just comparing
7415   // them.
7416   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7417   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7418 
7419   // Common case: no conversion required.
7420   if (LHSType == RHSType) {
7421     Kind = CK_NoOp;
7422     return Compatible;
7423   }
7424 
7425   // If we have an atomic type, try a non-atomic assignment, then just add an
7426   // atomic qualification step.
7427   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7428     Sema::AssignConvertType result =
7429       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7430     if (result != Compatible)
7431       return result;
7432     if (Kind != CK_NoOp && ConvertRHS)
7433       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7434     Kind = CK_NonAtomicToAtomic;
7435     return Compatible;
7436   }
7437 
7438   // If the left-hand side is a reference type, then we are in a
7439   // (rare!) case where we've allowed the use of references in C,
7440   // e.g., as a parameter type in a built-in function. In this case,
7441   // just make sure that the type referenced is compatible with the
7442   // right-hand side type. The caller is responsible for adjusting
7443   // LHSType so that the resulting expression does not have reference
7444   // type.
7445   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7446     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7447       Kind = CK_LValueBitCast;
7448       return Compatible;
7449     }
7450     return Incompatible;
7451   }
7452 
7453   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7454   // to the same ExtVector type.
7455   if (LHSType->isExtVectorType()) {
7456     if (RHSType->isExtVectorType())
7457       return Incompatible;
7458     if (RHSType->isArithmeticType()) {
7459       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7460       if (ConvertRHS)
7461         RHS = prepareVectorSplat(LHSType, RHS.get());
7462       Kind = CK_VectorSplat;
7463       return Compatible;
7464     }
7465   }
7466 
7467   // Conversions to or from vector type.
7468   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7469     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7470       // Allow assignments of an AltiVec vector type to an equivalent GCC
7471       // vector type and vice versa
7472       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7473         Kind = CK_BitCast;
7474         return Compatible;
7475       }
7476 
7477       // If we are allowing lax vector conversions, and LHS and RHS are both
7478       // vectors, the total size only needs to be the same. This is a bitcast;
7479       // no bits are changed but the result type is different.
7480       if (isLaxVectorConversion(RHSType, LHSType)) {
7481         Kind = CK_BitCast;
7482         return IncompatibleVectors;
7483       }
7484     }
7485 
7486     // When the RHS comes from another lax conversion (e.g. binops between
7487     // scalars and vectors) the result is canonicalized as a vector. When the
7488     // LHS is also a vector, the lax is allowed by the condition above. Handle
7489     // the case where LHS is a scalar.
7490     if (LHSType->isScalarType()) {
7491       const VectorType *VecType = RHSType->getAs<VectorType>();
7492       if (VecType && VecType->getNumElements() == 1 &&
7493           isLaxVectorConversion(RHSType, LHSType)) {
7494         ExprResult *VecExpr = &RHS;
7495         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7496         Kind = CK_BitCast;
7497         return Compatible;
7498       }
7499     }
7500 
7501     return Incompatible;
7502   }
7503 
7504   // Diagnose attempts to convert between __float128 and long double where
7505   // such conversions currently can't be handled.
7506   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7507     return Incompatible;
7508 
7509   // Arithmetic conversions.
7510   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7511       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7512     if (ConvertRHS)
7513       Kind = PrepareScalarCast(RHS, LHSType);
7514     return Compatible;
7515   }
7516 
7517   // Conversions to normal pointers.
7518   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7519     // U* -> T*
7520     if (isa<PointerType>(RHSType)) {
7521       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7522       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7523       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7524       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7525     }
7526 
7527     // int -> T*
7528     if (RHSType->isIntegerType()) {
7529       Kind = CK_IntegralToPointer; // FIXME: null?
7530       return IntToPointer;
7531     }
7532 
7533     // C pointers are not compatible with ObjC object pointers,
7534     // with two exceptions:
7535     if (isa<ObjCObjectPointerType>(RHSType)) {
7536       //  - conversions to void*
7537       if (LHSPointer->getPointeeType()->isVoidType()) {
7538         Kind = CK_BitCast;
7539         return Compatible;
7540       }
7541 
7542       //  - conversions from 'Class' to the redefinition type
7543       if (RHSType->isObjCClassType() &&
7544           Context.hasSameType(LHSType,
7545                               Context.getObjCClassRedefinitionType())) {
7546         Kind = CK_BitCast;
7547         return Compatible;
7548       }
7549 
7550       Kind = CK_BitCast;
7551       return IncompatiblePointer;
7552     }
7553 
7554     // U^ -> void*
7555     if (RHSType->getAs<BlockPointerType>()) {
7556       if (LHSPointer->getPointeeType()->isVoidType()) {
7557         Kind = CK_BitCast;
7558         return Compatible;
7559       }
7560     }
7561 
7562     return Incompatible;
7563   }
7564 
7565   // Conversions to block pointers.
7566   if (isa<BlockPointerType>(LHSType)) {
7567     // U^ -> T^
7568     if (RHSType->isBlockPointerType()) {
7569       Kind = CK_BitCast;
7570       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7571     }
7572 
7573     // int or null -> T^
7574     if (RHSType->isIntegerType()) {
7575       Kind = CK_IntegralToPointer; // FIXME: null
7576       return IntToBlockPointer;
7577     }
7578 
7579     // id -> T^
7580     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7581       Kind = CK_AnyPointerToBlockPointerCast;
7582       return Compatible;
7583     }
7584 
7585     // void* -> T^
7586     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7587       if (RHSPT->getPointeeType()->isVoidType()) {
7588         Kind = CK_AnyPointerToBlockPointerCast;
7589         return Compatible;
7590       }
7591 
7592     return Incompatible;
7593   }
7594 
7595   // Conversions to Objective-C pointers.
7596   if (isa<ObjCObjectPointerType>(LHSType)) {
7597     // A* -> B*
7598     if (RHSType->isObjCObjectPointerType()) {
7599       Kind = CK_BitCast;
7600       Sema::AssignConvertType result =
7601         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7602       if (getLangOpts().ObjCAutoRefCount &&
7603           result == Compatible &&
7604           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7605         result = IncompatibleObjCWeakRef;
7606       return result;
7607     }
7608 
7609     // int or null -> A*
7610     if (RHSType->isIntegerType()) {
7611       Kind = CK_IntegralToPointer; // FIXME: null
7612       return IntToPointer;
7613     }
7614 
7615     // In general, C pointers are not compatible with ObjC object pointers,
7616     // with two exceptions:
7617     if (isa<PointerType>(RHSType)) {
7618       Kind = CK_CPointerToObjCPointerCast;
7619 
7620       //  - conversions from 'void*'
7621       if (RHSType->isVoidPointerType()) {
7622         return Compatible;
7623       }
7624 
7625       //  - conversions to 'Class' from its redefinition type
7626       if (LHSType->isObjCClassType() &&
7627           Context.hasSameType(RHSType,
7628                               Context.getObjCClassRedefinitionType())) {
7629         return Compatible;
7630       }
7631 
7632       return IncompatiblePointer;
7633     }
7634 
7635     // Only under strict condition T^ is compatible with an Objective-C pointer.
7636     if (RHSType->isBlockPointerType() &&
7637         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7638       if (ConvertRHS)
7639         maybeExtendBlockObject(RHS);
7640       Kind = CK_BlockPointerToObjCPointerCast;
7641       return Compatible;
7642     }
7643 
7644     return Incompatible;
7645   }
7646 
7647   // Conversions from pointers that are not covered by the above.
7648   if (isa<PointerType>(RHSType)) {
7649     // T* -> _Bool
7650     if (LHSType == Context.BoolTy) {
7651       Kind = CK_PointerToBoolean;
7652       return Compatible;
7653     }
7654 
7655     // T* -> int
7656     if (LHSType->isIntegerType()) {
7657       Kind = CK_PointerToIntegral;
7658       return PointerToInt;
7659     }
7660 
7661     return Incompatible;
7662   }
7663 
7664   // Conversions from Objective-C pointers that are not covered by the above.
7665   if (isa<ObjCObjectPointerType>(RHSType)) {
7666     // T* -> _Bool
7667     if (LHSType == Context.BoolTy) {
7668       Kind = CK_PointerToBoolean;
7669       return Compatible;
7670     }
7671 
7672     // T* -> int
7673     if (LHSType->isIntegerType()) {
7674       Kind = CK_PointerToIntegral;
7675       return PointerToInt;
7676     }
7677 
7678     return Incompatible;
7679   }
7680 
7681   // struct A -> struct B
7682   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7683     if (Context.typesAreCompatible(LHSType, RHSType)) {
7684       Kind = CK_NoOp;
7685       return Compatible;
7686     }
7687   }
7688 
7689   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7690     Kind = CK_IntToOCLSampler;
7691     return Compatible;
7692   }
7693 
7694   return Incompatible;
7695 }
7696 
7697 /// \brief Constructs a transparent union from an expression that is
7698 /// used to initialize the transparent union.
7699 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7700                                       ExprResult &EResult, QualType UnionType,
7701                                       FieldDecl *Field) {
7702   // Build an initializer list that designates the appropriate member
7703   // of the transparent union.
7704   Expr *E = EResult.get();
7705   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7706                                                    E, SourceLocation());
7707   Initializer->setType(UnionType);
7708   Initializer->setInitializedFieldInUnion(Field);
7709 
7710   // Build a compound literal constructing a value of the transparent
7711   // union type from this initializer list.
7712   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7713   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7714                                         VK_RValue, Initializer, false);
7715 }
7716 
7717 Sema::AssignConvertType
7718 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7719                                                ExprResult &RHS) {
7720   QualType RHSType = RHS.get()->getType();
7721 
7722   // If the ArgType is a Union type, we want to handle a potential
7723   // transparent_union GCC extension.
7724   const RecordType *UT = ArgType->getAsUnionType();
7725   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7726     return Incompatible;
7727 
7728   // The field to initialize within the transparent union.
7729   RecordDecl *UD = UT->getDecl();
7730   FieldDecl *InitField = nullptr;
7731   // It's compatible if the expression matches any of the fields.
7732   for (auto *it : UD->fields()) {
7733     if (it->getType()->isPointerType()) {
7734       // If the transparent union contains a pointer type, we allow:
7735       // 1) void pointer
7736       // 2) null pointer constant
7737       if (RHSType->isPointerType())
7738         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7739           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7740           InitField = it;
7741           break;
7742         }
7743 
7744       if (RHS.get()->isNullPointerConstant(Context,
7745                                            Expr::NPC_ValueDependentIsNull)) {
7746         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7747                                 CK_NullToPointer);
7748         InitField = it;
7749         break;
7750       }
7751     }
7752 
7753     CastKind Kind = CK_Invalid;
7754     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7755           == Compatible) {
7756       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7757       InitField = it;
7758       break;
7759     }
7760   }
7761 
7762   if (!InitField)
7763     return Incompatible;
7764 
7765   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7766   return Compatible;
7767 }
7768 
7769 Sema::AssignConvertType
7770 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7771                                        bool Diagnose,
7772                                        bool DiagnoseCFAudited,
7773                                        bool ConvertRHS) {
7774   // We need to be able to tell the caller whether we diagnosed a problem, if
7775   // they ask us to issue diagnostics.
7776   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7777 
7778   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7779   // we can't avoid *all* modifications at the moment, so we need some somewhere
7780   // to put the updated value.
7781   ExprResult LocalRHS = CallerRHS;
7782   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7783 
7784   if (getLangOpts().CPlusPlus) {
7785     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7786       // C++ 5.17p3: If the left operand is not of class type, the
7787       // expression is implicitly converted (C++ 4) to the
7788       // cv-unqualified type of the left operand.
7789       QualType RHSType = RHS.get()->getType();
7790       if (Diagnose) {
7791         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7792                                         AA_Assigning);
7793       } else {
7794         ImplicitConversionSequence ICS =
7795             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7796                                   /*SuppressUserConversions=*/false,
7797                                   /*AllowExplicit=*/false,
7798                                   /*InOverloadResolution=*/false,
7799                                   /*CStyle=*/false,
7800                                   /*AllowObjCWritebackConversion=*/false);
7801         if (ICS.isFailure())
7802           return Incompatible;
7803         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7804                                         ICS, AA_Assigning);
7805       }
7806       if (RHS.isInvalid())
7807         return Incompatible;
7808       Sema::AssignConvertType result = Compatible;
7809       if (getLangOpts().ObjCAutoRefCount &&
7810           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7811         result = IncompatibleObjCWeakRef;
7812       return result;
7813     }
7814 
7815     // FIXME: Currently, we fall through and treat C++ classes like C
7816     // structures.
7817     // FIXME: We also fall through for atomics; not sure what should
7818     // happen there, though.
7819   } else if (RHS.get()->getType() == Context.OverloadTy) {
7820     // As a set of extensions to C, we support overloading on functions. These
7821     // functions need to be resolved here.
7822     DeclAccessPair DAP;
7823     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7824             RHS.get(), LHSType, /*Complain=*/false, DAP))
7825       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7826     else
7827       return Incompatible;
7828   }
7829 
7830   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7831   // a null pointer constant.
7832   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7833        LHSType->isBlockPointerType()) &&
7834       RHS.get()->isNullPointerConstant(Context,
7835                                        Expr::NPC_ValueDependentIsNull)) {
7836     if (Diagnose || ConvertRHS) {
7837       CastKind Kind;
7838       CXXCastPath Path;
7839       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7840                              /*IgnoreBaseAccess=*/false, Diagnose);
7841       if (ConvertRHS)
7842         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7843     }
7844     return Compatible;
7845   }
7846 
7847   // This check seems unnatural, however it is necessary to ensure the proper
7848   // conversion of functions/arrays. If the conversion were done for all
7849   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7850   // expressions that suppress this implicit conversion (&, sizeof).
7851   //
7852   // Suppress this for references: C++ 8.5.3p5.
7853   if (!LHSType->isReferenceType()) {
7854     // FIXME: We potentially allocate here even if ConvertRHS is false.
7855     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7856     if (RHS.isInvalid())
7857       return Incompatible;
7858   }
7859 
7860   Expr *PRE = RHS.get()->IgnoreParenCasts();
7861   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7862     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7863     if (PDecl && !PDecl->hasDefinition()) {
7864       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7865       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7866     }
7867   }
7868 
7869   CastKind Kind = CK_Invalid;
7870   Sema::AssignConvertType result =
7871     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7872 
7873   // C99 6.5.16.1p2: The value of the right operand is converted to the
7874   // type of the assignment expression.
7875   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7876   // so that we can use references in built-in functions even in C.
7877   // The getNonReferenceType() call makes sure that the resulting expression
7878   // does not have reference type.
7879   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7880     QualType Ty = LHSType.getNonLValueExprType(Context);
7881     Expr *E = RHS.get();
7882 
7883     // Check for various Objective-C errors. If we are not reporting
7884     // diagnostics and just checking for errors, e.g., during overload
7885     // resolution, return Incompatible to indicate the failure.
7886     if (getLangOpts().ObjCAutoRefCount &&
7887         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7888                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7889       if (!Diagnose)
7890         return Incompatible;
7891     }
7892     if (getLangOpts().ObjC1 &&
7893         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7894                                            E->getType(), E, Diagnose) ||
7895          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7896       if (!Diagnose)
7897         return Incompatible;
7898       // Replace the expression with a corrected version and continue so we
7899       // can find further errors.
7900       RHS = E;
7901       return Compatible;
7902     }
7903 
7904     if (ConvertRHS)
7905       RHS = ImpCastExprToType(E, Ty, Kind);
7906   }
7907   return result;
7908 }
7909 
7910 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7911                                ExprResult &RHS) {
7912   Diag(Loc, diag::err_typecheck_invalid_operands)
7913     << LHS.get()->getType() << RHS.get()->getType()
7914     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7915   return QualType();
7916 }
7917 
7918 /// Try to convert a value of non-vector type to a vector type by converting
7919 /// the type to the element type of the vector and then performing a splat.
7920 /// If the language is OpenCL, we only use conversions that promote scalar
7921 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7922 /// for float->int.
7923 ///
7924 /// \param scalar - if non-null, actually perform the conversions
7925 /// \return true if the operation fails (but without diagnosing the failure)
7926 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7927                                      QualType scalarTy,
7928                                      QualType vectorEltTy,
7929                                      QualType vectorTy) {
7930   // The conversion to apply to the scalar before splatting it,
7931   // if necessary.
7932   CastKind scalarCast = CK_Invalid;
7933 
7934   if (vectorEltTy->isIntegralType(S.Context)) {
7935     if (!scalarTy->isIntegralType(S.Context))
7936       return true;
7937     if (S.getLangOpts().OpenCL &&
7938         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7939       return true;
7940     scalarCast = CK_IntegralCast;
7941   } else if (vectorEltTy->isRealFloatingType()) {
7942     if (scalarTy->isRealFloatingType()) {
7943       if (S.getLangOpts().OpenCL &&
7944           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7945         return true;
7946       scalarCast = CK_FloatingCast;
7947     }
7948     else if (scalarTy->isIntegralType(S.Context))
7949       scalarCast = CK_IntegralToFloating;
7950     else
7951       return true;
7952   } else {
7953     return true;
7954   }
7955 
7956   // Adjust scalar if desired.
7957   if (scalar) {
7958     if (scalarCast != CK_Invalid)
7959       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7960     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7961   }
7962   return false;
7963 }
7964 
7965 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7966                                    SourceLocation Loc, bool IsCompAssign,
7967                                    bool AllowBothBool,
7968                                    bool AllowBoolConversions) {
7969   if (!IsCompAssign) {
7970     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7971     if (LHS.isInvalid())
7972       return QualType();
7973   }
7974   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7975   if (RHS.isInvalid())
7976     return QualType();
7977 
7978   // For conversion purposes, we ignore any qualifiers.
7979   // For example, "const float" and "float" are equivalent.
7980   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7981   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7982 
7983   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7984   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7985   assert(LHSVecType || RHSVecType);
7986 
7987   // AltiVec-style "vector bool op vector bool" combinations are allowed
7988   // for some operators but not others.
7989   if (!AllowBothBool &&
7990       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7991       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7992     return InvalidOperands(Loc, LHS, RHS);
7993 
7994   // If the vector types are identical, return.
7995   if (Context.hasSameType(LHSType, RHSType))
7996     return LHSType;
7997 
7998   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7999   if (LHSVecType && RHSVecType &&
8000       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8001     if (isa<ExtVectorType>(LHSVecType)) {
8002       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8003       return LHSType;
8004     }
8005 
8006     if (!IsCompAssign)
8007       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8008     return RHSType;
8009   }
8010 
8011   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8012   // can be mixed, with the result being the non-bool type.  The non-bool
8013   // operand must have integer element type.
8014   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8015       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8016       (Context.getTypeSize(LHSVecType->getElementType()) ==
8017        Context.getTypeSize(RHSVecType->getElementType()))) {
8018     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8019         LHSVecType->getElementType()->isIntegerType() &&
8020         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8021       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8022       return LHSType;
8023     }
8024     if (!IsCompAssign &&
8025         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8026         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8027         RHSVecType->getElementType()->isIntegerType()) {
8028       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8029       return RHSType;
8030     }
8031   }
8032 
8033   // If there's an ext-vector type and a scalar, try to convert the scalar to
8034   // the vector element type and splat.
8035   // FIXME: this should also work for regular vector types as supported in GCC.
8036   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8037     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8038                                   LHSVecType->getElementType(), LHSType))
8039       return LHSType;
8040   }
8041   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8042     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8043                                   LHSType, RHSVecType->getElementType(),
8044                                   RHSType))
8045       return RHSType;
8046   }
8047 
8048   // FIXME: The code below also handles convertion between vectors and
8049   // non-scalars, we should break this down into fine grained specific checks
8050   // and emit proper diagnostics.
8051   QualType VecType = LHSVecType ? LHSType : RHSType;
8052   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8053   QualType OtherType = LHSVecType ? RHSType : LHSType;
8054   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8055   if (isLaxVectorConversion(OtherType, VecType)) {
8056     // If we're allowing lax vector conversions, only the total (data) size
8057     // needs to be the same. For non compound assignment, if one of the types is
8058     // scalar, the result is always the vector type.
8059     if (!IsCompAssign) {
8060       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8061       return VecType;
8062     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8063     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8064     // type. Note that this is already done by non-compound assignments in
8065     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8066     // <1 x T> -> T. The result is also a vector type.
8067     } else if (OtherType->isExtVectorType() ||
8068                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8069       ExprResult *RHSExpr = &RHS;
8070       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8071       return VecType;
8072     }
8073   }
8074 
8075   // Okay, the expression is invalid.
8076 
8077   // If there's a non-vector, non-real operand, diagnose that.
8078   if ((!RHSVecType && !RHSType->isRealType()) ||
8079       (!LHSVecType && !LHSType->isRealType())) {
8080     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8081       << LHSType << RHSType
8082       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8083     return QualType();
8084   }
8085 
8086   // OpenCL V1.1 6.2.6.p1:
8087   // If the operands are of more than one vector type, then an error shall
8088   // occur. Implicit conversions between vector types are not permitted, per
8089   // section 6.2.1.
8090   if (getLangOpts().OpenCL &&
8091       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8092       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8093     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8094                                                            << RHSType;
8095     return QualType();
8096   }
8097 
8098   // Otherwise, use the generic diagnostic.
8099   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8100     << LHSType << RHSType
8101     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8102   return QualType();
8103 }
8104 
8105 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8106 // expression.  These are mainly cases where the null pointer is used as an
8107 // integer instead of a pointer.
8108 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8109                                 SourceLocation Loc, bool IsCompare) {
8110   // The canonical way to check for a GNU null is with isNullPointerConstant,
8111   // but we use a bit of a hack here for speed; this is a relatively
8112   // hot path, and isNullPointerConstant is slow.
8113   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8114   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8115 
8116   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8117 
8118   // Avoid analyzing cases where the result will either be invalid (and
8119   // diagnosed as such) or entirely valid and not something to warn about.
8120   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8121       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8122     return;
8123 
8124   // Comparison operations would not make sense with a null pointer no matter
8125   // what the other expression is.
8126   if (!IsCompare) {
8127     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8128         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8129         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8130     return;
8131   }
8132 
8133   // The rest of the operations only make sense with a null pointer
8134   // if the other expression is a pointer.
8135   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8136       NonNullType->canDecayToPointerType())
8137     return;
8138 
8139   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8140       << LHSNull /* LHS is NULL */ << NonNullType
8141       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8142 }
8143 
8144 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8145                                                ExprResult &RHS,
8146                                                SourceLocation Loc, bool IsDiv) {
8147   // Check for division/remainder by zero.
8148   llvm::APSInt RHSValue;
8149   if (!RHS.get()->isValueDependent() &&
8150       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8151     S.DiagRuntimeBehavior(Loc, RHS.get(),
8152                           S.PDiag(diag::warn_remainder_division_by_zero)
8153                             << IsDiv << RHS.get()->getSourceRange());
8154 }
8155 
8156 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8157                                            SourceLocation Loc,
8158                                            bool IsCompAssign, bool IsDiv) {
8159   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8160 
8161   if (LHS.get()->getType()->isVectorType() ||
8162       RHS.get()->getType()->isVectorType())
8163     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8164                                /*AllowBothBool*/getLangOpts().AltiVec,
8165                                /*AllowBoolConversions*/false);
8166 
8167   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8168   if (LHS.isInvalid() || RHS.isInvalid())
8169     return QualType();
8170 
8171 
8172   if (compType.isNull() || !compType->isArithmeticType())
8173     return InvalidOperands(Loc, LHS, RHS);
8174   if (IsDiv)
8175     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8176   return compType;
8177 }
8178 
8179 QualType Sema::CheckRemainderOperands(
8180   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8181   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8182 
8183   if (LHS.get()->getType()->isVectorType() ||
8184       RHS.get()->getType()->isVectorType()) {
8185     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8186         RHS.get()->getType()->hasIntegerRepresentation())
8187       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8188                                  /*AllowBothBool*/getLangOpts().AltiVec,
8189                                  /*AllowBoolConversions*/false);
8190     return InvalidOperands(Loc, LHS, RHS);
8191   }
8192 
8193   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8194   if (LHS.isInvalid() || RHS.isInvalid())
8195     return QualType();
8196 
8197   if (compType.isNull() || !compType->isIntegerType())
8198     return InvalidOperands(Loc, LHS, RHS);
8199   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8200   return compType;
8201 }
8202 
8203 /// \brief Diagnose invalid arithmetic on two void pointers.
8204 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8205                                                 Expr *LHSExpr, Expr *RHSExpr) {
8206   S.Diag(Loc, S.getLangOpts().CPlusPlus
8207                 ? diag::err_typecheck_pointer_arith_void_type
8208                 : diag::ext_gnu_void_ptr)
8209     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8210                             << RHSExpr->getSourceRange();
8211 }
8212 
8213 /// \brief Diagnose invalid arithmetic on a void pointer.
8214 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8215                                             Expr *Pointer) {
8216   S.Diag(Loc, S.getLangOpts().CPlusPlus
8217                 ? diag::err_typecheck_pointer_arith_void_type
8218                 : diag::ext_gnu_void_ptr)
8219     << 0 /* one pointer */ << Pointer->getSourceRange();
8220 }
8221 
8222 /// \brief Diagnose invalid arithmetic on two function pointers.
8223 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8224                                                     Expr *LHS, Expr *RHS) {
8225   assert(LHS->getType()->isAnyPointerType());
8226   assert(RHS->getType()->isAnyPointerType());
8227   S.Diag(Loc, S.getLangOpts().CPlusPlus
8228                 ? diag::err_typecheck_pointer_arith_function_type
8229                 : diag::ext_gnu_ptr_func_arith)
8230     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8231     // We only show the second type if it differs from the first.
8232     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8233                                                    RHS->getType())
8234     << RHS->getType()->getPointeeType()
8235     << LHS->getSourceRange() << RHS->getSourceRange();
8236 }
8237 
8238 /// \brief Diagnose invalid arithmetic on a function pointer.
8239 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8240                                                 Expr *Pointer) {
8241   assert(Pointer->getType()->isAnyPointerType());
8242   S.Diag(Loc, S.getLangOpts().CPlusPlus
8243                 ? diag::err_typecheck_pointer_arith_function_type
8244                 : diag::ext_gnu_ptr_func_arith)
8245     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8246     << 0 /* one pointer, so only one type */
8247     << Pointer->getSourceRange();
8248 }
8249 
8250 /// \brief Emit error if Operand is incomplete pointer type
8251 ///
8252 /// \returns True if pointer has incomplete type
8253 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8254                                                  Expr *Operand) {
8255   QualType ResType = Operand->getType();
8256   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8257     ResType = ResAtomicType->getValueType();
8258 
8259   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8260   QualType PointeeTy = ResType->getPointeeType();
8261   return S.RequireCompleteType(Loc, PointeeTy,
8262                                diag::err_typecheck_arithmetic_incomplete_type,
8263                                PointeeTy, Operand->getSourceRange());
8264 }
8265 
8266 /// \brief Check the validity of an arithmetic pointer operand.
8267 ///
8268 /// If the operand has pointer type, this code will check for pointer types
8269 /// which are invalid in arithmetic operations. These will be diagnosed
8270 /// appropriately, including whether or not the use is supported as an
8271 /// extension.
8272 ///
8273 /// \returns True when the operand is valid to use (even if as an extension).
8274 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8275                                             Expr *Operand) {
8276   QualType ResType = Operand->getType();
8277   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8278     ResType = ResAtomicType->getValueType();
8279 
8280   if (!ResType->isAnyPointerType()) return true;
8281 
8282   QualType PointeeTy = ResType->getPointeeType();
8283   if (PointeeTy->isVoidType()) {
8284     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8285     return !S.getLangOpts().CPlusPlus;
8286   }
8287   if (PointeeTy->isFunctionType()) {
8288     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8289     return !S.getLangOpts().CPlusPlus;
8290   }
8291 
8292   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8293 
8294   return true;
8295 }
8296 
8297 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8298 /// operands.
8299 ///
8300 /// This routine will diagnose any invalid arithmetic on pointer operands much
8301 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8302 /// for emitting a single diagnostic even for operations where both LHS and RHS
8303 /// are (potentially problematic) pointers.
8304 ///
8305 /// \returns True when the operand is valid to use (even if as an extension).
8306 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8307                                                 Expr *LHSExpr, Expr *RHSExpr) {
8308   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8309   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8310   if (!isLHSPointer && !isRHSPointer) return true;
8311 
8312   QualType LHSPointeeTy, RHSPointeeTy;
8313   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8314   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8315 
8316   // if both are pointers check if operation is valid wrt address spaces
8317   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8318     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8319     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8320     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8321       S.Diag(Loc,
8322              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8323           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8324           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8325       return false;
8326     }
8327   }
8328 
8329   // Check for arithmetic on pointers to incomplete types.
8330   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8331   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8332   if (isLHSVoidPtr || isRHSVoidPtr) {
8333     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8334     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8335     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8336 
8337     return !S.getLangOpts().CPlusPlus;
8338   }
8339 
8340   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8341   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8342   if (isLHSFuncPtr || isRHSFuncPtr) {
8343     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8344     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8345                                                                 RHSExpr);
8346     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8347 
8348     return !S.getLangOpts().CPlusPlus;
8349   }
8350 
8351   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8352     return false;
8353   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8354     return false;
8355 
8356   return true;
8357 }
8358 
8359 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8360 /// literal.
8361 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8362                                   Expr *LHSExpr, Expr *RHSExpr) {
8363   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8364   Expr* IndexExpr = RHSExpr;
8365   if (!StrExpr) {
8366     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8367     IndexExpr = LHSExpr;
8368   }
8369 
8370   bool IsStringPlusInt = StrExpr &&
8371       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8372   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8373     return;
8374 
8375   llvm::APSInt index;
8376   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8377     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8378     if (index.isNonNegative() &&
8379         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8380                               index.isUnsigned()))
8381       return;
8382   }
8383 
8384   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8385   Self.Diag(OpLoc, diag::warn_string_plus_int)
8386       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8387 
8388   // Only print a fixit for "str" + int, not for int + "str".
8389   if (IndexExpr == RHSExpr) {
8390     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8391     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8392         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8393         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8394         << FixItHint::CreateInsertion(EndLoc, "]");
8395   } else
8396     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8397 }
8398 
8399 /// \brief Emit a warning when adding a char literal to a string.
8400 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8401                                    Expr *LHSExpr, Expr *RHSExpr) {
8402   const Expr *StringRefExpr = LHSExpr;
8403   const CharacterLiteral *CharExpr =
8404       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8405 
8406   if (!CharExpr) {
8407     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8408     StringRefExpr = RHSExpr;
8409   }
8410 
8411   if (!CharExpr || !StringRefExpr)
8412     return;
8413 
8414   const QualType StringType = StringRefExpr->getType();
8415 
8416   // Return if not a PointerType.
8417   if (!StringType->isAnyPointerType())
8418     return;
8419 
8420   // Return if not a CharacterType.
8421   if (!StringType->getPointeeType()->isAnyCharacterType())
8422     return;
8423 
8424   ASTContext &Ctx = Self.getASTContext();
8425   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8426 
8427   const QualType CharType = CharExpr->getType();
8428   if (!CharType->isAnyCharacterType() &&
8429       CharType->isIntegerType() &&
8430       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8431     Self.Diag(OpLoc, diag::warn_string_plus_char)
8432         << DiagRange << Ctx.CharTy;
8433   } else {
8434     Self.Diag(OpLoc, diag::warn_string_plus_char)
8435         << DiagRange << CharExpr->getType();
8436   }
8437 
8438   // Only print a fixit for str + char, not for char + str.
8439   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8440     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8441     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8442         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8443         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8444         << FixItHint::CreateInsertion(EndLoc, "]");
8445   } else {
8446     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8447   }
8448 }
8449 
8450 /// \brief Emit error when two pointers are incompatible.
8451 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8452                                            Expr *LHSExpr, Expr *RHSExpr) {
8453   assert(LHSExpr->getType()->isAnyPointerType());
8454   assert(RHSExpr->getType()->isAnyPointerType());
8455   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8456     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8457     << RHSExpr->getSourceRange();
8458 }
8459 
8460 // C99 6.5.6
8461 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8462                                      SourceLocation Loc, BinaryOperatorKind Opc,
8463                                      QualType* CompLHSTy) {
8464   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8465 
8466   if (LHS.get()->getType()->isVectorType() ||
8467       RHS.get()->getType()->isVectorType()) {
8468     QualType compType = CheckVectorOperands(
8469         LHS, RHS, Loc, CompLHSTy,
8470         /*AllowBothBool*/getLangOpts().AltiVec,
8471         /*AllowBoolConversions*/getLangOpts().ZVector);
8472     if (CompLHSTy) *CompLHSTy = compType;
8473     return compType;
8474   }
8475 
8476   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8477   if (LHS.isInvalid() || RHS.isInvalid())
8478     return QualType();
8479 
8480   // Diagnose "string literal" '+' int and string '+' "char literal".
8481   if (Opc == BO_Add) {
8482     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8483     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8484   }
8485 
8486   // handle the common case first (both operands are arithmetic).
8487   if (!compType.isNull() && compType->isArithmeticType()) {
8488     if (CompLHSTy) *CompLHSTy = compType;
8489     return compType;
8490   }
8491 
8492   // Type-checking.  Ultimately the pointer's going to be in PExp;
8493   // note that we bias towards the LHS being the pointer.
8494   Expr *PExp = LHS.get(), *IExp = RHS.get();
8495 
8496   bool isObjCPointer;
8497   if (PExp->getType()->isPointerType()) {
8498     isObjCPointer = false;
8499   } else if (PExp->getType()->isObjCObjectPointerType()) {
8500     isObjCPointer = true;
8501   } else {
8502     std::swap(PExp, IExp);
8503     if (PExp->getType()->isPointerType()) {
8504       isObjCPointer = false;
8505     } else if (PExp->getType()->isObjCObjectPointerType()) {
8506       isObjCPointer = true;
8507     } else {
8508       return InvalidOperands(Loc, LHS, RHS);
8509     }
8510   }
8511   assert(PExp->getType()->isAnyPointerType());
8512 
8513   if (!IExp->getType()->isIntegerType())
8514     return InvalidOperands(Loc, LHS, RHS);
8515 
8516   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8517     return QualType();
8518 
8519   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8520     return QualType();
8521 
8522   // Check array bounds for pointer arithemtic
8523   CheckArrayAccess(PExp, IExp);
8524 
8525   if (CompLHSTy) {
8526     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8527     if (LHSTy.isNull()) {
8528       LHSTy = LHS.get()->getType();
8529       if (LHSTy->isPromotableIntegerType())
8530         LHSTy = Context.getPromotedIntegerType(LHSTy);
8531     }
8532     *CompLHSTy = LHSTy;
8533   }
8534 
8535   return PExp->getType();
8536 }
8537 
8538 // C99 6.5.6
8539 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8540                                         SourceLocation Loc,
8541                                         QualType* CompLHSTy) {
8542   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8543 
8544   if (LHS.get()->getType()->isVectorType() ||
8545       RHS.get()->getType()->isVectorType()) {
8546     QualType compType = CheckVectorOperands(
8547         LHS, RHS, Loc, CompLHSTy,
8548         /*AllowBothBool*/getLangOpts().AltiVec,
8549         /*AllowBoolConversions*/getLangOpts().ZVector);
8550     if (CompLHSTy) *CompLHSTy = compType;
8551     return compType;
8552   }
8553 
8554   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8555   if (LHS.isInvalid() || RHS.isInvalid())
8556     return QualType();
8557 
8558   // Enforce type constraints: C99 6.5.6p3.
8559 
8560   // Handle the common case first (both operands are arithmetic).
8561   if (!compType.isNull() && compType->isArithmeticType()) {
8562     if (CompLHSTy) *CompLHSTy = compType;
8563     return compType;
8564   }
8565 
8566   // Either ptr - int   or   ptr - ptr.
8567   if (LHS.get()->getType()->isAnyPointerType()) {
8568     QualType lpointee = LHS.get()->getType()->getPointeeType();
8569 
8570     // Diagnose bad cases where we step over interface counts.
8571     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8572         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8573       return QualType();
8574 
8575     // The result type of a pointer-int computation is the pointer type.
8576     if (RHS.get()->getType()->isIntegerType()) {
8577       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8578         return QualType();
8579 
8580       // Check array bounds for pointer arithemtic
8581       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8582                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8583 
8584       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8585       return LHS.get()->getType();
8586     }
8587 
8588     // Handle pointer-pointer subtractions.
8589     if (const PointerType *RHSPTy
8590           = RHS.get()->getType()->getAs<PointerType>()) {
8591       QualType rpointee = RHSPTy->getPointeeType();
8592 
8593       if (getLangOpts().CPlusPlus) {
8594         // Pointee types must be the same: C++ [expr.add]
8595         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8596           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8597         }
8598       } else {
8599         // Pointee types must be compatible C99 6.5.6p3
8600         if (!Context.typesAreCompatible(
8601                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8602                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8603           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8604           return QualType();
8605         }
8606       }
8607 
8608       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8609                                                LHS.get(), RHS.get()))
8610         return QualType();
8611 
8612       // The pointee type may have zero size.  As an extension, a structure or
8613       // union may have zero size or an array may have zero length.  In this
8614       // case subtraction does not make sense.
8615       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8616         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8617         if (ElementSize.isZero()) {
8618           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8619             << rpointee.getUnqualifiedType()
8620             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8621         }
8622       }
8623 
8624       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8625       return Context.getPointerDiffType();
8626     }
8627   }
8628 
8629   return InvalidOperands(Loc, LHS, RHS);
8630 }
8631 
8632 static bool isScopedEnumerationType(QualType T) {
8633   if (const EnumType *ET = T->getAs<EnumType>())
8634     return ET->getDecl()->isScoped();
8635   return false;
8636 }
8637 
8638 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8639                                    SourceLocation Loc, BinaryOperatorKind Opc,
8640                                    QualType LHSType) {
8641   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8642   // so skip remaining warnings as we don't want to modify values within Sema.
8643   if (S.getLangOpts().OpenCL)
8644     return;
8645 
8646   llvm::APSInt Right;
8647   // Check right/shifter operand
8648   if (RHS.get()->isValueDependent() ||
8649       !RHS.get()->EvaluateAsInt(Right, S.Context))
8650     return;
8651 
8652   if (Right.isNegative()) {
8653     S.DiagRuntimeBehavior(Loc, RHS.get(),
8654                           S.PDiag(diag::warn_shift_negative)
8655                             << RHS.get()->getSourceRange());
8656     return;
8657   }
8658   llvm::APInt LeftBits(Right.getBitWidth(),
8659                        S.Context.getTypeSize(LHS.get()->getType()));
8660   if (Right.uge(LeftBits)) {
8661     S.DiagRuntimeBehavior(Loc, RHS.get(),
8662                           S.PDiag(diag::warn_shift_gt_typewidth)
8663                             << RHS.get()->getSourceRange());
8664     return;
8665   }
8666   if (Opc != BO_Shl)
8667     return;
8668 
8669   // When left shifting an ICE which is signed, we can check for overflow which
8670   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8671   // integers have defined behavior modulo one more than the maximum value
8672   // representable in the result type, so never warn for those.
8673   llvm::APSInt Left;
8674   if (LHS.get()->isValueDependent() ||
8675       LHSType->hasUnsignedIntegerRepresentation() ||
8676       !LHS.get()->EvaluateAsInt(Left, S.Context))
8677     return;
8678 
8679   // If LHS does not have a signed type and non-negative value
8680   // then, the behavior is undefined. Warn about it.
8681   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8682     S.DiagRuntimeBehavior(Loc, LHS.get(),
8683                           S.PDiag(diag::warn_shift_lhs_negative)
8684                             << LHS.get()->getSourceRange());
8685     return;
8686   }
8687 
8688   llvm::APInt ResultBits =
8689       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8690   if (LeftBits.uge(ResultBits))
8691     return;
8692   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8693   Result = Result.shl(Right);
8694 
8695   // Print the bit representation of the signed integer as an unsigned
8696   // hexadecimal number.
8697   SmallString<40> HexResult;
8698   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8699 
8700   // If we are only missing a sign bit, this is less likely to result in actual
8701   // bugs -- if the result is cast back to an unsigned type, it will have the
8702   // expected value. Thus we place this behind a different warning that can be
8703   // turned off separately if needed.
8704   if (LeftBits == ResultBits - 1) {
8705     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8706         << HexResult << LHSType
8707         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8708     return;
8709   }
8710 
8711   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8712     << HexResult.str() << Result.getMinSignedBits() << LHSType
8713     << Left.getBitWidth() << LHS.get()->getSourceRange()
8714     << RHS.get()->getSourceRange();
8715 }
8716 
8717 /// \brief Return the resulting type when a vector is shifted
8718 ///        by a scalar or vector shift amount.
8719 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8720                                  SourceLocation Loc, bool IsCompAssign) {
8721   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8722   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8723       !LHS.get()->getType()->isVectorType()) {
8724     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8725       << RHS.get()->getType() << LHS.get()->getType()
8726       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8727     return QualType();
8728   }
8729 
8730   if (!IsCompAssign) {
8731     LHS = S.UsualUnaryConversions(LHS.get());
8732     if (LHS.isInvalid()) return QualType();
8733   }
8734 
8735   RHS = S.UsualUnaryConversions(RHS.get());
8736   if (RHS.isInvalid()) return QualType();
8737 
8738   QualType LHSType = LHS.get()->getType();
8739   // Note that LHS might be a scalar because the routine calls not only in
8740   // OpenCL case.
8741   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8742   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8743 
8744   // Note that RHS might not be a vector.
8745   QualType RHSType = RHS.get()->getType();
8746   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8747   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8748 
8749   // The operands need to be integers.
8750   if (!LHSEleType->isIntegerType()) {
8751     S.Diag(Loc, diag::err_typecheck_expect_int)
8752       << LHS.get()->getType() << LHS.get()->getSourceRange();
8753     return QualType();
8754   }
8755 
8756   if (!RHSEleType->isIntegerType()) {
8757     S.Diag(Loc, diag::err_typecheck_expect_int)
8758       << RHS.get()->getType() << RHS.get()->getSourceRange();
8759     return QualType();
8760   }
8761 
8762   if (!LHSVecTy) {
8763     assert(RHSVecTy);
8764     if (IsCompAssign)
8765       return RHSType;
8766     if (LHSEleType != RHSEleType) {
8767       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8768       LHSEleType = RHSEleType;
8769     }
8770     QualType VecTy =
8771         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8772     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8773     LHSType = VecTy;
8774   } else if (RHSVecTy) {
8775     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8776     // are applied component-wise. So if RHS is a vector, then ensure
8777     // that the number of elements is the same as LHS...
8778     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8779       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8780         << LHS.get()->getType() << RHS.get()->getType()
8781         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8782       return QualType();
8783     }
8784   } else {
8785     // ...else expand RHS to match the number of elements in LHS.
8786     QualType VecTy =
8787       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8788     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8789   }
8790 
8791   return LHSType;
8792 }
8793 
8794 // C99 6.5.7
8795 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8796                                   SourceLocation Loc, BinaryOperatorKind Opc,
8797                                   bool IsCompAssign) {
8798   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8799 
8800   // Vector shifts promote their scalar inputs to vector type.
8801   if (LHS.get()->getType()->isVectorType() ||
8802       RHS.get()->getType()->isVectorType()) {
8803     if (LangOpts.ZVector) {
8804       // The shift operators for the z vector extensions work basically
8805       // like general shifts, except that neither the LHS nor the RHS is
8806       // allowed to be a "vector bool".
8807       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8808         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8809           return InvalidOperands(Loc, LHS, RHS);
8810       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8811         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8812           return InvalidOperands(Loc, LHS, RHS);
8813     }
8814     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8815   }
8816 
8817   // Shifts don't perform usual arithmetic conversions, they just do integer
8818   // promotions on each operand. C99 6.5.7p3
8819 
8820   // For the LHS, do usual unary conversions, but then reset them away
8821   // if this is a compound assignment.
8822   ExprResult OldLHS = LHS;
8823   LHS = UsualUnaryConversions(LHS.get());
8824   if (LHS.isInvalid())
8825     return QualType();
8826   QualType LHSType = LHS.get()->getType();
8827   if (IsCompAssign) LHS = OldLHS;
8828 
8829   // The RHS is simpler.
8830   RHS = UsualUnaryConversions(RHS.get());
8831   if (RHS.isInvalid())
8832     return QualType();
8833   QualType RHSType = RHS.get()->getType();
8834 
8835   // C99 6.5.7p2: Each of the operands shall have integer type.
8836   if (!LHSType->hasIntegerRepresentation() ||
8837       !RHSType->hasIntegerRepresentation())
8838     return InvalidOperands(Loc, LHS, RHS);
8839 
8840   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8841   // hasIntegerRepresentation() above instead of this.
8842   if (isScopedEnumerationType(LHSType) ||
8843       isScopedEnumerationType(RHSType)) {
8844     return InvalidOperands(Loc, LHS, RHS);
8845   }
8846   // Sanity-check shift operands
8847   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8848 
8849   // "The type of the result is that of the promoted left operand."
8850   return LHSType;
8851 }
8852 
8853 static bool IsWithinTemplateSpecialization(Decl *D) {
8854   if (DeclContext *DC = D->getDeclContext()) {
8855     if (isa<ClassTemplateSpecializationDecl>(DC))
8856       return true;
8857     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8858       return FD->isFunctionTemplateSpecialization();
8859   }
8860   return false;
8861 }
8862 
8863 /// If two different enums are compared, raise a warning.
8864 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8865                                 Expr *RHS) {
8866   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8867   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8868 
8869   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8870   if (!LHSEnumType)
8871     return;
8872   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8873   if (!RHSEnumType)
8874     return;
8875 
8876   // Ignore anonymous enums.
8877   if (!LHSEnumType->getDecl()->getIdentifier())
8878     return;
8879   if (!RHSEnumType->getDecl()->getIdentifier())
8880     return;
8881 
8882   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8883     return;
8884 
8885   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8886       << LHSStrippedType << RHSStrippedType
8887       << LHS->getSourceRange() << RHS->getSourceRange();
8888 }
8889 
8890 /// \brief Diagnose bad pointer comparisons.
8891 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8892                                               ExprResult &LHS, ExprResult &RHS,
8893                                               bool IsError) {
8894   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8895                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8896     << LHS.get()->getType() << RHS.get()->getType()
8897     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8898 }
8899 
8900 /// \brief Returns false if the pointers are converted to a composite type,
8901 /// true otherwise.
8902 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8903                                            ExprResult &LHS, ExprResult &RHS) {
8904   // C++ [expr.rel]p2:
8905   //   [...] Pointer conversions (4.10) and qualification
8906   //   conversions (4.4) are performed on pointer operands (or on
8907   //   a pointer operand and a null pointer constant) to bring
8908   //   them to their composite pointer type. [...]
8909   //
8910   // C++ [expr.eq]p1 uses the same notion for (in)equality
8911   // comparisons of pointers.
8912 
8913   // C++ [expr.eq]p2:
8914   //   In addition, pointers to members can be compared, or a pointer to
8915   //   member and a null pointer constant. Pointer to member conversions
8916   //   (4.11) and qualification conversions (4.4) are performed to bring
8917   //   them to a common type. If one operand is a null pointer constant,
8918   //   the common type is the type of the other operand. Otherwise, the
8919   //   common type is a pointer to member type similar (4.4) to the type
8920   //   of one of the operands, with a cv-qualification signature (4.4)
8921   //   that is the union of the cv-qualification signatures of the operand
8922   //   types.
8923 
8924   QualType LHSType = LHS.get()->getType();
8925   QualType RHSType = RHS.get()->getType();
8926   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8927          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8928 
8929   bool NonStandardCompositeType = false;
8930   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8931   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8932   if (T.isNull()) {
8933     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8934     return true;
8935   }
8936 
8937   if (NonStandardCompositeType)
8938     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8939       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8940       << RHS.get()->getSourceRange();
8941 
8942   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8943   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8944   return false;
8945 }
8946 
8947 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8948                                                     ExprResult &LHS,
8949                                                     ExprResult &RHS,
8950                                                     bool IsError) {
8951   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8952                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8953     << LHS.get()->getType() << RHS.get()->getType()
8954     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8955 }
8956 
8957 static bool isObjCObjectLiteral(ExprResult &E) {
8958   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8959   case Stmt::ObjCArrayLiteralClass:
8960   case Stmt::ObjCDictionaryLiteralClass:
8961   case Stmt::ObjCStringLiteralClass:
8962   case Stmt::ObjCBoxedExprClass:
8963     return true;
8964   default:
8965     // Note that ObjCBoolLiteral is NOT an object literal!
8966     return false;
8967   }
8968 }
8969 
8970 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8971   const ObjCObjectPointerType *Type =
8972     LHS->getType()->getAs<ObjCObjectPointerType>();
8973 
8974   // If this is not actually an Objective-C object, bail out.
8975   if (!Type)
8976     return false;
8977 
8978   // Get the LHS object's interface type.
8979   QualType InterfaceType = Type->getPointeeType();
8980 
8981   // If the RHS isn't an Objective-C object, bail out.
8982   if (!RHS->getType()->isObjCObjectPointerType())
8983     return false;
8984 
8985   // Try to find the -isEqual: method.
8986   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8987   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8988                                                       InterfaceType,
8989                                                       /*instance=*/true);
8990   if (!Method) {
8991     if (Type->isObjCIdType()) {
8992       // For 'id', just check the global pool.
8993       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8994                                                   /*receiverId=*/true);
8995     } else {
8996       // Check protocols.
8997       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8998                                              /*instance=*/true);
8999     }
9000   }
9001 
9002   if (!Method)
9003     return false;
9004 
9005   QualType T = Method->parameters()[0]->getType();
9006   if (!T->isObjCObjectPointerType())
9007     return false;
9008 
9009   QualType R = Method->getReturnType();
9010   if (!R->isScalarType())
9011     return false;
9012 
9013   return true;
9014 }
9015 
9016 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9017   FromE = FromE->IgnoreParenImpCasts();
9018   switch (FromE->getStmtClass()) {
9019     default:
9020       break;
9021     case Stmt::ObjCStringLiteralClass:
9022       // "string literal"
9023       return LK_String;
9024     case Stmt::ObjCArrayLiteralClass:
9025       // "array literal"
9026       return LK_Array;
9027     case Stmt::ObjCDictionaryLiteralClass:
9028       // "dictionary literal"
9029       return LK_Dictionary;
9030     case Stmt::BlockExprClass:
9031       return LK_Block;
9032     case Stmt::ObjCBoxedExprClass: {
9033       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9034       switch (Inner->getStmtClass()) {
9035         case Stmt::IntegerLiteralClass:
9036         case Stmt::FloatingLiteralClass:
9037         case Stmt::CharacterLiteralClass:
9038         case Stmt::ObjCBoolLiteralExprClass:
9039         case Stmt::CXXBoolLiteralExprClass:
9040           // "numeric literal"
9041           return LK_Numeric;
9042         case Stmt::ImplicitCastExprClass: {
9043           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9044           // Boolean literals can be represented by implicit casts.
9045           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9046             return LK_Numeric;
9047           break;
9048         }
9049         default:
9050           break;
9051       }
9052       return LK_Boxed;
9053     }
9054   }
9055   return LK_None;
9056 }
9057 
9058 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9059                                           ExprResult &LHS, ExprResult &RHS,
9060                                           BinaryOperator::Opcode Opc){
9061   Expr *Literal;
9062   Expr *Other;
9063   if (isObjCObjectLiteral(LHS)) {
9064     Literal = LHS.get();
9065     Other = RHS.get();
9066   } else {
9067     Literal = RHS.get();
9068     Other = LHS.get();
9069   }
9070 
9071   // Don't warn on comparisons against nil.
9072   Other = Other->IgnoreParenCasts();
9073   if (Other->isNullPointerConstant(S.getASTContext(),
9074                                    Expr::NPC_ValueDependentIsNotNull))
9075     return;
9076 
9077   // This should be kept in sync with warn_objc_literal_comparison.
9078   // LK_String should always be after the other literals, since it has its own
9079   // warning flag.
9080   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9081   assert(LiteralKind != Sema::LK_Block);
9082   if (LiteralKind == Sema::LK_None) {
9083     llvm_unreachable("Unknown Objective-C object literal kind");
9084   }
9085 
9086   if (LiteralKind == Sema::LK_String)
9087     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9088       << Literal->getSourceRange();
9089   else
9090     S.Diag(Loc, diag::warn_objc_literal_comparison)
9091       << LiteralKind << Literal->getSourceRange();
9092 
9093   if (BinaryOperator::isEqualityOp(Opc) &&
9094       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9095     SourceLocation Start = LHS.get()->getLocStart();
9096     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9097     CharSourceRange OpRange =
9098       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9099 
9100     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9101       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9102       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9103       << FixItHint::CreateInsertion(End, "]");
9104   }
9105 }
9106 
9107 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
9108                                                 ExprResult &RHS,
9109                                                 SourceLocation Loc,
9110                                                 BinaryOperatorKind Opc) {
9111   // Check that left hand side is !something.
9112   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9113   if (!UO || UO->getOpcode() != UO_LNot) return;
9114 
9115   // Only check if the right hand side is non-bool arithmetic type.
9116   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9117 
9118   // Make sure that the something in !something is not bool.
9119   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9120   if (SubExpr->isKnownToHaveBooleanValue()) return;
9121 
9122   // Emit warning.
9123   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
9124       << Loc;
9125 
9126   // First note suggest !(x < y)
9127   SourceLocation FirstOpen = SubExpr->getLocStart();
9128   SourceLocation FirstClose = RHS.get()->getLocEnd();
9129   FirstClose = S.getLocForEndOfToken(FirstClose);
9130   if (FirstClose.isInvalid())
9131     FirstOpen = SourceLocation();
9132   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9133       << FixItHint::CreateInsertion(FirstOpen, "(")
9134       << FixItHint::CreateInsertion(FirstClose, ")");
9135 
9136   // Second note suggests (!x) < y
9137   SourceLocation SecondOpen = LHS.get()->getLocStart();
9138   SourceLocation SecondClose = LHS.get()->getLocEnd();
9139   SecondClose = S.getLocForEndOfToken(SecondClose);
9140   if (SecondClose.isInvalid())
9141     SecondOpen = SourceLocation();
9142   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9143       << FixItHint::CreateInsertion(SecondOpen, "(")
9144       << FixItHint::CreateInsertion(SecondClose, ")");
9145 }
9146 
9147 // Get the decl for a simple expression: a reference to a variable,
9148 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9149 static ValueDecl *getCompareDecl(Expr *E) {
9150   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9151     return DR->getDecl();
9152   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9153     if (Ivar->isFreeIvar())
9154       return Ivar->getDecl();
9155   }
9156   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9157     if (Mem->isImplicitAccess())
9158       return Mem->getMemberDecl();
9159   }
9160   return nullptr;
9161 }
9162 
9163 // C99 6.5.8, C++ [expr.rel]
9164 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9165                                     SourceLocation Loc, BinaryOperatorKind Opc,
9166                                     bool IsRelational) {
9167   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9168 
9169   // Handle vector comparisons separately.
9170   if (LHS.get()->getType()->isVectorType() ||
9171       RHS.get()->getType()->isVectorType())
9172     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9173 
9174   QualType LHSType = LHS.get()->getType();
9175   QualType RHSType = RHS.get()->getType();
9176 
9177   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9178   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9179 
9180   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9181   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9182 
9183   if (!LHSType->hasFloatingRepresentation() &&
9184       !(LHSType->isBlockPointerType() && IsRelational) &&
9185       !LHS.get()->getLocStart().isMacroID() &&
9186       !RHS.get()->getLocStart().isMacroID() &&
9187       ActiveTemplateInstantiations.empty()) {
9188     // For non-floating point types, check for self-comparisons of the form
9189     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9190     // often indicate logic errors in the program.
9191     //
9192     // NOTE: Don't warn about comparison expressions resulting from macro
9193     // expansion. Also don't warn about comparisons which are only self
9194     // comparisons within a template specialization. The warnings should catch
9195     // obvious cases in the definition of the template anyways. The idea is to
9196     // warn when the typed comparison operator will always evaluate to the same
9197     // result.
9198     ValueDecl *DL = getCompareDecl(LHSStripped);
9199     ValueDecl *DR = getCompareDecl(RHSStripped);
9200     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9201       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9202                           << 0 // self-
9203                           << (Opc == BO_EQ
9204                               || Opc == BO_LE
9205                               || Opc == BO_GE));
9206     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9207                !DL->getType()->isReferenceType() &&
9208                !DR->getType()->isReferenceType()) {
9209         // what is it always going to eval to?
9210         char always_evals_to;
9211         switch(Opc) {
9212         case BO_EQ: // e.g. array1 == array2
9213           always_evals_to = 0; // false
9214           break;
9215         case BO_NE: // e.g. array1 != array2
9216           always_evals_to = 1; // true
9217           break;
9218         default:
9219           // best we can say is 'a constant'
9220           always_evals_to = 2; // e.g. array1 <= array2
9221           break;
9222         }
9223         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9224                             << 1 // array
9225                             << always_evals_to);
9226     }
9227 
9228     if (isa<CastExpr>(LHSStripped))
9229       LHSStripped = LHSStripped->IgnoreParenCasts();
9230     if (isa<CastExpr>(RHSStripped))
9231       RHSStripped = RHSStripped->IgnoreParenCasts();
9232 
9233     // Warn about comparisons against a string constant (unless the other
9234     // operand is null), the user probably wants strcmp.
9235     Expr *literalString = nullptr;
9236     Expr *literalStringStripped = nullptr;
9237     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9238         !RHSStripped->isNullPointerConstant(Context,
9239                                             Expr::NPC_ValueDependentIsNull)) {
9240       literalString = LHS.get();
9241       literalStringStripped = LHSStripped;
9242     } else if ((isa<StringLiteral>(RHSStripped) ||
9243                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9244                !LHSStripped->isNullPointerConstant(Context,
9245                                             Expr::NPC_ValueDependentIsNull)) {
9246       literalString = RHS.get();
9247       literalStringStripped = RHSStripped;
9248     }
9249 
9250     if (literalString) {
9251       DiagRuntimeBehavior(Loc, nullptr,
9252         PDiag(diag::warn_stringcompare)
9253           << isa<ObjCEncodeExpr>(literalStringStripped)
9254           << literalString->getSourceRange());
9255     }
9256   }
9257 
9258   // C99 6.5.8p3 / C99 6.5.9p4
9259   UsualArithmeticConversions(LHS, RHS);
9260   if (LHS.isInvalid() || RHS.isInvalid())
9261     return QualType();
9262 
9263   LHSType = LHS.get()->getType();
9264   RHSType = RHS.get()->getType();
9265 
9266   // The result of comparisons is 'bool' in C++, 'int' in C.
9267   QualType ResultTy = Context.getLogicalOperationType();
9268 
9269   if (IsRelational) {
9270     if (LHSType->isRealType() && RHSType->isRealType())
9271       return ResultTy;
9272   } else {
9273     // Check for comparisons of floating point operands using != and ==.
9274     if (LHSType->hasFloatingRepresentation())
9275       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9276 
9277     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9278       return ResultTy;
9279   }
9280 
9281   const Expr::NullPointerConstantKind LHSNullKind =
9282       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9283   const Expr::NullPointerConstantKind RHSNullKind =
9284       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9285   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9286   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9287 
9288   if (!IsRelational && LHSIsNull != RHSIsNull) {
9289     bool IsEquality = Opc == BO_EQ;
9290     if (RHSIsNull)
9291       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9292                                    RHS.get()->getSourceRange());
9293     else
9294       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9295                                    LHS.get()->getSourceRange());
9296   }
9297 
9298   // All of the following pointer-related warnings are GCC extensions, except
9299   // when handling null pointer constants.
9300   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9301     QualType LCanPointeeTy =
9302       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9303     QualType RCanPointeeTy =
9304       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9305 
9306     if (getLangOpts().CPlusPlus) {
9307       if (LCanPointeeTy == RCanPointeeTy)
9308         return ResultTy;
9309       if (!IsRelational &&
9310           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9311         // Valid unless comparison between non-null pointer and function pointer
9312         // This is a gcc extension compatibility comparison.
9313         // In a SFINAE context, we treat this as a hard error to maintain
9314         // conformance with the C++ standard.
9315         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9316             && !LHSIsNull && !RHSIsNull) {
9317           diagnoseFunctionPointerToVoidComparison(
9318               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9319 
9320           if (isSFINAEContext())
9321             return QualType();
9322 
9323           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9324           return ResultTy;
9325         }
9326       }
9327 
9328       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9329         return QualType();
9330       else
9331         return ResultTy;
9332     }
9333     // C99 6.5.9p2 and C99 6.5.8p2
9334     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9335                                    RCanPointeeTy.getUnqualifiedType())) {
9336       // Valid unless a relational comparison of function pointers
9337       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9338         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9339           << LHSType << RHSType << LHS.get()->getSourceRange()
9340           << RHS.get()->getSourceRange();
9341       }
9342     } else if (!IsRelational &&
9343                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9344       // Valid unless comparison between non-null pointer and function pointer
9345       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9346           && !LHSIsNull && !RHSIsNull)
9347         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9348                                                 /*isError*/false);
9349     } else {
9350       // Invalid
9351       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9352     }
9353     if (LCanPointeeTy != RCanPointeeTy) {
9354       // Treat NULL constant as a special case in OpenCL.
9355       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9356         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9357         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9358           Diag(Loc,
9359                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9360               << LHSType << RHSType << 0 /* comparison */
9361               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9362         }
9363       }
9364       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9365       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9366       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9367                                                : CK_BitCast;
9368       if (LHSIsNull && !RHSIsNull)
9369         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9370       else
9371         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9372     }
9373     return ResultTy;
9374   }
9375 
9376   if (getLangOpts().CPlusPlus) {
9377     // Comparison of nullptr_t with itself.
9378     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9379       return ResultTy;
9380 
9381     // Comparison of pointers with null pointer constants and equality
9382     // comparisons of member pointers to null pointer constants.
9383     if (RHSIsNull &&
9384         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9385          (!IsRelational &&
9386           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9387       RHS = ImpCastExprToType(RHS.get(), LHSType,
9388                         LHSType->isMemberPointerType()
9389                           ? CK_NullToMemberPointer
9390                           : CK_NullToPointer);
9391       return ResultTy;
9392     }
9393     if (LHSIsNull &&
9394         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9395          (!IsRelational &&
9396           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9397       LHS = ImpCastExprToType(LHS.get(), RHSType,
9398                         RHSType->isMemberPointerType()
9399                           ? CK_NullToMemberPointer
9400                           : CK_NullToPointer);
9401       return ResultTy;
9402     }
9403 
9404     // Comparison of member pointers.
9405     if (!IsRelational &&
9406         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9407       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9408         return QualType();
9409       else
9410         return ResultTy;
9411     }
9412 
9413     // Handle scoped enumeration types specifically, since they don't promote
9414     // to integers.
9415     if (LHS.get()->getType()->isEnumeralType() &&
9416         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9417                                        RHS.get()->getType()))
9418       return ResultTy;
9419   }
9420 
9421   // Handle block pointer types.
9422   if (!IsRelational && LHSType->isBlockPointerType() &&
9423       RHSType->isBlockPointerType()) {
9424     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9425     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9426 
9427     if (!LHSIsNull && !RHSIsNull &&
9428         !Context.typesAreCompatible(lpointee, rpointee)) {
9429       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9430         << LHSType << RHSType << LHS.get()->getSourceRange()
9431         << RHS.get()->getSourceRange();
9432     }
9433     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9434     return ResultTy;
9435   }
9436 
9437   // Allow block pointers to be compared with null pointer constants.
9438   if (!IsRelational
9439       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9440           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9441     if (!LHSIsNull && !RHSIsNull) {
9442       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9443              ->getPointeeType()->isVoidType())
9444             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9445                 ->getPointeeType()->isVoidType())))
9446         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9447           << LHSType << RHSType << LHS.get()->getSourceRange()
9448           << RHS.get()->getSourceRange();
9449     }
9450     if (LHSIsNull && !RHSIsNull)
9451       LHS = ImpCastExprToType(LHS.get(), RHSType,
9452                               RHSType->isPointerType() ? CK_BitCast
9453                                 : CK_AnyPointerToBlockPointerCast);
9454     else
9455       RHS = ImpCastExprToType(RHS.get(), LHSType,
9456                               LHSType->isPointerType() ? CK_BitCast
9457                                 : CK_AnyPointerToBlockPointerCast);
9458     return ResultTy;
9459   }
9460 
9461   if (LHSType->isObjCObjectPointerType() ||
9462       RHSType->isObjCObjectPointerType()) {
9463     const PointerType *LPT = LHSType->getAs<PointerType>();
9464     const PointerType *RPT = RHSType->getAs<PointerType>();
9465     if (LPT || RPT) {
9466       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9467       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9468 
9469       if (!LPtrToVoid && !RPtrToVoid &&
9470           !Context.typesAreCompatible(LHSType, RHSType)) {
9471         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9472                                           /*isError*/false);
9473       }
9474       if (LHSIsNull && !RHSIsNull) {
9475         Expr *E = LHS.get();
9476         if (getLangOpts().ObjCAutoRefCount)
9477           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9478         LHS = ImpCastExprToType(E, RHSType,
9479                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9480       }
9481       else {
9482         Expr *E = RHS.get();
9483         if (getLangOpts().ObjCAutoRefCount)
9484           CheckObjCARCConversion(SourceRange(), LHSType, E,
9485                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9486                                  /*DiagnoseCFAudited=*/false, Opc);
9487         RHS = ImpCastExprToType(E, LHSType,
9488                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9489       }
9490       return ResultTy;
9491     }
9492     if (LHSType->isObjCObjectPointerType() &&
9493         RHSType->isObjCObjectPointerType()) {
9494       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9495         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9496                                           /*isError*/false);
9497       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9498         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9499 
9500       if (LHSIsNull && !RHSIsNull)
9501         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9502       else
9503         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9504       return ResultTy;
9505     }
9506   }
9507   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9508       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9509     unsigned DiagID = 0;
9510     bool isError = false;
9511     if (LangOpts.DebuggerSupport) {
9512       // Under a debugger, allow the comparison of pointers to integers,
9513       // since users tend to want to compare addresses.
9514     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9515         (RHSIsNull && RHSType->isIntegerType())) {
9516       if (IsRelational && !getLangOpts().CPlusPlus)
9517         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9518     } else if (IsRelational && !getLangOpts().CPlusPlus)
9519       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9520     else if (getLangOpts().CPlusPlus) {
9521       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9522       isError = true;
9523     } else
9524       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9525 
9526     if (DiagID) {
9527       Diag(Loc, DiagID)
9528         << LHSType << RHSType << LHS.get()->getSourceRange()
9529         << RHS.get()->getSourceRange();
9530       if (isError)
9531         return QualType();
9532     }
9533 
9534     if (LHSType->isIntegerType())
9535       LHS = ImpCastExprToType(LHS.get(), RHSType,
9536                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9537     else
9538       RHS = ImpCastExprToType(RHS.get(), LHSType,
9539                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9540     return ResultTy;
9541   }
9542 
9543   // Handle block pointers.
9544   if (!IsRelational && RHSIsNull
9545       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9546     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9547     return ResultTy;
9548   }
9549   if (!IsRelational && LHSIsNull
9550       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9551     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9552     return ResultTy;
9553   }
9554 
9555   return InvalidOperands(Loc, LHS, RHS);
9556 }
9557 
9558 
9559 // Return a signed type that is of identical size and number of elements.
9560 // For floating point vectors, return an integer type of identical size
9561 // and number of elements.
9562 QualType Sema::GetSignedVectorType(QualType V) {
9563   const VectorType *VTy = V->getAs<VectorType>();
9564   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9565   if (TypeSize == Context.getTypeSize(Context.CharTy))
9566     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9567   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9568     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9569   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9570     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9571   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9572     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9573   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9574          "Unhandled vector element size in vector compare");
9575   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9576 }
9577 
9578 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9579 /// operates on extended vector types.  Instead of producing an IntTy result,
9580 /// like a scalar comparison, a vector comparison produces a vector of integer
9581 /// types.
9582 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9583                                           SourceLocation Loc,
9584                                           bool IsRelational) {
9585   // Check to make sure we're operating on vectors of the same type and width,
9586   // Allowing one side to be a scalar of element type.
9587   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9588                               /*AllowBothBool*/true,
9589                               /*AllowBoolConversions*/getLangOpts().ZVector);
9590   if (vType.isNull())
9591     return vType;
9592 
9593   QualType LHSType = LHS.get()->getType();
9594 
9595   // If AltiVec, the comparison results in a numeric type, i.e.
9596   // bool for C++, int for C
9597   if (getLangOpts().AltiVec &&
9598       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9599     return Context.getLogicalOperationType();
9600 
9601   // For non-floating point types, check for self-comparisons of the form
9602   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9603   // often indicate logic errors in the program.
9604   if (!LHSType->hasFloatingRepresentation() &&
9605       ActiveTemplateInstantiations.empty()) {
9606     if (DeclRefExpr* DRL
9607           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9608       if (DeclRefExpr* DRR
9609             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9610         if (DRL->getDecl() == DRR->getDecl())
9611           DiagRuntimeBehavior(Loc, nullptr,
9612                               PDiag(diag::warn_comparison_always)
9613                                 << 0 // self-
9614                                 << 2 // "a constant"
9615                               );
9616   }
9617 
9618   // Check for comparisons of floating point operands using != and ==.
9619   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9620     assert (RHS.get()->getType()->hasFloatingRepresentation());
9621     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9622   }
9623 
9624   // Return a signed type for the vector.
9625   return GetSignedVectorType(vType);
9626 }
9627 
9628 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9629                                           SourceLocation Loc) {
9630   // Ensure that either both operands are of the same vector type, or
9631   // one operand is of a vector type and the other is of its element type.
9632   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9633                                        /*AllowBothBool*/true,
9634                                        /*AllowBoolConversions*/false);
9635   if (vType.isNull())
9636     return InvalidOperands(Loc, LHS, RHS);
9637   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9638       vType->hasFloatingRepresentation())
9639     return InvalidOperands(Loc, LHS, RHS);
9640 
9641   return GetSignedVectorType(LHS.get()->getType());
9642 }
9643 
9644 inline QualType Sema::CheckBitwiseOperands(
9645   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9646   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9647 
9648   if (LHS.get()->getType()->isVectorType() ||
9649       RHS.get()->getType()->isVectorType()) {
9650     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9651         RHS.get()->getType()->hasIntegerRepresentation())
9652       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9653                         /*AllowBothBool*/true,
9654                         /*AllowBoolConversions*/getLangOpts().ZVector);
9655     return InvalidOperands(Loc, LHS, RHS);
9656   }
9657 
9658   ExprResult LHSResult = LHS, RHSResult = RHS;
9659   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9660                                                  IsCompAssign);
9661   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9662     return QualType();
9663   LHS = LHSResult.get();
9664   RHS = RHSResult.get();
9665 
9666   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9667     return compType;
9668   return InvalidOperands(Loc, LHS, RHS);
9669 }
9670 
9671 // C99 6.5.[13,14]
9672 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9673                                            SourceLocation Loc,
9674                                            BinaryOperatorKind Opc) {
9675   // Check vector operands differently.
9676   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9677     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9678 
9679   // Diagnose cases where the user write a logical and/or but probably meant a
9680   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9681   // is a constant.
9682   if (LHS.get()->getType()->isIntegerType() &&
9683       !LHS.get()->getType()->isBooleanType() &&
9684       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9685       // Don't warn in macros or template instantiations.
9686       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9687     // If the RHS can be constant folded, and if it constant folds to something
9688     // that isn't 0 or 1 (which indicate a potential logical operation that
9689     // happened to fold to true/false) then warn.
9690     // Parens on the RHS are ignored.
9691     llvm::APSInt Result;
9692     if (RHS.get()->EvaluateAsInt(Result, Context))
9693       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9694            !RHS.get()->getExprLoc().isMacroID()) ||
9695           (Result != 0 && Result != 1)) {
9696         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9697           << RHS.get()->getSourceRange()
9698           << (Opc == BO_LAnd ? "&&" : "||");
9699         // Suggest replacing the logical operator with the bitwise version
9700         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9701             << (Opc == BO_LAnd ? "&" : "|")
9702             << FixItHint::CreateReplacement(SourceRange(
9703                                                  Loc, getLocForEndOfToken(Loc)),
9704                                             Opc == BO_LAnd ? "&" : "|");
9705         if (Opc == BO_LAnd)
9706           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9707           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9708               << FixItHint::CreateRemoval(
9709                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9710                               RHS.get()->getLocEnd()));
9711       }
9712   }
9713 
9714   if (!Context.getLangOpts().CPlusPlus) {
9715     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9716     // not operate on the built-in scalar and vector float types.
9717     if (Context.getLangOpts().OpenCL &&
9718         Context.getLangOpts().OpenCLVersion < 120) {
9719       if (LHS.get()->getType()->isFloatingType() ||
9720           RHS.get()->getType()->isFloatingType())
9721         return InvalidOperands(Loc, LHS, RHS);
9722     }
9723 
9724     LHS = UsualUnaryConversions(LHS.get());
9725     if (LHS.isInvalid())
9726       return QualType();
9727 
9728     RHS = UsualUnaryConversions(RHS.get());
9729     if (RHS.isInvalid())
9730       return QualType();
9731 
9732     if (!LHS.get()->getType()->isScalarType() ||
9733         !RHS.get()->getType()->isScalarType())
9734       return InvalidOperands(Loc, LHS, RHS);
9735 
9736     return Context.IntTy;
9737   }
9738 
9739   // The following is safe because we only use this method for
9740   // non-overloadable operands.
9741 
9742   // C++ [expr.log.and]p1
9743   // C++ [expr.log.or]p1
9744   // The operands are both contextually converted to type bool.
9745   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9746   if (LHSRes.isInvalid())
9747     return InvalidOperands(Loc, LHS, RHS);
9748   LHS = LHSRes;
9749 
9750   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9751   if (RHSRes.isInvalid())
9752     return InvalidOperands(Loc, LHS, RHS);
9753   RHS = RHSRes;
9754 
9755   // C++ [expr.log.and]p2
9756   // C++ [expr.log.or]p2
9757   // The result is a bool.
9758   return Context.BoolTy;
9759 }
9760 
9761 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9762   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9763   if (!ME) return false;
9764   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9765   ObjCMessageExpr *Base =
9766     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9767   if (!Base) return false;
9768   return Base->getMethodDecl() != nullptr;
9769 }
9770 
9771 /// Is the given expression (which must be 'const') a reference to a
9772 /// variable which was originally non-const, but which has become
9773 /// 'const' due to being captured within a block?
9774 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9775 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9776   assert(E->isLValue() && E->getType().isConstQualified());
9777   E = E->IgnoreParens();
9778 
9779   // Must be a reference to a declaration from an enclosing scope.
9780   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9781   if (!DRE) return NCCK_None;
9782   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9783 
9784   // The declaration must be a variable which is not declared 'const'.
9785   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9786   if (!var) return NCCK_None;
9787   if (var->getType().isConstQualified()) return NCCK_None;
9788   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9789 
9790   // Decide whether the first capture was for a block or a lambda.
9791   DeclContext *DC = S.CurContext, *Prev = nullptr;
9792   // Decide whether the first capture was for a block or a lambda.
9793   while (DC) {
9794     // For init-capture, it is possible that the variable belongs to the
9795     // template pattern of the current context.
9796     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9797       if (var->isInitCapture() &&
9798           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9799         break;
9800     if (DC == var->getDeclContext())
9801       break;
9802     Prev = DC;
9803     DC = DC->getParent();
9804   }
9805   // Unless we have an init-capture, we've gone one step too far.
9806   if (!var->isInitCapture())
9807     DC = Prev;
9808   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9809 }
9810 
9811 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9812   Ty = Ty.getNonReferenceType();
9813   if (IsDereference && Ty->isPointerType())
9814     Ty = Ty->getPointeeType();
9815   return !Ty.isConstQualified();
9816 }
9817 
9818 /// Emit the "read-only variable not assignable" error and print notes to give
9819 /// more information about why the variable is not assignable, such as pointing
9820 /// to the declaration of a const variable, showing that a method is const, or
9821 /// that the function is returning a const reference.
9822 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9823                                     SourceLocation Loc) {
9824   // Update err_typecheck_assign_const and note_typecheck_assign_const
9825   // when this enum is changed.
9826   enum {
9827     ConstFunction,
9828     ConstVariable,
9829     ConstMember,
9830     ConstMethod,
9831     ConstUnknown,  // Keep as last element
9832   };
9833 
9834   SourceRange ExprRange = E->getSourceRange();
9835 
9836   // Only emit one error on the first const found.  All other consts will emit
9837   // a note to the error.
9838   bool DiagnosticEmitted = false;
9839 
9840   // Track if the current expression is the result of a derefence, and if the
9841   // next checked expression is the result of a derefence.
9842   bool IsDereference = false;
9843   bool NextIsDereference = false;
9844 
9845   // Loop to process MemberExpr chains.
9846   while (true) {
9847     IsDereference = NextIsDereference;
9848     NextIsDereference = false;
9849 
9850     E = E->IgnoreParenImpCasts();
9851     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9852       NextIsDereference = ME->isArrow();
9853       const ValueDecl *VD = ME->getMemberDecl();
9854       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9855         // Mutable fields can be modified even if the class is const.
9856         if (Field->isMutable()) {
9857           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9858           break;
9859         }
9860 
9861         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9862           if (!DiagnosticEmitted) {
9863             S.Diag(Loc, diag::err_typecheck_assign_const)
9864                 << ExprRange << ConstMember << false /*static*/ << Field
9865                 << Field->getType();
9866             DiagnosticEmitted = true;
9867           }
9868           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9869               << ConstMember << false /*static*/ << Field << Field->getType()
9870               << Field->getSourceRange();
9871         }
9872         E = ME->getBase();
9873         continue;
9874       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9875         if (VDecl->getType().isConstQualified()) {
9876           if (!DiagnosticEmitted) {
9877             S.Diag(Loc, diag::err_typecheck_assign_const)
9878                 << ExprRange << ConstMember << true /*static*/ << VDecl
9879                 << VDecl->getType();
9880             DiagnosticEmitted = true;
9881           }
9882           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9883               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9884               << VDecl->getSourceRange();
9885         }
9886         // Static fields do not inherit constness from parents.
9887         break;
9888       }
9889       break;
9890     } // End MemberExpr
9891     break;
9892   }
9893 
9894   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9895     // Function calls
9896     const FunctionDecl *FD = CE->getDirectCallee();
9897     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9898       if (!DiagnosticEmitted) {
9899         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9900                                                       << ConstFunction << FD;
9901         DiagnosticEmitted = true;
9902       }
9903       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9904              diag::note_typecheck_assign_const)
9905           << ConstFunction << FD << FD->getReturnType()
9906           << FD->getReturnTypeSourceRange();
9907     }
9908   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9909     // Point to variable declaration.
9910     if (const ValueDecl *VD = DRE->getDecl()) {
9911       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9912         if (!DiagnosticEmitted) {
9913           S.Diag(Loc, diag::err_typecheck_assign_const)
9914               << ExprRange << ConstVariable << VD << VD->getType();
9915           DiagnosticEmitted = true;
9916         }
9917         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9918             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9919       }
9920     }
9921   } else if (isa<CXXThisExpr>(E)) {
9922     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9923       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9924         if (MD->isConst()) {
9925           if (!DiagnosticEmitted) {
9926             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9927                                                           << ConstMethod << MD;
9928             DiagnosticEmitted = true;
9929           }
9930           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9931               << ConstMethod << MD << MD->getSourceRange();
9932         }
9933       }
9934     }
9935   }
9936 
9937   if (DiagnosticEmitted)
9938     return;
9939 
9940   // Can't determine a more specific message, so display the generic error.
9941   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9942 }
9943 
9944 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9945 /// emit an error and return true.  If so, return false.
9946 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9947   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9948 
9949   S.CheckShadowingDeclModification(E, Loc);
9950 
9951   SourceLocation OrigLoc = Loc;
9952   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9953                                                               &Loc);
9954   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9955     IsLV = Expr::MLV_InvalidMessageExpression;
9956   if (IsLV == Expr::MLV_Valid)
9957     return false;
9958 
9959   unsigned DiagID = 0;
9960   bool NeedType = false;
9961   switch (IsLV) { // C99 6.5.16p2
9962   case Expr::MLV_ConstQualified:
9963     // Use a specialized diagnostic when we're assigning to an object
9964     // from an enclosing function or block.
9965     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9966       if (NCCK == NCCK_Block)
9967         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9968       else
9969         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9970       break;
9971     }
9972 
9973     // In ARC, use some specialized diagnostics for occasions where we
9974     // infer 'const'.  These are always pseudo-strong variables.
9975     if (S.getLangOpts().ObjCAutoRefCount) {
9976       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9977       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9978         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9979 
9980         // Use the normal diagnostic if it's pseudo-__strong but the
9981         // user actually wrote 'const'.
9982         if (var->isARCPseudoStrong() &&
9983             (!var->getTypeSourceInfo() ||
9984              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9985           // There are two pseudo-strong cases:
9986           //  - self
9987           ObjCMethodDecl *method = S.getCurMethodDecl();
9988           if (method && var == method->getSelfDecl())
9989             DiagID = method->isClassMethod()
9990               ? diag::err_typecheck_arc_assign_self_class_method
9991               : diag::err_typecheck_arc_assign_self;
9992 
9993           //  - fast enumeration variables
9994           else
9995             DiagID = diag::err_typecheck_arr_assign_enumeration;
9996 
9997           SourceRange Assign;
9998           if (Loc != OrigLoc)
9999             Assign = SourceRange(OrigLoc, OrigLoc);
10000           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10001           // We need to preserve the AST regardless, so migration tool
10002           // can do its job.
10003           return false;
10004         }
10005       }
10006     }
10007 
10008     // If none of the special cases above are triggered, then this is a
10009     // simple const assignment.
10010     if (DiagID == 0) {
10011       DiagnoseConstAssignment(S, E, Loc);
10012       return true;
10013     }
10014 
10015     break;
10016   case Expr::MLV_ConstAddrSpace:
10017     DiagnoseConstAssignment(S, E, Loc);
10018     return true;
10019   case Expr::MLV_ArrayType:
10020   case Expr::MLV_ArrayTemporary:
10021     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10022     NeedType = true;
10023     break;
10024   case Expr::MLV_NotObjectType:
10025     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10026     NeedType = true;
10027     break;
10028   case Expr::MLV_LValueCast:
10029     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10030     break;
10031   case Expr::MLV_Valid:
10032     llvm_unreachable("did not take early return for MLV_Valid");
10033   case Expr::MLV_InvalidExpression:
10034   case Expr::MLV_MemberFunction:
10035   case Expr::MLV_ClassTemporary:
10036     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10037     break;
10038   case Expr::MLV_IncompleteType:
10039   case Expr::MLV_IncompleteVoidType:
10040     return S.RequireCompleteType(Loc, E->getType(),
10041              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10042   case Expr::MLV_DuplicateVectorComponents:
10043     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10044     break;
10045   case Expr::MLV_NoSetterProperty:
10046     llvm_unreachable("readonly properties should be processed differently");
10047   case Expr::MLV_InvalidMessageExpression:
10048     DiagID = diag::error_readonly_message_assignment;
10049     break;
10050   case Expr::MLV_SubObjCPropertySetting:
10051     DiagID = diag::error_no_subobject_property_setting;
10052     break;
10053   }
10054 
10055   SourceRange Assign;
10056   if (Loc != OrigLoc)
10057     Assign = SourceRange(OrigLoc, OrigLoc);
10058   if (NeedType)
10059     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10060   else
10061     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10062   return true;
10063 }
10064 
10065 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10066                                          SourceLocation Loc,
10067                                          Sema &Sema) {
10068   // C / C++ fields
10069   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10070   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10071   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10072     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10073       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10074   }
10075 
10076   // Objective-C instance variables
10077   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10078   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10079   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10080     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10081     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10082     if (RL && RR && RL->getDecl() == RR->getDecl())
10083       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10084   }
10085 }
10086 
10087 // C99 6.5.16.1
10088 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10089                                        SourceLocation Loc,
10090                                        QualType CompoundType) {
10091   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10092 
10093   // Verify that LHS is a modifiable lvalue, and emit error if not.
10094   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10095     return QualType();
10096 
10097   QualType LHSType = LHSExpr->getType();
10098   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10099                                              CompoundType;
10100   // OpenCL v1.2 s6.1.1.1 p2:
10101   // The half data type can only be used to declare a pointer to a buffer that
10102   // contains half values
10103   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
10104     LHSType->isHalfType()) {
10105     Diag(Loc, diag::err_opencl_half_load_store) << 1
10106         << LHSType.getUnqualifiedType();
10107     return QualType();
10108   }
10109 
10110   AssignConvertType ConvTy;
10111   if (CompoundType.isNull()) {
10112     Expr *RHSCheck = RHS.get();
10113 
10114     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10115 
10116     QualType LHSTy(LHSType);
10117     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10118     if (RHS.isInvalid())
10119       return QualType();
10120     // Special case of NSObject attributes on c-style pointer types.
10121     if (ConvTy == IncompatiblePointer &&
10122         ((Context.isObjCNSObjectType(LHSType) &&
10123           RHSType->isObjCObjectPointerType()) ||
10124          (Context.isObjCNSObjectType(RHSType) &&
10125           LHSType->isObjCObjectPointerType())))
10126       ConvTy = Compatible;
10127 
10128     if (ConvTy == Compatible &&
10129         LHSType->isObjCObjectType())
10130         Diag(Loc, diag::err_objc_object_assignment)
10131           << LHSType;
10132 
10133     // If the RHS is a unary plus or minus, check to see if they = and + are
10134     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10135     // instead of "x += 4".
10136     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10137       RHSCheck = ICE->getSubExpr();
10138     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10139       if ((UO->getOpcode() == UO_Plus ||
10140            UO->getOpcode() == UO_Minus) &&
10141           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10142           // Only if the two operators are exactly adjacent.
10143           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10144           // And there is a space or other character before the subexpr of the
10145           // unary +/-.  We don't want to warn on "x=-1".
10146           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10147           UO->getSubExpr()->getLocStart().isFileID()) {
10148         Diag(Loc, diag::warn_not_compound_assign)
10149           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10150           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10151       }
10152     }
10153 
10154     if (ConvTy == Compatible) {
10155       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10156         // Warn about retain cycles where a block captures the LHS, but
10157         // not if the LHS is a simple variable into which the block is
10158         // being stored...unless that variable can be captured by reference!
10159         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10160         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10161         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10162           checkRetainCycles(LHSExpr, RHS.get());
10163 
10164         // It is safe to assign a weak reference into a strong variable.
10165         // Although this code can still have problems:
10166         //   id x = self.weakProp;
10167         //   id y = self.weakProp;
10168         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10169         // paths through the function. This should be revisited if
10170         // -Wrepeated-use-of-weak is made flow-sensitive.
10171         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10172                              RHS.get()->getLocStart()))
10173           getCurFunction()->markSafeWeakUse(RHS.get());
10174 
10175       } else if (getLangOpts().ObjCAutoRefCount) {
10176         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10177       }
10178     }
10179   } else {
10180     // Compound assignment "x += y"
10181     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10182   }
10183 
10184   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10185                                RHS.get(), AA_Assigning))
10186     return QualType();
10187 
10188   CheckForNullPointerDereference(*this, LHSExpr);
10189 
10190   // C99 6.5.16p3: The type of an assignment expression is the type of the
10191   // left operand unless the left operand has qualified type, in which case
10192   // it is the unqualified version of the type of the left operand.
10193   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10194   // is converted to the type of the assignment expression (above).
10195   // C++ 5.17p1: the type of the assignment expression is that of its left
10196   // operand.
10197   return (getLangOpts().CPlusPlus
10198           ? LHSType : LHSType.getUnqualifiedType());
10199 }
10200 
10201 // Only ignore explicit casts to void.
10202 static bool IgnoreCommaOperand(const Expr *E) {
10203   E = E->IgnoreParens();
10204 
10205   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10206     if (CE->getCastKind() == CK_ToVoid) {
10207       return true;
10208     }
10209   }
10210 
10211   return false;
10212 }
10213 
10214 // Look for instances where it is likely the comma operator is confused with
10215 // another operator.  There is a whitelist of acceptable expressions for the
10216 // left hand side of the comma operator, otherwise emit a warning.
10217 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10218   // No warnings in macros
10219   if (Loc.isMacroID())
10220     return;
10221 
10222   // Don't warn in template instantiations.
10223   if (!ActiveTemplateInstantiations.empty())
10224     return;
10225 
10226   // Scope isn't fine-grained enough to whitelist the specific cases, so
10227   // instead, skip more than needed, then call back into here with the
10228   // CommaVisitor in SemaStmt.cpp.
10229   // The whitelisted locations are the initialization and increment portions
10230   // of a for loop.  The additional checks are on the condition of
10231   // if statements, do/while loops, and for loops.
10232   const unsigned ForIncrementFlags =
10233       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10234   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10235   const unsigned ScopeFlags = getCurScope()->getFlags();
10236   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10237       (ScopeFlags & ForInitFlags) == ForInitFlags)
10238     return;
10239 
10240   // If there are multiple comma operators used together, get the RHS of the
10241   // of the comma operator as the LHS.
10242   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10243     if (BO->getOpcode() != BO_Comma)
10244       break;
10245     LHS = BO->getRHS();
10246   }
10247 
10248   // Only allow some expressions on LHS to not warn.
10249   if (IgnoreCommaOperand(LHS))
10250     return;
10251 
10252   Diag(Loc, diag::warn_comma_operator);
10253   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10254       << LHS->getSourceRange()
10255       << FixItHint::CreateInsertion(LHS->getLocStart(),
10256                                     LangOpts.CPlusPlus ? "static_cast<void>("
10257                                                        : "(void)(")
10258       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10259                                     ")");
10260 }
10261 
10262 // C99 6.5.17
10263 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10264                                    SourceLocation Loc) {
10265   LHS = S.CheckPlaceholderExpr(LHS.get());
10266   RHS = S.CheckPlaceholderExpr(RHS.get());
10267   if (LHS.isInvalid() || RHS.isInvalid())
10268     return QualType();
10269 
10270   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10271   // operands, but not unary promotions.
10272   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10273 
10274   // So we treat the LHS as a ignored value, and in C++ we allow the
10275   // containing site to determine what should be done with the RHS.
10276   LHS = S.IgnoredValueConversions(LHS.get());
10277   if (LHS.isInvalid())
10278     return QualType();
10279 
10280   S.DiagnoseUnusedExprResult(LHS.get());
10281 
10282   if (!S.getLangOpts().CPlusPlus) {
10283     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10284     if (RHS.isInvalid())
10285       return QualType();
10286     if (!RHS.get()->getType()->isVoidType())
10287       S.RequireCompleteType(Loc, RHS.get()->getType(),
10288                             diag::err_incomplete_type);
10289   }
10290 
10291   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10292     S.DiagnoseCommaOperator(LHS.get(), Loc);
10293 
10294   return RHS.get()->getType();
10295 }
10296 
10297 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10298 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10299 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10300                                                ExprValueKind &VK,
10301                                                ExprObjectKind &OK,
10302                                                SourceLocation OpLoc,
10303                                                bool IsInc, bool IsPrefix) {
10304   if (Op->isTypeDependent())
10305     return S.Context.DependentTy;
10306 
10307   QualType ResType = Op->getType();
10308   // Atomic types can be used for increment / decrement where the non-atomic
10309   // versions can, so ignore the _Atomic() specifier for the purpose of
10310   // checking.
10311   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10312     ResType = ResAtomicType->getValueType();
10313 
10314   assert(!ResType.isNull() && "no type for increment/decrement expression");
10315 
10316   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10317     // Decrement of bool is not allowed.
10318     if (!IsInc) {
10319       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10320       return QualType();
10321     }
10322     // Increment of bool sets it to true, but is deprecated.
10323     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10324                                               : diag::warn_increment_bool)
10325       << Op->getSourceRange();
10326   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10327     // Error on enum increments and decrements in C++ mode
10328     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10329     return QualType();
10330   } else if (ResType->isRealType()) {
10331     // OK!
10332   } else if (ResType->isPointerType()) {
10333     // C99 6.5.2.4p2, 6.5.6p2
10334     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10335       return QualType();
10336   } else if (ResType->isObjCObjectPointerType()) {
10337     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10338     // Otherwise, we just need a complete type.
10339     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10340         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10341       return QualType();
10342   } else if (ResType->isAnyComplexType()) {
10343     // C99 does not support ++/-- on complex types, we allow as an extension.
10344     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10345       << ResType << Op->getSourceRange();
10346   } else if (ResType->isPlaceholderType()) {
10347     ExprResult PR = S.CheckPlaceholderExpr(Op);
10348     if (PR.isInvalid()) return QualType();
10349     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10350                                           IsInc, IsPrefix);
10351   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10352     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10353   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10354              (ResType->getAs<VectorType>()->getVectorKind() !=
10355               VectorType::AltiVecBool)) {
10356     // The z vector extensions allow ++ and -- for non-bool vectors.
10357   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10358             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10359     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10360   } else {
10361     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10362       << ResType << int(IsInc) << Op->getSourceRange();
10363     return QualType();
10364   }
10365   // At this point, we know we have a real, complex or pointer type.
10366   // Now make sure the operand is a modifiable lvalue.
10367   if (CheckForModifiableLvalue(Op, OpLoc, S))
10368     return QualType();
10369   // In C++, a prefix increment is the same type as the operand. Otherwise
10370   // (in C or with postfix), the increment is the unqualified type of the
10371   // operand.
10372   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10373     VK = VK_LValue;
10374     OK = Op->getObjectKind();
10375     return ResType;
10376   } else {
10377     VK = VK_RValue;
10378     return ResType.getUnqualifiedType();
10379   }
10380 }
10381 
10382 
10383 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10384 /// This routine allows us to typecheck complex/recursive expressions
10385 /// where the declaration is needed for type checking. We only need to
10386 /// handle cases when the expression references a function designator
10387 /// or is an lvalue. Here are some examples:
10388 ///  - &(x) => x
10389 ///  - &*****f => f for f a function designator.
10390 ///  - &s.xx => s
10391 ///  - &s.zz[1].yy -> s, if zz is an array
10392 ///  - *(x + 1) -> x, if x is an array
10393 ///  - &"123"[2] -> 0
10394 ///  - & __real__ x -> x
10395 static ValueDecl *getPrimaryDecl(Expr *E) {
10396   switch (E->getStmtClass()) {
10397   case Stmt::DeclRefExprClass:
10398     return cast<DeclRefExpr>(E)->getDecl();
10399   case Stmt::MemberExprClass:
10400     // If this is an arrow operator, the address is an offset from
10401     // the base's value, so the object the base refers to is
10402     // irrelevant.
10403     if (cast<MemberExpr>(E)->isArrow())
10404       return nullptr;
10405     // Otherwise, the expression refers to a part of the base
10406     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10407   case Stmt::ArraySubscriptExprClass: {
10408     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10409     // promotion of register arrays earlier.
10410     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10411     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10412       if (ICE->getSubExpr()->getType()->isArrayType())
10413         return getPrimaryDecl(ICE->getSubExpr());
10414     }
10415     return nullptr;
10416   }
10417   case Stmt::UnaryOperatorClass: {
10418     UnaryOperator *UO = cast<UnaryOperator>(E);
10419 
10420     switch(UO->getOpcode()) {
10421     case UO_Real:
10422     case UO_Imag:
10423     case UO_Extension:
10424       return getPrimaryDecl(UO->getSubExpr());
10425     default:
10426       return nullptr;
10427     }
10428   }
10429   case Stmt::ParenExprClass:
10430     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10431   case Stmt::ImplicitCastExprClass:
10432     // If the result of an implicit cast is an l-value, we care about
10433     // the sub-expression; otherwise, the result here doesn't matter.
10434     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10435   default:
10436     return nullptr;
10437   }
10438 }
10439 
10440 namespace {
10441   enum {
10442     AO_Bit_Field = 0,
10443     AO_Vector_Element = 1,
10444     AO_Property_Expansion = 2,
10445     AO_Register_Variable = 3,
10446     AO_No_Error = 4
10447   };
10448 }
10449 /// \brief Diagnose invalid operand for address of operations.
10450 ///
10451 /// \param Type The type of operand which cannot have its address taken.
10452 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10453                                          Expr *E, unsigned Type) {
10454   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10455 }
10456 
10457 /// CheckAddressOfOperand - The operand of & must be either a function
10458 /// designator or an lvalue designating an object. If it is an lvalue, the
10459 /// object cannot be declared with storage class register or be a bit field.
10460 /// Note: The usual conversions are *not* applied to the operand of the &
10461 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10462 /// In C++, the operand might be an overloaded function name, in which case
10463 /// we allow the '&' but retain the overloaded-function type.
10464 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10465   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10466     if (PTy->getKind() == BuiltinType::Overload) {
10467       Expr *E = OrigOp.get()->IgnoreParens();
10468       if (!isa<OverloadExpr>(E)) {
10469         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10470         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10471           << OrigOp.get()->getSourceRange();
10472         return QualType();
10473       }
10474 
10475       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10476       if (isa<UnresolvedMemberExpr>(Ovl))
10477         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10478           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10479             << OrigOp.get()->getSourceRange();
10480           return QualType();
10481         }
10482 
10483       return Context.OverloadTy;
10484     }
10485 
10486     if (PTy->getKind() == BuiltinType::UnknownAny)
10487       return Context.UnknownAnyTy;
10488 
10489     if (PTy->getKind() == BuiltinType::BoundMember) {
10490       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10491         << OrigOp.get()->getSourceRange();
10492       return QualType();
10493     }
10494 
10495     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10496     if (OrigOp.isInvalid()) return QualType();
10497   }
10498 
10499   if (OrigOp.get()->isTypeDependent())
10500     return Context.DependentTy;
10501 
10502   assert(!OrigOp.get()->getType()->isPlaceholderType());
10503 
10504   // Make sure to ignore parentheses in subsequent checks
10505   Expr *op = OrigOp.get()->IgnoreParens();
10506 
10507   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10508   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10509     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10510     return QualType();
10511   }
10512 
10513   if (getLangOpts().C99) {
10514     // Implement C99-only parts of addressof rules.
10515     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10516       if (uOp->getOpcode() == UO_Deref)
10517         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10518         // (assuming the deref expression is valid).
10519         return uOp->getSubExpr()->getType();
10520     }
10521     // Technically, there should be a check for array subscript
10522     // expressions here, but the result of one is always an lvalue anyway.
10523   }
10524   ValueDecl *dcl = getPrimaryDecl(op);
10525 
10526   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10527     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10528                                            op->getLocStart()))
10529       return QualType();
10530 
10531   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10532   unsigned AddressOfError = AO_No_Error;
10533 
10534   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10535     bool sfinae = (bool)isSFINAEContext();
10536     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10537                                   : diag::ext_typecheck_addrof_temporary)
10538       << op->getType() << op->getSourceRange();
10539     if (sfinae)
10540       return QualType();
10541     // Materialize the temporary as an lvalue so that we can take its address.
10542     OrigOp = op =
10543         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10544   } else if (isa<ObjCSelectorExpr>(op)) {
10545     return Context.getPointerType(op->getType());
10546   } else if (lval == Expr::LV_MemberFunction) {
10547     // If it's an instance method, make a member pointer.
10548     // The expression must have exactly the form &A::foo.
10549 
10550     // If the underlying expression isn't a decl ref, give up.
10551     if (!isa<DeclRefExpr>(op)) {
10552       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10553         << OrigOp.get()->getSourceRange();
10554       return QualType();
10555     }
10556     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10557     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10558 
10559     // The id-expression was parenthesized.
10560     if (OrigOp.get() != DRE) {
10561       Diag(OpLoc, diag::err_parens_pointer_member_function)
10562         << OrigOp.get()->getSourceRange();
10563 
10564     // The method was named without a qualifier.
10565     } else if (!DRE->getQualifier()) {
10566       if (MD->getParent()->getName().empty())
10567         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10568           << op->getSourceRange();
10569       else {
10570         SmallString<32> Str;
10571         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10572         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10573           << op->getSourceRange()
10574           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10575       }
10576     }
10577 
10578     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10579     if (isa<CXXDestructorDecl>(MD))
10580       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10581 
10582     QualType MPTy = Context.getMemberPointerType(
10583         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10584     // Under the MS ABI, lock down the inheritance model now.
10585     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10586       (void)isCompleteType(OpLoc, MPTy);
10587     return MPTy;
10588   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10589     // C99 6.5.3.2p1
10590     // The operand must be either an l-value or a function designator
10591     if (!op->getType()->isFunctionType()) {
10592       // Use a special diagnostic for loads from property references.
10593       if (isa<PseudoObjectExpr>(op)) {
10594         AddressOfError = AO_Property_Expansion;
10595       } else {
10596         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10597           << op->getType() << op->getSourceRange();
10598         return QualType();
10599       }
10600     }
10601   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10602     // The operand cannot be a bit-field
10603     AddressOfError = AO_Bit_Field;
10604   } else if (op->getObjectKind() == OK_VectorComponent) {
10605     // The operand cannot be an element of a vector
10606     AddressOfError = AO_Vector_Element;
10607   } else if (dcl) { // C99 6.5.3.2p1
10608     // We have an lvalue with a decl. Make sure the decl is not declared
10609     // with the register storage-class specifier.
10610     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10611       // in C++ it is not error to take address of a register
10612       // variable (c++03 7.1.1P3)
10613       if (vd->getStorageClass() == SC_Register &&
10614           !getLangOpts().CPlusPlus) {
10615         AddressOfError = AO_Register_Variable;
10616       }
10617     } else if (isa<MSPropertyDecl>(dcl)) {
10618       AddressOfError = AO_Property_Expansion;
10619     } else if (isa<FunctionTemplateDecl>(dcl)) {
10620       return Context.OverloadTy;
10621     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10622       // Okay: we can take the address of a field.
10623       // Could be a pointer to member, though, if there is an explicit
10624       // scope qualifier for the class.
10625       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10626         DeclContext *Ctx = dcl->getDeclContext();
10627         if (Ctx && Ctx->isRecord()) {
10628           if (dcl->getType()->isReferenceType()) {
10629             Diag(OpLoc,
10630                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10631               << dcl->getDeclName() << dcl->getType();
10632             return QualType();
10633           }
10634 
10635           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10636             Ctx = Ctx->getParent();
10637 
10638           QualType MPTy = Context.getMemberPointerType(
10639               op->getType(),
10640               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10641           // Under the MS ABI, lock down the inheritance model now.
10642           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10643             (void)isCompleteType(OpLoc, MPTy);
10644           return MPTy;
10645         }
10646       }
10647     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10648                !isa<BindingDecl>(dcl))
10649       llvm_unreachable("Unknown/unexpected decl type");
10650   }
10651 
10652   if (AddressOfError != AO_No_Error) {
10653     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10654     return QualType();
10655   }
10656 
10657   if (lval == Expr::LV_IncompleteVoidType) {
10658     // Taking the address of a void variable is technically illegal, but we
10659     // allow it in cases which are otherwise valid.
10660     // Example: "extern void x; void* y = &x;".
10661     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10662   }
10663 
10664   // If the operand has type "type", the result has type "pointer to type".
10665   if (op->getType()->isObjCObjectType())
10666     return Context.getObjCObjectPointerType(op->getType());
10667 
10668   CheckAddressOfPackedMember(op);
10669 
10670   return Context.getPointerType(op->getType());
10671 }
10672 
10673 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10674   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10675   if (!DRE)
10676     return;
10677   const Decl *D = DRE->getDecl();
10678   if (!D)
10679     return;
10680   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10681   if (!Param)
10682     return;
10683   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10684     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10685       return;
10686   if (FunctionScopeInfo *FD = S.getCurFunction())
10687     if (!FD->ModifiedNonNullParams.count(Param))
10688       FD->ModifiedNonNullParams.insert(Param);
10689 }
10690 
10691 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10692 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10693                                         SourceLocation OpLoc) {
10694   if (Op->isTypeDependent())
10695     return S.Context.DependentTy;
10696 
10697   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10698   if (ConvResult.isInvalid())
10699     return QualType();
10700   Op = ConvResult.get();
10701   QualType OpTy = Op->getType();
10702   QualType Result;
10703 
10704   if (isa<CXXReinterpretCastExpr>(Op)) {
10705     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10706     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10707                                      Op->getSourceRange());
10708   }
10709 
10710   if (const PointerType *PT = OpTy->getAs<PointerType>())
10711   {
10712     Result = PT->getPointeeType();
10713   }
10714   else if (const ObjCObjectPointerType *OPT =
10715              OpTy->getAs<ObjCObjectPointerType>())
10716     Result = OPT->getPointeeType();
10717   else {
10718     ExprResult PR = S.CheckPlaceholderExpr(Op);
10719     if (PR.isInvalid()) return QualType();
10720     if (PR.get() != Op)
10721       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10722   }
10723 
10724   if (Result.isNull()) {
10725     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10726       << OpTy << Op->getSourceRange();
10727     return QualType();
10728   }
10729 
10730   // Note that per both C89 and C99, indirection is always legal, even if Result
10731   // is an incomplete type or void.  It would be possible to warn about
10732   // dereferencing a void pointer, but it's completely well-defined, and such a
10733   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10734   // for pointers to 'void' but is fine for any other pointer type:
10735   //
10736   // C++ [expr.unary.op]p1:
10737   //   [...] the expression to which [the unary * operator] is applied shall
10738   //   be a pointer to an object type, or a pointer to a function type
10739   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10740     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10741       << OpTy << Op->getSourceRange();
10742 
10743   // Dereferences are usually l-values...
10744   VK = VK_LValue;
10745 
10746   // ...except that certain expressions are never l-values in C.
10747   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10748     VK = VK_RValue;
10749 
10750   return Result;
10751 }
10752 
10753 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10754   BinaryOperatorKind Opc;
10755   switch (Kind) {
10756   default: llvm_unreachable("Unknown binop!");
10757   case tok::periodstar:           Opc = BO_PtrMemD; break;
10758   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10759   case tok::star:                 Opc = BO_Mul; break;
10760   case tok::slash:                Opc = BO_Div; break;
10761   case tok::percent:              Opc = BO_Rem; break;
10762   case tok::plus:                 Opc = BO_Add; break;
10763   case tok::minus:                Opc = BO_Sub; break;
10764   case tok::lessless:             Opc = BO_Shl; break;
10765   case tok::greatergreater:       Opc = BO_Shr; break;
10766   case tok::lessequal:            Opc = BO_LE; break;
10767   case tok::less:                 Opc = BO_LT; break;
10768   case tok::greaterequal:         Opc = BO_GE; break;
10769   case tok::greater:              Opc = BO_GT; break;
10770   case tok::exclaimequal:         Opc = BO_NE; break;
10771   case tok::equalequal:           Opc = BO_EQ; break;
10772   case tok::amp:                  Opc = BO_And; break;
10773   case tok::caret:                Opc = BO_Xor; break;
10774   case tok::pipe:                 Opc = BO_Or; break;
10775   case tok::ampamp:               Opc = BO_LAnd; break;
10776   case tok::pipepipe:             Opc = BO_LOr; break;
10777   case tok::equal:                Opc = BO_Assign; break;
10778   case tok::starequal:            Opc = BO_MulAssign; break;
10779   case tok::slashequal:           Opc = BO_DivAssign; break;
10780   case tok::percentequal:         Opc = BO_RemAssign; break;
10781   case tok::plusequal:            Opc = BO_AddAssign; break;
10782   case tok::minusequal:           Opc = BO_SubAssign; break;
10783   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10784   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10785   case tok::ampequal:             Opc = BO_AndAssign; break;
10786   case tok::caretequal:           Opc = BO_XorAssign; break;
10787   case tok::pipeequal:            Opc = BO_OrAssign; break;
10788   case tok::comma:                Opc = BO_Comma; break;
10789   }
10790   return Opc;
10791 }
10792 
10793 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10794   tok::TokenKind Kind) {
10795   UnaryOperatorKind Opc;
10796   switch (Kind) {
10797   default: llvm_unreachable("Unknown unary op!");
10798   case tok::plusplus:     Opc = UO_PreInc; break;
10799   case tok::minusminus:   Opc = UO_PreDec; break;
10800   case tok::amp:          Opc = UO_AddrOf; break;
10801   case tok::star:         Opc = UO_Deref; break;
10802   case tok::plus:         Opc = UO_Plus; break;
10803   case tok::minus:        Opc = UO_Minus; break;
10804   case tok::tilde:        Opc = UO_Not; break;
10805   case tok::exclaim:      Opc = UO_LNot; break;
10806   case tok::kw___real:    Opc = UO_Real; break;
10807   case tok::kw___imag:    Opc = UO_Imag; break;
10808   case tok::kw___extension__: Opc = UO_Extension; break;
10809   }
10810   return Opc;
10811 }
10812 
10813 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10814 /// This warning is only emitted for builtin assignment operations. It is also
10815 /// suppressed in the event of macro expansions.
10816 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10817                                    SourceLocation OpLoc) {
10818   if (!S.ActiveTemplateInstantiations.empty())
10819     return;
10820   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10821     return;
10822   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10823   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10824   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10825   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10826   if (!LHSDeclRef || !RHSDeclRef ||
10827       LHSDeclRef->getLocation().isMacroID() ||
10828       RHSDeclRef->getLocation().isMacroID())
10829     return;
10830   const ValueDecl *LHSDecl =
10831     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10832   const ValueDecl *RHSDecl =
10833     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10834   if (LHSDecl != RHSDecl)
10835     return;
10836   if (LHSDecl->getType().isVolatileQualified())
10837     return;
10838   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10839     if (RefTy->getPointeeType().isVolatileQualified())
10840       return;
10841 
10842   S.Diag(OpLoc, diag::warn_self_assignment)
10843       << LHSDeclRef->getType()
10844       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10845 }
10846 
10847 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10848 /// is usually indicative of introspection within the Objective-C pointer.
10849 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10850                                           SourceLocation OpLoc) {
10851   if (!S.getLangOpts().ObjC1)
10852     return;
10853 
10854   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10855   const Expr *LHS = L.get();
10856   const Expr *RHS = R.get();
10857 
10858   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10859     ObjCPointerExpr = LHS;
10860     OtherExpr = RHS;
10861   }
10862   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10863     ObjCPointerExpr = RHS;
10864     OtherExpr = LHS;
10865   }
10866 
10867   // This warning is deliberately made very specific to reduce false
10868   // positives with logic that uses '&' for hashing.  This logic mainly
10869   // looks for code trying to introspect into tagged pointers, which
10870   // code should generally never do.
10871   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10872     unsigned Diag = diag::warn_objc_pointer_masking;
10873     // Determine if we are introspecting the result of performSelectorXXX.
10874     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10875     // Special case messages to -performSelector and friends, which
10876     // can return non-pointer values boxed in a pointer value.
10877     // Some clients may wish to silence warnings in this subcase.
10878     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10879       Selector S = ME->getSelector();
10880       StringRef SelArg0 = S.getNameForSlot(0);
10881       if (SelArg0.startswith("performSelector"))
10882         Diag = diag::warn_objc_pointer_masking_performSelector;
10883     }
10884 
10885     S.Diag(OpLoc, Diag)
10886       << ObjCPointerExpr->getSourceRange();
10887   }
10888 }
10889 
10890 static NamedDecl *getDeclFromExpr(Expr *E) {
10891   if (!E)
10892     return nullptr;
10893   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10894     return DRE->getDecl();
10895   if (auto *ME = dyn_cast<MemberExpr>(E))
10896     return ME->getMemberDecl();
10897   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10898     return IRE->getDecl();
10899   return nullptr;
10900 }
10901 
10902 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10903 /// operator @p Opc at location @c TokLoc. This routine only supports
10904 /// built-in operations; ActOnBinOp handles overloaded operators.
10905 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10906                                     BinaryOperatorKind Opc,
10907                                     Expr *LHSExpr, Expr *RHSExpr) {
10908   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10909     // The syntax only allows initializer lists on the RHS of assignment,
10910     // so we don't need to worry about accepting invalid code for
10911     // non-assignment operators.
10912     // C++11 5.17p9:
10913     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10914     //   of x = {} is x = T().
10915     InitializationKind Kind =
10916         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10917     InitializedEntity Entity =
10918         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10919     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10920     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10921     if (Init.isInvalid())
10922       return Init;
10923     RHSExpr = Init.get();
10924   }
10925 
10926   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10927   QualType ResultTy;     // Result type of the binary operator.
10928   // The following two variables are used for compound assignment operators
10929   QualType CompLHSTy;    // Type of LHS after promotions for computation
10930   QualType CompResultTy; // Type of computation result
10931   ExprValueKind VK = VK_RValue;
10932   ExprObjectKind OK = OK_Ordinary;
10933 
10934   if (!getLangOpts().CPlusPlus) {
10935     // C cannot handle TypoExpr nodes on either side of a binop because it
10936     // doesn't handle dependent types properly, so make sure any TypoExprs have
10937     // been dealt with before checking the operands.
10938     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10939     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10940       if (Opc != BO_Assign)
10941         return ExprResult(E);
10942       // Avoid correcting the RHS to the same Expr as the LHS.
10943       Decl *D = getDeclFromExpr(E);
10944       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10945     });
10946     if (!LHS.isUsable() || !RHS.isUsable())
10947       return ExprError();
10948   }
10949 
10950   if (getLangOpts().OpenCL) {
10951     QualType LHSTy = LHSExpr->getType();
10952     QualType RHSTy = RHSExpr->getType();
10953     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10954     // the ATOMIC_VAR_INIT macro.
10955     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10956       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10957       if (BO_Assign == Opc)
10958         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10959       else
10960         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10961       return ExprError();
10962     }
10963 
10964     // OpenCL special types - image, sampler, pipe, and blocks are to be used
10965     // only with a builtin functions and therefore should be disallowed here.
10966     if (LHSTy->isImageType() || RHSTy->isImageType() ||
10967         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
10968         LHSTy->isPipeType() || RHSTy->isPipeType() ||
10969         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
10970       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10971       return ExprError();
10972     }
10973   }
10974 
10975   switch (Opc) {
10976   case BO_Assign:
10977     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10978     if (getLangOpts().CPlusPlus &&
10979         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10980       VK = LHS.get()->getValueKind();
10981       OK = LHS.get()->getObjectKind();
10982     }
10983     if (!ResultTy.isNull()) {
10984       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10985       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10986     }
10987     RecordModifiableNonNullParam(*this, LHS.get());
10988     break;
10989   case BO_PtrMemD:
10990   case BO_PtrMemI:
10991     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10992                                             Opc == BO_PtrMemI);
10993     break;
10994   case BO_Mul:
10995   case BO_Div:
10996     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10997                                            Opc == BO_Div);
10998     break;
10999   case BO_Rem:
11000     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11001     break;
11002   case BO_Add:
11003     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11004     break;
11005   case BO_Sub:
11006     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11007     break;
11008   case BO_Shl:
11009   case BO_Shr:
11010     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11011     break;
11012   case BO_LE:
11013   case BO_LT:
11014   case BO_GE:
11015   case BO_GT:
11016     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11017     break;
11018   case BO_EQ:
11019   case BO_NE:
11020     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11021     break;
11022   case BO_And:
11023     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11024   case BO_Xor:
11025   case BO_Or:
11026     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
11027     break;
11028   case BO_LAnd:
11029   case BO_LOr:
11030     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11031     break;
11032   case BO_MulAssign:
11033   case BO_DivAssign:
11034     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11035                                                Opc == BO_DivAssign);
11036     CompLHSTy = CompResultTy;
11037     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11038       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11039     break;
11040   case BO_RemAssign:
11041     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11042     CompLHSTy = CompResultTy;
11043     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11044       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11045     break;
11046   case BO_AddAssign:
11047     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11048     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11049       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11050     break;
11051   case BO_SubAssign:
11052     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11053     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11054       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11055     break;
11056   case BO_ShlAssign:
11057   case BO_ShrAssign:
11058     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11059     CompLHSTy = CompResultTy;
11060     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11061       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11062     break;
11063   case BO_AndAssign:
11064   case BO_OrAssign: // fallthrough
11065     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11066   case BO_XorAssign:
11067     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
11068     CompLHSTy = CompResultTy;
11069     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11070       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11071     break;
11072   case BO_Comma:
11073     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11074     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11075       VK = RHS.get()->getValueKind();
11076       OK = RHS.get()->getObjectKind();
11077     }
11078     break;
11079   }
11080   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11081     return ExprError();
11082 
11083   // Check for array bounds violations for both sides of the BinaryOperator
11084   CheckArrayAccess(LHS.get());
11085   CheckArrayAccess(RHS.get());
11086 
11087   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11088     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11089                                                  &Context.Idents.get("object_setClass"),
11090                                                  SourceLocation(), LookupOrdinaryName);
11091     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11092       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11093       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11094       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11095       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11096       FixItHint::CreateInsertion(RHSLocEnd, ")");
11097     }
11098     else
11099       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11100   }
11101   else if (const ObjCIvarRefExpr *OIRE =
11102            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11103     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11104 
11105   if (CompResultTy.isNull())
11106     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11107                                         OK, OpLoc, FPFeatures.fp_contract);
11108   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11109       OK_ObjCProperty) {
11110     VK = VK_LValue;
11111     OK = LHS.get()->getObjectKind();
11112   }
11113   return new (Context) CompoundAssignOperator(
11114       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11115       OpLoc, FPFeatures.fp_contract);
11116 }
11117 
11118 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11119 /// operators are mixed in a way that suggests that the programmer forgot that
11120 /// comparison operators have higher precedence. The most typical example of
11121 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11122 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11123                                       SourceLocation OpLoc, Expr *LHSExpr,
11124                                       Expr *RHSExpr) {
11125   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11126   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11127 
11128   // Check that one of the sides is a comparison operator and the other isn't.
11129   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11130   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11131   if (isLeftComp == isRightComp)
11132     return;
11133 
11134   // Bitwise operations are sometimes used as eager logical ops.
11135   // Don't diagnose this.
11136   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11137   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11138   if (isLeftBitwise || isRightBitwise)
11139     return;
11140 
11141   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11142                                                    OpLoc)
11143                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11144   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11145   SourceRange ParensRange = isLeftComp ?
11146       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11147     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11148 
11149   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11150     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11151   SuggestParentheses(Self, OpLoc,
11152     Self.PDiag(diag::note_precedence_silence) << OpStr,
11153     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11154   SuggestParentheses(Self, OpLoc,
11155     Self.PDiag(diag::note_precedence_bitwise_first)
11156       << BinaryOperator::getOpcodeStr(Opc),
11157     ParensRange);
11158 }
11159 
11160 /// \brief It accepts a '&&' expr that is inside a '||' one.
11161 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11162 /// in parentheses.
11163 static void
11164 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11165                                        BinaryOperator *Bop) {
11166   assert(Bop->getOpcode() == BO_LAnd);
11167   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11168       << Bop->getSourceRange() << OpLoc;
11169   SuggestParentheses(Self, Bop->getOperatorLoc(),
11170     Self.PDiag(diag::note_precedence_silence)
11171       << Bop->getOpcodeStr(),
11172     Bop->getSourceRange());
11173 }
11174 
11175 /// \brief Returns true if the given expression can be evaluated as a constant
11176 /// 'true'.
11177 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11178   bool Res;
11179   return !E->isValueDependent() &&
11180          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11181 }
11182 
11183 /// \brief Returns true if the given expression can be evaluated as a constant
11184 /// 'false'.
11185 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11186   bool Res;
11187   return !E->isValueDependent() &&
11188          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11189 }
11190 
11191 /// \brief Look for '&&' in the left hand of a '||' expr.
11192 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11193                                              Expr *LHSExpr, Expr *RHSExpr) {
11194   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11195     if (Bop->getOpcode() == BO_LAnd) {
11196       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11197       if (EvaluatesAsFalse(S, RHSExpr))
11198         return;
11199       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11200       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11201         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11202     } else if (Bop->getOpcode() == BO_LOr) {
11203       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11204         // If it's "a || b && 1 || c" we didn't warn earlier for
11205         // "a || b && 1", but warn now.
11206         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11207           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11208       }
11209     }
11210   }
11211 }
11212 
11213 /// \brief Look for '&&' in the right hand of a '||' expr.
11214 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11215                                              Expr *LHSExpr, Expr *RHSExpr) {
11216   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11217     if (Bop->getOpcode() == BO_LAnd) {
11218       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11219       if (EvaluatesAsFalse(S, LHSExpr))
11220         return;
11221       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11222       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11223         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11224     }
11225   }
11226 }
11227 
11228 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11229 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11230 /// the '&' expression in parentheses.
11231 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11232                                          SourceLocation OpLoc, Expr *SubExpr) {
11233   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11234     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11235       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11236         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11237         << Bop->getSourceRange() << OpLoc;
11238       SuggestParentheses(S, Bop->getOperatorLoc(),
11239         S.PDiag(diag::note_precedence_silence)
11240           << Bop->getOpcodeStr(),
11241         Bop->getSourceRange());
11242     }
11243   }
11244 }
11245 
11246 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11247                                     Expr *SubExpr, StringRef Shift) {
11248   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11249     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11250       StringRef Op = Bop->getOpcodeStr();
11251       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11252           << Bop->getSourceRange() << OpLoc << Shift << Op;
11253       SuggestParentheses(S, Bop->getOperatorLoc(),
11254           S.PDiag(diag::note_precedence_silence) << Op,
11255           Bop->getSourceRange());
11256     }
11257   }
11258 }
11259 
11260 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11261                                  Expr *LHSExpr, Expr *RHSExpr) {
11262   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11263   if (!OCE)
11264     return;
11265 
11266   FunctionDecl *FD = OCE->getDirectCallee();
11267   if (!FD || !FD->isOverloadedOperator())
11268     return;
11269 
11270   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11271   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11272     return;
11273 
11274   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11275       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11276       << (Kind == OO_LessLess);
11277   SuggestParentheses(S, OCE->getOperatorLoc(),
11278                      S.PDiag(diag::note_precedence_silence)
11279                          << (Kind == OO_LessLess ? "<<" : ">>"),
11280                      OCE->getSourceRange());
11281   SuggestParentheses(S, OpLoc,
11282                      S.PDiag(diag::note_evaluate_comparison_first),
11283                      SourceRange(OCE->getArg(1)->getLocStart(),
11284                                  RHSExpr->getLocEnd()));
11285 }
11286 
11287 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11288 /// precedence.
11289 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11290                                     SourceLocation OpLoc, Expr *LHSExpr,
11291                                     Expr *RHSExpr){
11292   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11293   if (BinaryOperator::isBitwiseOp(Opc))
11294     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11295 
11296   // Diagnose "arg1 & arg2 | arg3"
11297   if ((Opc == BO_Or || Opc == BO_Xor) &&
11298       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11299     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11300     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11301   }
11302 
11303   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11304   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11305   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11306     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11307     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11308   }
11309 
11310   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11311       || Opc == BO_Shr) {
11312     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11313     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11314     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11315   }
11316 
11317   // Warn on overloaded shift operators and comparisons, such as:
11318   // cout << 5 == 4;
11319   if (BinaryOperator::isComparisonOp(Opc))
11320     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11321 }
11322 
11323 // Binary Operators.  'Tok' is the token for the operator.
11324 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11325                             tok::TokenKind Kind,
11326                             Expr *LHSExpr, Expr *RHSExpr) {
11327   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11328   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11329   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11330 
11331   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11332   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11333 
11334   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11335 }
11336 
11337 /// Build an overloaded binary operator expression in the given scope.
11338 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11339                                        BinaryOperatorKind Opc,
11340                                        Expr *LHS, Expr *RHS) {
11341   // Find all of the overloaded operators visible from this
11342   // point. We perform both an operator-name lookup from the local
11343   // scope and an argument-dependent lookup based on the types of
11344   // the arguments.
11345   UnresolvedSet<16> Functions;
11346   OverloadedOperatorKind OverOp
11347     = BinaryOperator::getOverloadedOperator(Opc);
11348   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11349     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11350                                    RHS->getType(), Functions);
11351 
11352   // Build the (potentially-overloaded, potentially-dependent)
11353   // binary operation.
11354   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11355 }
11356 
11357 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11358                             BinaryOperatorKind Opc,
11359                             Expr *LHSExpr, Expr *RHSExpr) {
11360   // We want to end up calling one of checkPseudoObjectAssignment
11361   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11362   // both expressions are overloadable or either is type-dependent),
11363   // or CreateBuiltinBinOp (in any other case).  We also want to get
11364   // any placeholder types out of the way.
11365 
11366   // Handle pseudo-objects in the LHS.
11367   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11368     // Assignments with a pseudo-object l-value need special analysis.
11369     if (pty->getKind() == BuiltinType::PseudoObject &&
11370         BinaryOperator::isAssignmentOp(Opc))
11371       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11372 
11373     // Don't resolve overloads if the other type is overloadable.
11374     if (pty->getKind() == BuiltinType::Overload) {
11375       // We can't actually test that if we still have a placeholder,
11376       // though.  Fortunately, none of the exceptions we see in that
11377       // code below are valid when the LHS is an overload set.  Note
11378       // that an overload set can be dependently-typed, but it never
11379       // instantiates to having an overloadable type.
11380       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11381       if (resolvedRHS.isInvalid()) return ExprError();
11382       RHSExpr = resolvedRHS.get();
11383 
11384       if (RHSExpr->isTypeDependent() ||
11385           RHSExpr->getType()->isOverloadableType())
11386         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11387     }
11388 
11389     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11390     if (LHS.isInvalid()) return ExprError();
11391     LHSExpr = LHS.get();
11392   }
11393 
11394   // Handle pseudo-objects in the RHS.
11395   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11396     // An overload in the RHS can potentially be resolved by the type
11397     // being assigned to.
11398     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11399       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11400         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11401 
11402       if (LHSExpr->getType()->isOverloadableType())
11403         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11404 
11405       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11406     }
11407 
11408     // Don't resolve overloads if the other type is overloadable.
11409     if (pty->getKind() == BuiltinType::Overload &&
11410         LHSExpr->getType()->isOverloadableType())
11411       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11412 
11413     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11414     if (!resolvedRHS.isUsable()) return ExprError();
11415     RHSExpr = resolvedRHS.get();
11416   }
11417 
11418   if (getLangOpts().CPlusPlus) {
11419     // If either expression is type-dependent, always build an
11420     // overloaded op.
11421     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11422       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11423 
11424     // Otherwise, build an overloaded op if either expression has an
11425     // overloadable type.
11426     if (LHSExpr->getType()->isOverloadableType() ||
11427         RHSExpr->getType()->isOverloadableType())
11428       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11429   }
11430 
11431   // Build a built-in binary operation.
11432   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11433 }
11434 
11435 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11436                                       UnaryOperatorKind Opc,
11437                                       Expr *InputExpr) {
11438   ExprResult Input = InputExpr;
11439   ExprValueKind VK = VK_RValue;
11440   ExprObjectKind OK = OK_Ordinary;
11441   QualType resultType;
11442   if (getLangOpts().OpenCL) {
11443     QualType Ty = InputExpr->getType();
11444     // The only legal unary operation for atomics is '&'.
11445     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11446     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11447     // only with a builtin functions and therefore should be disallowed here.
11448         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11449         || Ty->isBlockPointerType())) {
11450       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11451                        << InputExpr->getType()
11452                        << Input.get()->getSourceRange());
11453     }
11454   }
11455   switch (Opc) {
11456   case UO_PreInc:
11457   case UO_PreDec:
11458   case UO_PostInc:
11459   case UO_PostDec:
11460     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11461                                                 OpLoc,
11462                                                 Opc == UO_PreInc ||
11463                                                 Opc == UO_PostInc,
11464                                                 Opc == UO_PreInc ||
11465                                                 Opc == UO_PreDec);
11466     break;
11467   case UO_AddrOf:
11468     resultType = CheckAddressOfOperand(Input, OpLoc);
11469     RecordModifiableNonNullParam(*this, InputExpr);
11470     break;
11471   case UO_Deref: {
11472     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11473     if (Input.isInvalid()) return ExprError();
11474     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11475     break;
11476   }
11477   case UO_Plus:
11478   case UO_Minus:
11479     Input = UsualUnaryConversions(Input.get());
11480     if (Input.isInvalid()) return ExprError();
11481     resultType = Input.get()->getType();
11482     if (resultType->isDependentType())
11483       break;
11484     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11485       break;
11486     else if (resultType->isVectorType() &&
11487              // The z vector extensions don't allow + or - with bool vectors.
11488              (!Context.getLangOpts().ZVector ||
11489               resultType->getAs<VectorType>()->getVectorKind() !=
11490               VectorType::AltiVecBool))
11491       break;
11492     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11493              Opc == UO_Plus &&
11494              resultType->isPointerType())
11495       break;
11496 
11497     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11498       << resultType << Input.get()->getSourceRange());
11499 
11500   case UO_Not: // bitwise complement
11501     Input = UsualUnaryConversions(Input.get());
11502     if (Input.isInvalid())
11503       return ExprError();
11504     resultType = Input.get()->getType();
11505     if (resultType->isDependentType())
11506       break;
11507     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11508     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11509       // C99 does not support '~' for complex conjugation.
11510       Diag(OpLoc, diag::ext_integer_complement_complex)
11511           << resultType << Input.get()->getSourceRange();
11512     else if (resultType->hasIntegerRepresentation())
11513       break;
11514     else if (resultType->isExtVectorType()) {
11515       if (Context.getLangOpts().OpenCL) {
11516         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11517         // on vector float types.
11518         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11519         if (!T->isIntegerType())
11520           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11521                            << resultType << Input.get()->getSourceRange());
11522       }
11523       break;
11524     } else {
11525       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11526                        << resultType << Input.get()->getSourceRange());
11527     }
11528     break;
11529 
11530   case UO_LNot: // logical negation
11531     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11532     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11533     if (Input.isInvalid()) return ExprError();
11534     resultType = Input.get()->getType();
11535 
11536     // Though we still have to promote half FP to float...
11537     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11538       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11539       resultType = Context.FloatTy;
11540     }
11541 
11542     if (resultType->isDependentType())
11543       break;
11544     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11545       // C99 6.5.3.3p1: ok, fallthrough;
11546       if (Context.getLangOpts().CPlusPlus) {
11547         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11548         // operand contextually converted to bool.
11549         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11550                                   ScalarTypeToBooleanCastKind(resultType));
11551       } else if (Context.getLangOpts().OpenCL &&
11552                  Context.getLangOpts().OpenCLVersion < 120) {
11553         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11554         // operate on scalar float types.
11555         if (!resultType->isIntegerType())
11556           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11557                            << resultType << Input.get()->getSourceRange());
11558       }
11559     } else if (resultType->isExtVectorType()) {
11560       if (Context.getLangOpts().OpenCL &&
11561           Context.getLangOpts().OpenCLVersion < 120) {
11562         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11563         // operate on vector float types.
11564         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11565         if (!T->isIntegerType())
11566           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11567                            << resultType << Input.get()->getSourceRange());
11568       }
11569       // Vector logical not returns the signed variant of the operand type.
11570       resultType = GetSignedVectorType(resultType);
11571       break;
11572     } else {
11573       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11574         << resultType << Input.get()->getSourceRange());
11575     }
11576 
11577     // LNot always has type int. C99 6.5.3.3p5.
11578     // In C++, it's bool. C++ 5.3.1p8
11579     resultType = Context.getLogicalOperationType();
11580     break;
11581   case UO_Real:
11582   case UO_Imag:
11583     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11584     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11585     // complex l-values to ordinary l-values and all other values to r-values.
11586     if (Input.isInvalid()) return ExprError();
11587     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11588       if (Input.get()->getValueKind() != VK_RValue &&
11589           Input.get()->getObjectKind() == OK_Ordinary)
11590         VK = Input.get()->getValueKind();
11591     } else if (!getLangOpts().CPlusPlus) {
11592       // In C, a volatile scalar is read by __imag. In C++, it is not.
11593       Input = DefaultLvalueConversion(Input.get());
11594     }
11595     break;
11596   case UO_Extension:
11597   case UO_Coawait:
11598     resultType = Input.get()->getType();
11599     VK = Input.get()->getValueKind();
11600     OK = Input.get()->getObjectKind();
11601     break;
11602   }
11603   if (resultType.isNull() || Input.isInvalid())
11604     return ExprError();
11605 
11606   // Check for array bounds violations in the operand of the UnaryOperator,
11607   // except for the '*' and '&' operators that have to be handled specially
11608   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11609   // that are explicitly defined as valid by the standard).
11610   if (Opc != UO_AddrOf && Opc != UO_Deref)
11611     CheckArrayAccess(Input.get());
11612 
11613   return new (Context)
11614       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11615 }
11616 
11617 /// \brief Determine whether the given expression is a qualified member
11618 /// access expression, of a form that could be turned into a pointer to member
11619 /// with the address-of operator.
11620 static bool isQualifiedMemberAccess(Expr *E) {
11621   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11622     if (!DRE->getQualifier())
11623       return false;
11624 
11625     ValueDecl *VD = DRE->getDecl();
11626     if (!VD->isCXXClassMember())
11627       return false;
11628 
11629     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11630       return true;
11631     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11632       return Method->isInstance();
11633 
11634     return false;
11635   }
11636 
11637   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11638     if (!ULE->getQualifier())
11639       return false;
11640 
11641     for (NamedDecl *D : ULE->decls()) {
11642       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11643         if (Method->isInstance())
11644           return true;
11645       } else {
11646         // Overload set does not contain methods.
11647         break;
11648       }
11649     }
11650 
11651     return false;
11652   }
11653 
11654   return false;
11655 }
11656 
11657 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11658                               UnaryOperatorKind Opc, Expr *Input) {
11659   // First things first: handle placeholders so that the
11660   // overloaded-operator check considers the right type.
11661   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11662     // Increment and decrement of pseudo-object references.
11663     if (pty->getKind() == BuiltinType::PseudoObject &&
11664         UnaryOperator::isIncrementDecrementOp(Opc))
11665       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11666 
11667     // extension is always a builtin operator.
11668     if (Opc == UO_Extension)
11669       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11670 
11671     // & gets special logic for several kinds of placeholder.
11672     // The builtin code knows what to do.
11673     if (Opc == UO_AddrOf &&
11674         (pty->getKind() == BuiltinType::Overload ||
11675          pty->getKind() == BuiltinType::UnknownAny ||
11676          pty->getKind() == BuiltinType::BoundMember))
11677       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11678 
11679     // Anything else needs to be handled now.
11680     ExprResult Result = CheckPlaceholderExpr(Input);
11681     if (Result.isInvalid()) return ExprError();
11682     Input = Result.get();
11683   }
11684 
11685   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11686       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11687       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11688     // Find all of the overloaded operators visible from this
11689     // point. We perform both an operator-name lookup from the local
11690     // scope and an argument-dependent lookup based on the types of
11691     // the arguments.
11692     UnresolvedSet<16> Functions;
11693     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11694     if (S && OverOp != OO_None)
11695       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11696                                    Functions);
11697 
11698     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11699   }
11700 
11701   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11702 }
11703 
11704 // Unary Operators.  'Tok' is the token for the operator.
11705 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11706                               tok::TokenKind Op, Expr *Input) {
11707   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11708 }
11709 
11710 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11711 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11712                                 LabelDecl *TheDecl) {
11713   TheDecl->markUsed(Context);
11714   // Create the AST node.  The address of a label always has type 'void*'.
11715   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11716                                      Context.getPointerType(Context.VoidTy));
11717 }
11718 
11719 /// Given the last statement in a statement-expression, check whether
11720 /// the result is a producing expression (like a call to an
11721 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11722 /// release out of the full-expression.  Otherwise, return null.
11723 /// Cannot fail.
11724 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11725   // Should always be wrapped with one of these.
11726   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11727   if (!cleanups) return nullptr;
11728 
11729   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11730   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11731     return nullptr;
11732 
11733   // Splice out the cast.  This shouldn't modify any interesting
11734   // features of the statement.
11735   Expr *producer = cast->getSubExpr();
11736   assert(producer->getType() == cast->getType());
11737   assert(producer->getValueKind() == cast->getValueKind());
11738   cleanups->setSubExpr(producer);
11739   return cleanups;
11740 }
11741 
11742 void Sema::ActOnStartStmtExpr() {
11743   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11744 }
11745 
11746 void Sema::ActOnStmtExprError() {
11747   // Note that function is also called by TreeTransform when leaving a
11748   // StmtExpr scope without rebuilding anything.
11749 
11750   DiscardCleanupsInEvaluationContext();
11751   PopExpressionEvaluationContext();
11752 }
11753 
11754 ExprResult
11755 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11756                     SourceLocation RPLoc) { // "({..})"
11757   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11758   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11759 
11760   if (hasAnyUnrecoverableErrorsInThisFunction())
11761     DiscardCleanupsInEvaluationContext();
11762   assert(!Cleanup.exprNeedsCleanups() &&
11763          "cleanups within StmtExpr not correctly bound!");
11764   PopExpressionEvaluationContext();
11765 
11766   // FIXME: there are a variety of strange constraints to enforce here, for
11767   // example, it is not possible to goto into a stmt expression apparently.
11768   // More semantic analysis is needed.
11769 
11770   // If there are sub-stmts in the compound stmt, take the type of the last one
11771   // as the type of the stmtexpr.
11772   QualType Ty = Context.VoidTy;
11773   bool StmtExprMayBindToTemp = false;
11774   if (!Compound->body_empty()) {
11775     Stmt *LastStmt = Compound->body_back();
11776     LabelStmt *LastLabelStmt = nullptr;
11777     // If LastStmt is a label, skip down through into the body.
11778     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11779       LastLabelStmt = Label;
11780       LastStmt = Label->getSubStmt();
11781     }
11782 
11783     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11784       // Do function/array conversion on the last expression, but not
11785       // lvalue-to-rvalue.  However, initialize an unqualified type.
11786       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11787       if (LastExpr.isInvalid())
11788         return ExprError();
11789       Ty = LastExpr.get()->getType().getUnqualifiedType();
11790 
11791       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11792         // In ARC, if the final expression ends in a consume, splice
11793         // the consume out and bind it later.  In the alternate case
11794         // (when dealing with a retainable type), the result
11795         // initialization will create a produce.  In both cases the
11796         // result will be +1, and we'll need to balance that out with
11797         // a bind.
11798         if (Expr *rebuiltLastStmt
11799               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11800           LastExpr = rebuiltLastStmt;
11801         } else {
11802           LastExpr = PerformCopyInitialization(
11803                             InitializedEntity::InitializeResult(LPLoc,
11804                                                                 Ty,
11805                                                                 false),
11806                                                    SourceLocation(),
11807                                                LastExpr);
11808         }
11809 
11810         if (LastExpr.isInvalid())
11811           return ExprError();
11812         if (LastExpr.get() != nullptr) {
11813           if (!LastLabelStmt)
11814             Compound->setLastStmt(LastExpr.get());
11815           else
11816             LastLabelStmt->setSubStmt(LastExpr.get());
11817           StmtExprMayBindToTemp = true;
11818         }
11819       }
11820     }
11821   }
11822 
11823   // FIXME: Check that expression type is complete/non-abstract; statement
11824   // expressions are not lvalues.
11825   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11826   if (StmtExprMayBindToTemp)
11827     return MaybeBindToTemporary(ResStmtExpr);
11828   return ResStmtExpr;
11829 }
11830 
11831 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11832                                       TypeSourceInfo *TInfo,
11833                                       ArrayRef<OffsetOfComponent> Components,
11834                                       SourceLocation RParenLoc) {
11835   QualType ArgTy = TInfo->getType();
11836   bool Dependent = ArgTy->isDependentType();
11837   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11838 
11839   // We must have at least one component that refers to the type, and the first
11840   // one is known to be a field designator.  Verify that the ArgTy represents
11841   // a struct/union/class.
11842   if (!Dependent && !ArgTy->isRecordType())
11843     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11844                        << ArgTy << TypeRange);
11845 
11846   // Type must be complete per C99 7.17p3 because a declaring a variable
11847   // with an incomplete type would be ill-formed.
11848   if (!Dependent
11849       && RequireCompleteType(BuiltinLoc, ArgTy,
11850                              diag::err_offsetof_incomplete_type, TypeRange))
11851     return ExprError();
11852 
11853   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11854   // GCC extension, diagnose them.
11855   // FIXME: This diagnostic isn't actually visible because the location is in
11856   // a system header!
11857   if (Components.size() != 1)
11858     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11859       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11860 
11861   bool DidWarnAboutNonPOD = false;
11862   QualType CurrentType = ArgTy;
11863   SmallVector<OffsetOfNode, 4> Comps;
11864   SmallVector<Expr*, 4> Exprs;
11865   for (const OffsetOfComponent &OC : Components) {
11866     if (OC.isBrackets) {
11867       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11868       if (!CurrentType->isDependentType()) {
11869         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11870         if(!AT)
11871           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11872                            << CurrentType);
11873         CurrentType = AT->getElementType();
11874       } else
11875         CurrentType = Context.DependentTy;
11876 
11877       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11878       if (IdxRval.isInvalid())
11879         return ExprError();
11880       Expr *Idx = IdxRval.get();
11881 
11882       // The expression must be an integral expression.
11883       // FIXME: An integral constant expression?
11884       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11885           !Idx->getType()->isIntegerType())
11886         return ExprError(Diag(Idx->getLocStart(),
11887                               diag::err_typecheck_subscript_not_integer)
11888                          << Idx->getSourceRange());
11889 
11890       // Record this array index.
11891       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11892       Exprs.push_back(Idx);
11893       continue;
11894     }
11895 
11896     // Offset of a field.
11897     if (CurrentType->isDependentType()) {
11898       // We have the offset of a field, but we can't look into the dependent
11899       // type. Just record the identifier of the field.
11900       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11901       CurrentType = Context.DependentTy;
11902       continue;
11903     }
11904 
11905     // We need to have a complete type to look into.
11906     if (RequireCompleteType(OC.LocStart, CurrentType,
11907                             diag::err_offsetof_incomplete_type))
11908       return ExprError();
11909 
11910     // Look for the designated field.
11911     const RecordType *RC = CurrentType->getAs<RecordType>();
11912     if (!RC)
11913       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11914                        << CurrentType);
11915     RecordDecl *RD = RC->getDecl();
11916 
11917     // C++ [lib.support.types]p5:
11918     //   The macro offsetof accepts a restricted set of type arguments in this
11919     //   International Standard. type shall be a POD structure or a POD union
11920     //   (clause 9).
11921     // C++11 [support.types]p4:
11922     //   If type is not a standard-layout class (Clause 9), the results are
11923     //   undefined.
11924     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11925       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11926       unsigned DiagID =
11927         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11928                             : diag::ext_offsetof_non_pod_type;
11929 
11930       if (!IsSafe && !DidWarnAboutNonPOD &&
11931           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11932                               PDiag(DiagID)
11933                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11934                               << CurrentType))
11935         DidWarnAboutNonPOD = true;
11936     }
11937 
11938     // Look for the field.
11939     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11940     LookupQualifiedName(R, RD);
11941     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11942     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11943     if (!MemberDecl) {
11944       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11945         MemberDecl = IndirectMemberDecl->getAnonField();
11946     }
11947 
11948     if (!MemberDecl)
11949       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11950                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11951                                                               OC.LocEnd));
11952 
11953     // C99 7.17p3:
11954     //   (If the specified member is a bit-field, the behavior is undefined.)
11955     //
11956     // We diagnose this as an error.
11957     if (MemberDecl->isBitField()) {
11958       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11959         << MemberDecl->getDeclName()
11960         << SourceRange(BuiltinLoc, RParenLoc);
11961       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11962       return ExprError();
11963     }
11964 
11965     RecordDecl *Parent = MemberDecl->getParent();
11966     if (IndirectMemberDecl)
11967       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11968 
11969     // If the member was found in a base class, introduce OffsetOfNodes for
11970     // the base class indirections.
11971     CXXBasePaths Paths;
11972     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11973                       Paths)) {
11974       if (Paths.getDetectedVirtual()) {
11975         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11976           << MemberDecl->getDeclName()
11977           << SourceRange(BuiltinLoc, RParenLoc);
11978         return ExprError();
11979       }
11980 
11981       CXXBasePath &Path = Paths.front();
11982       for (const CXXBasePathElement &B : Path)
11983         Comps.push_back(OffsetOfNode(B.Base));
11984     }
11985 
11986     if (IndirectMemberDecl) {
11987       for (auto *FI : IndirectMemberDecl->chain()) {
11988         assert(isa<FieldDecl>(FI));
11989         Comps.push_back(OffsetOfNode(OC.LocStart,
11990                                      cast<FieldDecl>(FI), OC.LocEnd));
11991       }
11992     } else
11993       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11994 
11995     CurrentType = MemberDecl->getType().getNonReferenceType();
11996   }
11997 
11998   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11999                               Comps, Exprs, RParenLoc);
12000 }
12001 
12002 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12003                                       SourceLocation BuiltinLoc,
12004                                       SourceLocation TypeLoc,
12005                                       ParsedType ParsedArgTy,
12006                                       ArrayRef<OffsetOfComponent> Components,
12007                                       SourceLocation RParenLoc) {
12008 
12009   TypeSourceInfo *ArgTInfo;
12010   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12011   if (ArgTy.isNull())
12012     return ExprError();
12013 
12014   if (!ArgTInfo)
12015     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12016 
12017   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12018 }
12019 
12020 
12021 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12022                                  Expr *CondExpr,
12023                                  Expr *LHSExpr, Expr *RHSExpr,
12024                                  SourceLocation RPLoc) {
12025   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12026 
12027   ExprValueKind VK = VK_RValue;
12028   ExprObjectKind OK = OK_Ordinary;
12029   QualType resType;
12030   bool ValueDependent = false;
12031   bool CondIsTrue = false;
12032   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12033     resType = Context.DependentTy;
12034     ValueDependent = true;
12035   } else {
12036     // The conditional expression is required to be a constant expression.
12037     llvm::APSInt condEval(32);
12038     ExprResult CondICE
12039       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12040           diag::err_typecheck_choose_expr_requires_constant, false);
12041     if (CondICE.isInvalid())
12042       return ExprError();
12043     CondExpr = CondICE.get();
12044     CondIsTrue = condEval.getZExtValue();
12045 
12046     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12047     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12048 
12049     resType = ActiveExpr->getType();
12050     ValueDependent = ActiveExpr->isValueDependent();
12051     VK = ActiveExpr->getValueKind();
12052     OK = ActiveExpr->getObjectKind();
12053   }
12054 
12055   return new (Context)
12056       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12057                  CondIsTrue, resType->isDependentType(), ValueDependent);
12058 }
12059 
12060 //===----------------------------------------------------------------------===//
12061 // Clang Extensions.
12062 //===----------------------------------------------------------------------===//
12063 
12064 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12065 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12066   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12067 
12068   if (LangOpts.CPlusPlus) {
12069     Decl *ManglingContextDecl;
12070     if (MangleNumberingContext *MCtx =
12071             getCurrentMangleNumberContext(Block->getDeclContext(),
12072                                           ManglingContextDecl)) {
12073       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12074       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12075     }
12076   }
12077 
12078   PushBlockScope(CurScope, Block);
12079   CurContext->addDecl(Block);
12080   if (CurScope)
12081     PushDeclContext(CurScope, Block);
12082   else
12083     CurContext = Block;
12084 
12085   getCurBlock()->HasImplicitReturnType = true;
12086 
12087   // Enter a new evaluation context to insulate the block from any
12088   // cleanups from the enclosing full-expression.
12089   PushExpressionEvaluationContext(PotentiallyEvaluated);
12090 }
12091 
12092 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12093                                Scope *CurScope) {
12094   assert(ParamInfo.getIdentifier() == nullptr &&
12095          "block-id should have no identifier!");
12096   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12097   BlockScopeInfo *CurBlock = getCurBlock();
12098 
12099   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12100   QualType T = Sig->getType();
12101 
12102   // FIXME: We should allow unexpanded parameter packs here, but that would,
12103   // in turn, make the block expression contain unexpanded parameter packs.
12104   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12105     // Drop the parameters.
12106     FunctionProtoType::ExtProtoInfo EPI;
12107     EPI.HasTrailingReturn = false;
12108     EPI.TypeQuals |= DeclSpec::TQ_const;
12109     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12110     Sig = Context.getTrivialTypeSourceInfo(T);
12111   }
12112 
12113   // GetTypeForDeclarator always produces a function type for a block
12114   // literal signature.  Furthermore, it is always a FunctionProtoType
12115   // unless the function was written with a typedef.
12116   assert(T->isFunctionType() &&
12117          "GetTypeForDeclarator made a non-function block signature");
12118 
12119   // Look for an explicit signature in that function type.
12120   FunctionProtoTypeLoc ExplicitSignature;
12121 
12122   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12123   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12124 
12125     // Check whether that explicit signature was synthesized by
12126     // GetTypeForDeclarator.  If so, don't save that as part of the
12127     // written signature.
12128     if (ExplicitSignature.getLocalRangeBegin() ==
12129         ExplicitSignature.getLocalRangeEnd()) {
12130       // This would be much cheaper if we stored TypeLocs instead of
12131       // TypeSourceInfos.
12132       TypeLoc Result = ExplicitSignature.getReturnLoc();
12133       unsigned Size = Result.getFullDataSize();
12134       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12135       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12136 
12137       ExplicitSignature = FunctionProtoTypeLoc();
12138     }
12139   }
12140 
12141   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12142   CurBlock->FunctionType = T;
12143 
12144   const FunctionType *Fn = T->getAs<FunctionType>();
12145   QualType RetTy = Fn->getReturnType();
12146   bool isVariadic =
12147     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12148 
12149   CurBlock->TheDecl->setIsVariadic(isVariadic);
12150 
12151   // Context.DependentTy is used as a placeholder for a missing block
12152   // return type.  TODO:  what should we do with declarators like:
12153   //   ^ * { ... }
12154   // If the answer is "apply template argument deduction"....
12155   if (RetTy != Context.DependentTy) {
12156     CurBlock->ReturnType = RetTy;
12157     CurBlock->TheDecl->setBlockMissingReturnType(false);
12158     CurBlock->HasImplicitReturnType = false;
12159   }
12160 
12161   // Push block parameters from the declarator if we had them.
12162   SmallVector<ParmVarDecl*, 8> Params;
12163   if (ExplicitSignature) {
12164     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12165       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12166       if (Param->getIdentifier() == nullptr &&
12167           !Param->isImplicit() &&
12168           !Param->isInvalidDecl() &&
12169           !getLangOpts().CPlusPlus)
12170         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12171       Params.push_back(Param);
12172     }
12173 
12174   // Fake up parameter variables if we have a typedef, like
12175   //   ^ fntype { ... }
12176   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12177     for (const auto &I : Fn->param_types()) {
12178       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12179           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12180       Params.push_back(Param);
12181     }
12182   }
12183 
12184   // Set the parameters on the block decl.
12185   if (!Params.empty()) {
12186     CurBlock->TheDecl->setParams(Params);
12187     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12188                              /*CheckParameterNames=*/false);
12189   }
12190 
12191   // Finally we can process decl attributes.
12192   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12193 
12194   // Put the parameter variables in scope.
12195   for (auto AI : CurBlock->TheDecl->parameters()) {
12196     AI->setOwningFunction(CurBlock->TheDecl);
12197 
12198     // If this has an identifier, add it to the scope stack.
12199     if (AI->getIdentifier()) {
12200       CheckShadow(CurBlock->TheScope, AI);
12201 
12202       PushOnScopeChains(AI, CurBlock->TheScope);
12203     }
12204   }
12205 }
12206 
12207 /// ActOnBlockError - If there is an error parsing a block, this callback
12208 /// is invoked to pop the information about the block from the action impl.
12209 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12210   // Leave the expression-evaluation context.
12211   DiscardCleanupsInEvaluationContext();
12212   PopExpressionEvaluationContext();
12213 
12214   // Pop off CurBlock, handle nested blocks.
12215   PopDeclContext();
12216   PopFunctionScopeInfo();
12217 }
12218 
12219 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12220 /// literal was successfully completed.  ^(int x){...}
12221 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12222                                     Stmt *Body, Scope *CurScope) {
12223   // If blocks are disabled, emit an error.
12224   if (!LangOpts.Blocks)
12225     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12226 
12227   // Leave the expression-evaluation context.
12228   if (hasAnyUnrecoverableErrorsInThisFunction())
12229     DiscardCleanupsInEvaluationContext();
12230   assert(!Cleanup.exprNeedsCleanups() &&
12231          "cleanups within block not correctly bound!");
12232   PopExpressionEvaluationContext();
12233 
12234   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12235 
12236   if (BSI->HasImplicitReturnType)
12237     deduceClosureReturnType(*BSI);
12238 
12239   PopDeclContext();
12240 
12241   QualType RetTy = Context.VoidTy;
12242   if (!BSI->ReturnType.isNull())
12243     RetTy = BSI->ReturnType;
12244 
12245   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12246   QualType BlockTy;
12247 
12248   // Set the captured variables on the block.
12249   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12250   SmallVector<BlockDecl::Capture, 4> Captures;
12251   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12252     if (Cap.isThisCapture())
12253       continue;
12254     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12255                               Cap.isNested(), Cap.getInitExpr());
12256     Captures.push_back(NewCap);
12257   }
12258   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12259 
12260   // If the user wrote a function type in some form, try to use that.
12261   if (!BSI->FunctionType.isNull()) {
12262     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12263 
12264     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12265     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12266 
12267     // Turn protoless block types into nullary block types.
12268     if (isa<FunctionNoProtoType>(FTy)) {
12269       FunctionProtoType::ExtProtoInfo EPI;
12270       EPI.ExtInfo = Ext;
12271       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12272 
12273     // Otherwise, if we don't need to change anything about the function type,
12274     // preserve its sugar structure.
12275     } else if (FTy->getReturnType() == RetTy &&
12276                (!NoReturn || FTy->getNoReturnAttr())) {
12277       BlockTy = BSI->FunctionType;
12278 
12279     // Otherwise, make the minimal modifications to the function type.
12280     } else {
12281       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12282       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12283       EPI.TypeQuals = 0; // FIXME: silently?
12284       EPI.ExtInfo = Ext;
12285       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12286     }
12287 
12288   // If we don't have a function type, just build one from nothing.
12289   } else {
12290     FunctionProtoType::ExtProtoInfo EPI;
12291     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12292     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12293   }
12294 
12295   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12296   BlockTy = Context.getBlockPointerType(BlockTy);
12297 
12298   // If needed, diagnose invalid gotos and switches in the block.
12299   if (getCurFunction()->NeedsScopeChecking() &&
12300       !PP.isCodeCompletionEnabled())
12301     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12302 
12303   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12304 
12305   // Try to apply the named return value optimization. We have to check again
12306   // if we can do this, though, because blocks keep return statements around
12307   // to deduce an implicit return type.
12308   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12309       !BSI->TheDecl->isDependentContext())
12310     computeNRVO(Body, BSI);
12311 
12312   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12313   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12314   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12315 
12316   // If the block isn't obviously global, i.e. it captures anything at
12317   // all, then we need to do a few things in the surrounding context:
12318   if (Result->getBlockDecl()->hasCaptures()) {
12319     // First, this expression has a new cleanup object.
12320     ExprCleanupObjects.push_back(Result->getBlockDecl());
12321     Cleanup.setExprNeedsCleanups(true);
12322 
12323     // It also gets a branch-protected scope if any of the captured
12324     // variables needs destruction.
12325     for (const auto &CI : Result->getBlockDecl()->captures()) {
12326       const VarDecl *var = CI.getVariable();
12327       if (var->getType().isDestructedType() != QualType::DK_none) {
12328         getCurFunction()->setHasBranchProtectedScope();
12329         break;
12330       }
12331     }
12332   }
12333 
12334   return Result;
12335 }
12336 
12337 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12338                             SourceLocation RPLoc) {
12339   TypeSourceInfo *TInfo;
12340   GetTypeFromParser(Ty, &TInfo);
12341   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12342 }
12343 
12344 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12345                                 Expr *E, TypeSourceInfo *TInfo,
12346                                 SourceLocation RPLoc) {
12347   Expr *OrigExpr = E;
12348   bool IsMS = false;
12349 
12350   // CUDA device code does not support varargs.
12351   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12352     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12353       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12354       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12355         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12356     }
12357   }
12358 
12359   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12360   // as Microsoft ABI on an actual Microsoft platform, where
12361   // __builtin_ms_va_list and __builtin_va_list are the same.)
12362   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12363       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12364     QualType MSVaListType = Context.getBuiltinMSVaListType();
12365     if (Context.hasSameType(MSVaListType, E->getType())) {
12366       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12367         return ExprError();
12368       IsMS = true;
12369     }
12370   }
12371 
12372   // Get the va_list type
12373   QualType VaListType = Context.getBuiltinVaListType();
12374   if (!IsMS) {
12375     if (VaListType->isArrayType()) {
12376       // Deal with implicit array decay; for example, on x86-64,
12377       // va_list is an array, but it's supposed to decay to
12378       // a pointer for va_arg.
12379       VaListType = Context.getArrayDecayedType(VaListType);
12380       // Make sure the input expression also decays appropriately.
12381       ExprResult Result = UsualUnaryConversions(E);
12382       if (Result.isInvalid())
12383         return ExprError();
12384       E = Result.get();
12385     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12386       // If va_list is a record type and we are compiling in C++ mode,
12387       // check the argument using reference binding.
12388       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12389           Context, Context.getLValueReferenceType(VaListType), false);
12390       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12391       if (Init.isInvalid())
12392         return ExprError();
12393       E = Init.getAs<Expr>();
12394     } else {
12395       // Otherwise, the va_list argument must be an l-value because
12396       // it is modified by va_arg.
12397       if (!E->isTypeDependent() &&
12398           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12399         return ExprError();
12400     }
12401   }
12402 
12403   if (!IsMS && !E->isTypeDependent() &&
12404       !Context.hasSameType(VaListType, E->getType()))
12405     return ExprError(Diag(E->getLocStart(),
12406                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12407       << OrigExpr->getType() << E->getSourceRange());
12408 
12409   if (!TInfo->getType()->isDependentType()) {
12410     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12411                             diag::err_second_parameter_to_va_arg_incomplete,
12412                             TInfo->getTypeLoc()))
12413       return ExprError();
12414 
12415     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12416                                TInfo->getType(),
12417                                diag::err_second_parameter_to_va_arg_abstract,
12418                                TInfo->getTypeLoc()))
12419       return ExprError();
12420 
12421     if (!TInfo->getType().isPODType(Context)) {
12422       Diag(TInfo->getTypeLoc().getBeginLoc(),
12423            TInfo->getType()->isObjCLifetimeType()
12424              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12425              : diag::warn_second_parameter_to_va_arg_not_pod)
12426         << TInfo->getType()
12427         << TInfo->getTypeLoc().getSourceRange();
12428     }
12429 
12430     // Check for va_arg where arguments of the given type will be promoted
12431     // (i.e. this va_arg is guaranteed to have undefined behavior).
12432     QualType PromoteType;
12433     if (TInfo->getType()->isPromotableIntegerType()) {
12434       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12435       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12436         PromoteType = QualType();
12437     }
12438     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12439       PromoteType = Context.DoubleTy;
12440     if (!PromoteType.isNull())
12441       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12442                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12443                           << TInfo->getType()
12444                           << PromoteType
12445                           << TInfo->getTypeLoc().getSourceRange());
12446   }
12447 
12448   QualType T = TInfo->getType().getNonLValueExprType(Context);
12449   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12450 }
12451 
12452 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12453   // The type of __null will be int or long, depending on the size of
12454   // pointers on the target.
12455   QualType Ty;
12456   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12457   if (pw == Context.getTargetInfo().getIntWidth())
12458     Ty = Context.IntTy;
12459   else if (pw == Context.getTargetInfo().getLongWidth())
12460     Ty = Context.LongTy;
12461   else if (pw == Context.getTargetInfo().getLongLongWidth())
12462     Ty = Context.LongLongTy;
12463   else {
12464     llvm_unreachable("I don't know size of pointer!");
12465   }
12466 
12467   return new (Context) GNUNullExpr(Ty, TokenLoc);
12468 }
12469 
12470 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12471                                               bool Diagnose) {
12472   if (!getLangOpts().ObjC1)
12473     return false;
12474 
12475   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12476   if (!PT)
12477     return false;
12478 
12479   if (!PT->isObjCIdType()) {
12480     // Check if the destination is the 'NSString' interface.
12481     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12482     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12483       return false;
12484   }
12485 
12486   // Ignore any parens, implicit casts (should only be
12487   // array-to-pointer decays), and not-so-opaque values.  The last is
12488   // important for making this trigger for property assignments.
12489   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12490   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12491     if (OV->getSourceExpr())
12492       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12493 
12494   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12495   if (!SL || !SL->isAscii())
12496     return false;
12497   if (Diagnose) {
12498     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12499       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12500     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12501   }
12502   return true;
12503 }
12504 
12505 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12506                                               const Expr *SrcExpr) {
12507   if (!DstType->isFunctionPointerType() ||
12508       !SrcExpr->getType()->isFunctionType())
12509     return false;
12510 
12511   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12512   if (!DRE)
12513     return false;
12514 
12515   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12516   if (!FD)
12517     return false;
12518 
12519   return !S.checkAddressOfFunctionIsAvailable(FD,
12520                                               /*Complain=*/true,
12521                                               SrcExpr->getLocStart());
12522 }
12523 
12524 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12525                                     SourceLocation Loc,
12526                                     QualType DstType, QualType SrcType,
12527                                     Expr *SrcExpr, AssignmentAction Action,
12528                                     bool *Complained) {
12529   if (Complained)
12530     *Complained = false;
12531 
12532   // Decode the result (notice that AST's are still created for extensions).
12533   bool CheckInferredResultType = false;
12534   bool isInvalid = false;
12535   unsigned DiagKind = 0;
12536   FixItHint Hint;
12537   ConversionFixItGenerator ConvHints;
12538   bool MayHaveConvFixit = false;
12539   bool MayHaveFunctionDiff = false;
12540   const ObjCInterfaceDecl *IFace = nullptr;
12541   const ObjCProtocolDecl *PDecl = nullptr;
12542 
12543   switch (ConvTy) {
12544   case Compatible:
12545       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12546       return false;
12547 
12548   case PointerToInt:
12549     DiagKind = diag::ext_typecheck_convert_pointer_int;
12550     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12551     MayHaveConvFixit = true;
12552     break;
12553   case IntToPointer:
12554     DiagKind = diag::ext_typecheck_convert_int_pointer;
12555     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12556     MayHaveConvFixit = true;
12557     break;
12558   case IncompatiblePointer:
12559     if (Action == AA_Passing_CFAudited)
12560       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12561     else if (SrcType->isFunctionPointerType() &&
12562              DstType->isFunctionPointerType())
12563       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12564     else
12565       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12566 
12567     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12568       SrcType->isObjCObjectPointerType();
12569     if (Hint.isNull() && !CheckInferredResultType) {
12570       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12571     }
12572     else if (CheckInferredResultType) {
12573       SrcType = SrcType.getUnqualifiedType();
12574       DstType = DstType.getUnqualifiedType();
12575     }
12576     MayHaveConvFixit = true;
12577     break;
12578   case IncompatiblePointerSign:
12579     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12580     break;
12581   case FunctionVoidPointer:
12582     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12583     break;
12584   case IncompatiblePointerDiscardsQualifiers: {
12585     // Perform array-to-pointer decay if necessary.
12586     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12587 
12588     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12589     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12590     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12591       DiagKind = diag::err_typecheck_incompatible_address_space;
12592       break;
12593 
12594 
12595     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12596       DiagKind = diag::err_typecheck_incompatible_ownership;
12597       break;
12598     }
12599 
12600     llvm_unreachable("unknown error case for discarding qualifiers!");
12601     // fallthrough
12602   }
12603   case CompatiblePointerDiscardsQualifiers:
12604     // If the qualifiers lost were because we were applying the
12605     // (deprecated) C++ conversion from a string literal to a char*
12606     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12607     // Ideally, this check would be performed in
12608     // checkPointerTypesForAssignment. However, that would require a
12609     // bit of refactoring (so that the second argument is an
12610     // expression, rather than a type), which should be done as part
12611     // of a larger effort to fix checkPointerTypesForAssignment for
12612     // C++ semantics.
12613     if (getLangOpts().CPlusPlus &&
12614         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12615       return false;
12616     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12617     break;
12618   case IncompatibleNestedPointerQualifiers:
12619     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12620     break;
12621   case IntToBlockPointer:
12622     DiagKind = diag::err_int_to_block_pointer;
12623     break;
12624   case IncompatibleBlockPointer:
12625     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12626     break;
12627   case IncompatibleObjCQualifiedId: {
12628     if (SrcType->isObjCQualifiedIdType()) {
12629       const ObjCObjectPointerType *srcOPT =
12630                 SrcType->getAs<ObjCObjectPointerType>();
12631       for (auto *srcProto : srcOPT->quals()) {
12632         PDecl = srcProto;
12633         break;
12634       }
12635       if (const ObjCInterfaceType *IFaceT =
12636             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12637         IFace = IFaceT->getDecl();
12638     }
12639     else if (DstType->isObjCQualifiedIdType()) {
12640       const ObjCObjectPointerType *dstOPT =
12641         DstType->getAs<ObjCObjectPointerType>();
12642       for (auto *dstProto : dstOPT->quals()) {
12643         PDecl = dstProto;
12644         break;
12645       }
12646       if (const ObjCInterfaceType *IFaceT =
12647             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12648         IFace = IFaceT->getDecl();
12649     }
12650     DiagKind = diag::warn_incompatible_qualified_id;
12651     break;
12652   }
12653   case IncompatibleVectors:
12654     DiagKind = diag::warn_incompatible_vectors;
12655     break;
12656   case IncompatibleObjCWeakRef:
12657     DiagKind = diag::err_arc_weak_unavailable_assign;
12658     break;
12659   case Incompatible:
12660     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12661       if (Complained)
12662         *Complained = true;
12663       return true;
12664     }
12665 
12666     DiagKind = diag::err_typecheck_convert_incompatible;
12667     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12668     MayHaveConvFixit = true;
12669     isInvalid = true;
12670     MayHaveFunctionDiff = true;
12671     break;
12672   }
12673 
12674   QualType FirstType, SecondType;
12675   switch (Action) {
12676   case AA_Assigning:
12677   case AA_Initializing:
12678     // The destination type comes first.
12679     FirstType = DstType;
12680     SecondType = SrcType;
12681     break;
12682 
12683   case AA_Returning:
12684   case AA_Passing:
12685   case AA_Passing_CFAudited:
12686   case AA_Converting:
12687   case AA_Sending:
12688   case AA_Casting:
12689     // The source type comes first.
12690     FirstType = SrcType;
12691     SecondType = DstType;
12692     break;
12693   }
12694 
12695   PartialDiagnostic FDiag = PDiag(DiagKind);
12696   if (Action == AA_Passing_CFAudited)
12697     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12698   else
12699     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12700 
12701   // If we can fix the conversion, suggest the FixIts.
12702   assert(ConvHints.isNull() || Hint.isNull());
12703   if (!ConvHints.isNull()) {
12704     for (FixItHint &H : ConvHints.Hints)
12705       FDiag << H;
12706   } else {
12707     FDiag << Hint;
12708   }
12709   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12710 
12711   if (MayHaveFunctionDiff)
12712     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12713 
12714   Diag(Loc, FDiag);
12715   if (DiagKind == diag::warn_incompatible_qualified_id &&
12716       PDecl && IFace && !IFace->hasDefinition())
12717       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12718         << IFace->getName() << PDecl->getName();
12719 
12720   if (SecondType == Context.OverloadTy)
12721     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12722                               FirstType, /*TakingAddress=*/true);
12723 
12724   if (CheckInferredResultType)
12725     EmitRelatedResultTypeNote(SrcExpr);
12726 
12727   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12728     EmitRelatedResultTypeNoteForReturn(DstType);
12729 
12730   if (Complained)
12731     *Complained = true;
12732   return isInvalid;
12733 }
12734 
12735 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12736                                                  llvm::APSInt *Result) {
12737   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12738   public:
12739     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12740       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12741     }
12742   } Diagnoser;
12743 
12744   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12745 }
12746 
12747 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12748                                                  llvm::APSInt *Result,
12749                                                  unsigned DiagID,
12750                                                  bool AllowFold) {
12751   class IDDiagnoser : public VerifyICEDiagnoser {
12752     unsigned DiagID;
12753 
12754   public:
12755     IDDiagnoser(unsigned DiagID)
12756       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12757 
12758     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12759       S.Diag(Loc, DiagID) << SR;
12760     }
12761   } Diagnoser(DiagID);
12762 
12763   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12764 }
12765 
12766 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12767                                             SourceRange SR) {
12768   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12769 }
12770 
12771 ExprResult
12772 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12773                                       VerifyICEDiagnoser &Diagnoser,
12774                                       bool AllowFold) {
12775   SourceLocation DiagLoc = E->getLocStart();
12776 
12777   if (getLangOpts().CPlusPlus11) {
12778     // C++11 [expr.const]p5:
12779     //   If an expression of literal class type is used in a context where an
12780     //   integral constant expression is required, then that class type shall
12781     //   have a single non-explicit conversion function to an integral or
12782     //   unscoped enumeration type
12783     ExprResult Converted;
12784     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12785     public:
12786       CXX11ConvertDiagnoser(bool Silent)
12787           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12788                                 Silent, true) {}
12789 
12790       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12791                                            QualType T) override {
12792         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12793       }
12794 
12795       SemaDiagnosticBuilder diagnoseIncomplete(
12796           Sema &S, SourceLocation Loc, QualType T) override {
12797         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12798       }
12799 
12800       SemaDiagnosticBuilder diagnoseExplicitConv(
12801           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12802         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12803       }
12804 
12805       SemaDiagnosticBuilder noteExplicitConv(
12806           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12807         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12808                  << ConvTy->isEnumeralType() << ConvTy;
12809       }
12810 
12811       SemaDiagnosticBuilder diagnoseAmbiguous(
12812           Sema &S, SourceLocation Loc, QualType T) override {
12813         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12814       }
12815 
12816       SemaDiagnosticBuilder noteAmbiguous(
12817           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12818         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12819                  << ConvTy->isEnumeralType() << ConvTy;
12820       }
12821 
12822       SemaDiagnosticBuilder diagnoseConversion(
12823           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12824         llvm_unreachable("conversion functions are permitted");
12825       }
12826     } ConvertDiagnoser(Diagnoser.Suppress);
12827 
12828     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12829                                                     ConvertDiagnoser);
12830     if (Converted.isInvalid())
12831       return Converted;
12832     E = Converted.get();
12833     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12834       return ExprError();
12835   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12836     // An ICE must be of integral or unscoped enumeration type.
12837     if (!Diagnoser.Suppress)
12838       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12839     return ExprError();
12840   }
12841 
12842   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12843   // in the non-ICE case.
12844   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12845     if (Result)
12846       *Result = E->EvaluateKnownConstInt(Context);
12847     return E;
12848   }
12849 
12850   Expr::EvalResult EvalResult;
12851   SmallVector<PartialDiagnosticAt, 8> Notes;
12852   EvalResult.Diag = &Notes;
12853 
12854   // Try to evaluate the expression, and produce diagnostics explaining why it's
12855   // not a constant expression as a side-effect.
12856   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12857                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12858 
12859   // In C++11, we can rely on diagnostics being produced for any expression
12860   // which is not a constant expression. If no diagnostics were produced, then
12861   // this is a constant expression.
12862   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12863     if (Result)
12864       *Result = EvalResult.Val.getInt();
12865     return E;
12866   }
12867 
12868   // If our only note is the usual "invalid subexpression" note, just point
12869   // the caret at its location rather than producing an essentially
12870   // redundant note.
12871   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12872         diag::note_invalid_subexpr_in_const_expr) {
12873     DiagLoc = Notes[0].first;
12874     Notes.clear();
12875   }
12876 
12877   if (!Folded || !AllowFold) {
12878     if (!Diagnoser.Suppress) {
12879       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12880       for (const PartialDiagnosticAt &Note : Notes)
12881         Diag(Note.first, Note.second);
12882     }
12883 
12884     return ExprError();
12885   }
12886 
12887   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12888   for (const PartialDiagnosticAt &Note : Notes)
12889     Diag(Note.first, Note.second);
12890 
12891   if (Result)
12892     *Result = EvalResult.Val.getInt();
12893   return E;
12894 }
12895 
12896 namespace {
12897   // Handle the case where we conclude a expression which we speculatively
12898   // considered to be unevaluated is actually evaluated.
12899   class TransformToPE : public TreeTransform<TransformToPE> {
12900     typedef TreeTransform<TransformToPE> BaseTransform;
12901 
12902   public:
12903     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12904 
12905     // Make sure we redo semantic analysis
12906     bool AlwaysRebuild() { return true; }
12907 
12908     // Make sure we handle LabelStmts correctly.
12909     // FIXME: This does the right thing, but maybe we need a more general
12910     // fix to TreeTransform?
12911     StmtResult TransformLabelStmt(LabelStmt *S) {
12912       S->getDecl()->setStmt(nullptr);
12913       return BaseTransform::TransformLabelStmt(S);
12914     }
12915 
12916     // We need to special-case DeclRefExprs referring to FieldDecls which
12917     // are not part of a member pointer formation; normal TreeTransforming
12918     // doesn't catch this case because of the way we represent them in the AST.
12919     // FIXME: This is a bit ugly; is it really the best way to handle this
12920     // case?
12921     //
12922     // Error on DeclRefExprs referring to FieldDecls.
12923     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12924       if (isa<FieldDecl>(E->getDecl()) &&
12925           !SemaRef.isUnevaluatedContext())
12926         return SemaRef.Diag(E->getLocation(),
12927                             diag::err_invalid_non_static_member_use)
12928             << E->getDecl() << E->getSourceRange();
12929 
12930       return BaseTransform::TransformDeclRefExpr(E);
12931     }
12932 
12933     // Exception: filter out member pointer formation
12934     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12935       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12936         return E;
12937 
12938       return BaseTransform::TransformUnaryOperator(E);
12939     }
12940 
12941     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12942       // Lambdas never need to be transformed.
12943       return E;
12944     }
12945   };
12946 }
12947 
12948 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12949   assert(isUnevaluatedContext() &&
12950          "Should only transform unevaluated expressions");
12951   ExprEvalContexts.back().Context =
12952       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12953   if (isUnevaluatedContext())
12954     return E;
12955   return TransformToPE(*this).TransformExpr(E);
12956 }
12957 
12958 void
12959 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12960                                       Decl *LambdaContextDecl,
12961                                       bool IsDecltype) {
12962   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
12963                                 LambdaContextDecl, IsDecltype);
12964   Cleanup.reset();
12965   if (!MaybeODRUseExprs.empty())
12966     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12967 }
12968 
12969 void
12970 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12971                                       ReuseLambdaContextDecl_t,
12972                                       bool IsDecltype) {
12973   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12974   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12975 }
12976 
12977 void Sema::PopExpressionEvaluationContext() {
12978   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12979   unsigned NumTypos = Rec.NumTypos;
12980 
12981   if (!Rec.Lambdas.empty()) {
12982     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12983       unsigned D;
12984       if (Rec.isUnevaluated()) {
12985         // C++11 [expr.prim.lambda]p2:
12986         //   A lambda-expression shall not appear in an unevaluated operand
12987         //   (Clause 5).
12988         D = diag::err_lambda_unevaluated_operand;
12989       } else {
12990         // C++1y [expr.const]p2:
12991         //   A conditional-expression e is a core constant expression unless the
12992         //   evaluation of e, following the rules of the abstract machine, would
12993         //   evaluate [...] a lambda-expression.
12994         D = diag::err_lambda_in_constant_expression;
12995       }
12996       for (const auto *L : Rec.Lambdas)
12997         Diag(L->getLocStart(), D);
12998     } else {
12999       // Mark the capture expressions odr-used. This was deferred
13000       // during lambda expression creation.
13001       for (auto *Lambda : Rec.Lambdas) {
13002         for (auto *C : Lambda->capture_inits())
13003           MarkDeclarationsReferencedInExpr(C);
13004       }
13005     }
13006   }
13007 
13008   // When are coming out of an unevaluated context, clear out any
13009   // temporaries that we may have created as part of the evaluation of
13010   // the expression in that context: they aren't relevant because they
13011   // will never be constructed.
13012   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13013     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13014                              ExprCleanupObjects.end());
13015     Cleanup = Rec.ParentCleanup;
13016     CleanupVarDeclMarking();
13017     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13018   // Otherwise, merge the contexts together.
13019   } else {
13020     Cleanup.mergeFrom(Rec.ParentCleanup);
13021     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13022                             Rec.SavedMaybeODRUseExprs.end());
13023   }
13024 
13025   // Pop the current expression evaluation context off the stack.
13026   ExprEvalContexts.pop_back();
13027 
13028   if (!ExprEvalContexts.empty())
13029     ExprEvalContexts.back().NumTypos += NumTypos;
13030   else
13031     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13032                             "last ExpressionEvaluationContextRecord");
13033 }
13034 
13035 void Sema::DiscardCleanupsInEvaluationContext() {
13036   ExprCleanupObjects.erase(
13037          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13038          ExprCleanupObjects.end());
13039   Cleanup.reset();
13040   MaybeODRUseExprs.clear();
13041 }
13042 
13043 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13044   if (!E->getType()->isVariablyModifiedType())
13045     return E;
13046   return TransformToPotentiallyEvaluated(E);
13047 }
13048 
13049 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
13050   // Do not mark anything as "used" within a dependent context; wait for
13051   // an instantiation.
13052   if (SemaRef.CurContext->isDependentContext())
13053     return false;
13054 
13055   switch (SemaRef.ExprEvalContexts.back().Context) {
13056     case Sema::Unevaluated:
13057     case Sema::UnevaluatedAbstract:
13058       // We are in an expression that is not potentially evaluated; do nothing.
13059       // (Depending on how you read the standard, we actually do need to do
13060       // something here for null pointer constants, but the standard's
13061       // definition of a null pointer constant is completely crazy.)
13062       return false;
13063 
13064     case Sema::DiscardedStatement:
13065       // These are technically a potentially evaluated but they have the effect
13066       // of suppressing use marking.
13067       return false;
13068 
13069     case Sema::ConstantEvaluated:
13070     case Sema::PotentiallyEvaluated:
13071       // We are in a potentially evaluated expression (or a constant-expression
13072       // in C++03); we need to do implicit template instantiation, implicitly
13073       // define class members, and mark most declarations as used.
13074       return true;
13075 
13076     case Sema::PotentiallyEvaluatedIfUsed:
13077       // Referenced declarations will only be used if the construct in the
13078       // containing expression is used.
13079       return false;
13080   }
13081   llvm_unreachable("Invalid context");
13082 }
13083 
13084 /// \brief Mark a function referenced, and check whether it is odr-used
13085 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13086 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13087                                   bool MightBeOdrUse) {
13088   assert(Func && "No function?");
13089 
13090   Func->setReferenced();
13091 
13092   // C++11 [basic.def.odr]p3:
13093   //   A function whose name appears as a potentially-evaluated expression is
13094   //   odr-used if it is the unique lookup result or the selected member of a
13095   //   set of overloaded functions [...].
13096   //
13097   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13098   // can just check that here.
13099   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13100 
13101   // Determine whether we require a function definition to exist, per
13102   // C++11 [temp.inst]p3:
13103   //   Unless a function template specialization has been explicitly
13104   //   instantiated or explicitly specialized, the function template
13105   //   specialization is implicitly instantiated when the specialization is
13106   //   referenced in a context that requires a function definition to exist.
13107   //
13108   // We consider constexpr function templates to be referenced in a context
13109   // that requires a definition to exist whenever they are referenced.
13110   //
13111   // FIXME: This instantiates constexpr functions too frequently. If this is
13112   // really an unevaluated context (and we're not just in the definition of a
13113   // function template or overload resolution or other cases which we
13114   // incorrectly consider to be unevaluated contexts), and we're not in a
13115   // subexpression which we actually need to evaluate (for instance, a
13116   // template argument, array bound or an expression in a braced-init-list),
13117   // we are not permitted to instantiate this constexpr function definition.
13118   //
13119   // FIXME: This also implicitly defines special members too frequently. They
13120   // are only supposed to be implicitly defined if they are odr-used, but they
13121   // are not odr-used from constant expressions in unevaluated contexts.
13122   // However, they cannot be referenced if they are deleted, and they are
13123   // deleted whenever the implicit definition of the special member would
13124   // fail (with very few exceptions).
13125   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13126   bool NeedDefinition =
13127       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13128                                          (MD && !MD->isUserProvided())));
13129 
13130   // C++14 [temp.expl.spec]p6:
13131   //   If a template [...] is explicitly specialized then that specialization
13132   //   shall be declared before the first use of that specialization that would
13133   //   cause an implicit instantiation to take place, in every translation unit
13134   //   in which such a use occurs
13135   if (NeedDefinition &&
13136       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13137        Func->getMemberSpecializationInfo()))
13138     checkSpecializationVisibility(Loc, Func);
13139 
13140   // If we don't need to mark the function as used, and we don't need to
13141   // try to provide a definition, there's nothing more to do.
13142   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13143       (!NeedDefinition || Func->getBody()))
13144     return;
13145 
13146   // Note that this declaration has been used.
13147   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13148     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13149     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13150       if (Constructor->isDefaultConstructor()) {
13151         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13152           return;
13153         DefineImplicitDefaultConstructor(Loc, Constructor);
13154       } else if (Constructor->isCopyConstructor()) {
13155         DefineImplicitCopyConstructor(Loc, Constructor);
13156       } else if (Constructor->isMoveConstructor()) {
13157         DefineImplicitMoveConstructor(Loc, Constructor);
13158       }
13159     } else if (Constructor->getInheritedConstructor()) {
13160       DefineInheritingConstructor(Loc, Constructor);
13161     }
13162   } else if (CXXDestructorDecl *Destructor =
13163                  dyn_cast<CXXDestructorDecl>(Func)) {
13164     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13165     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13166       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13167         return;
13168       DefineImplicitDestructor(Loc, Destructor);
13169     }
13170     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13171       MarkVTableUsed(Loc, Destructor->getParent());
13172   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13173     if (MethodDecl->isOverloadedOperator() &&
13174         MethodDecl->getOverloadedOperator() == OO_Equal) {
13175       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13176       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13177         if (MethodDecl->isCopyAssignmentOperator())
13178           DefineImplicitCopyAssignment(Loc, MethodDecl);
13179         else if (MethodDecl->isMoveAssignmentOperator())
13180           DefineImplicitMoveAssignment(Loc, MethodDecl);
13181       }
13182     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13183                MethodDecl->getParent()->isLambda()) {
13184       CXXConversionDecl *Conversion =
13185           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13186       if (Conversion->isLambdaToBlockPointerConversion())
13187         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13188       else
13189         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13190     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13191       MarkVTableUsed(Loc, MethodDecl->getParent());
13192   }
13193 
13194   // Recursive functions should be marked when used from another function.
13195   // FIXME: Is this really right?
13196   if (CurContext == Func) return;
13197 
13198   // Resolve the exception specification for any function which is
13199   // used: CodeGen will need it.
13200   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13201   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13202     ResolveExceptionSpec(Loc, FPT);
13203 
13204   // Implicit instantiation of function templates and member functions of
13205   // class templates.
13206   if (Func->isImplicitlyInstantiable()) {
13207     bool AlreadyInstantiated = false;
13208     SourceLocation PointOfInstantiation = Loc;
13209     if (FunctionTemplateSpecializationInfo *SpecInfo
13210                               = Func->getTemplateSpecializationInfo()) {
13211       if (SpecInfo->getPointOfInstantiation().isInvalid())
13212         SpecInfo->setPointOfInstantiation(Loc);
13213       else if (SpecInfo->getTemplateSpecializationKind()
13214                  == TSK_ImplicitInstantiation) {
13215         AlreadyInstantiated = true;
13216         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13217       }
13218     } else if (MemberSpecializationInfo *MSInfo
13219                                 = Func->getMemberSpecializationInfo()) {
13220       if (MSInfo->getPointOfInstantiation().isInvalid())
13221         MSInfo->setPointOfInstantiation(Loc);
13222       else if (MSInfo->getTemplateSpecializationKind()
13223                  == TSK_ImplicitInstantiation) {
13224         AlreadyInstantiated = true;
13225         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13226       }
13227     }
13228 
13229     if (!AlreadyInstantiated || Func->isConstexpr()) {
13230       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13231           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13232           ActiveTemplateInstantiations.size())
13233         PendingLocalImplicitInstantiations.push_back(
13234             std::make_pair(Func, PointOfInstantiation));
13235       else if (Func->isConstexpr())
13236         // Do not defer instantiations of constexpr functions, to avoid the
13237         // expression evaluator needing to call back into Sema if it sees a
13238         // call to such a function.
13239         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13240       else {
13241         PendingInstantiations.push_back(std::make_pair(Func,
13242                                                        PointOfInstantiation));
13243         // Notify the consumer that a function was implicitly instantiated.
13244         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13245       }
13246     }
13247   } else {
13248     // Walk redefinitions, as some of them may be instantiable.
13249     for (auto i : Func->redecls()) {
13250       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13251         MarkFunctionReferenced(Loc, i, OdrUse);
13252     }
13253   }
13254 
13255   if (!OdrUse) return;
13256 
13257   // Keep track of used but undefined functions.
13258   if (!Func->isDefined()) {
13259     if (mightHaveNonExternalLinkage(Func))
13260       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13261     else if (Func->getMostRecentDecl()->isInlined() &&
13262              !LangOpts.GNUInline &&
13263              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13264       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13265   }
13266 
13267   Func->markUsed(Context);
13268 }
13269 
13270 static void
13271 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13272                                    ValueDecl *var, DeclContext *DC) {
13273   DeclContext *VarDC = var->getDeclContext();
13274 
13275   //  If the parameter still belongs to the translation unit, then
13276   //  we're actually just using one parameter in the declaration of
13277   //  the next.
13278   if (isa<ParmVarDecl>(var) &&
13279       isa<TranslationUnitDecl>(VarDC))
13280     return;
13281 
13282   // For C code, don't diagnose about capture if we're not actually in code
13283   // right now; it's impossible to write a non-constant expression outside of
13284   // function context, so we'll get other (more useful) diagnostics later.
13285   //
13286   // For C++, things get a bit more nasty... it would be nice to suppress this
13287   // diagnostic for certain cases like using a local variable in an array bound
13288   // for a member of a local class, but the correct predicate is not obvious.
13289   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13290     return;
13291 
13292   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13293   unsigned ContextKind = 3; // unknown
13294   if (isa<CXXMethodDecl>(VarDC) &&
13295       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13296     ContextKind = 2;
13297   } else if (isa<FunctionDecl>(VarDC)) {
13298     ContextKind = 0;
13299   } else if (isa<BlockDecl>(VarDC)) {
13300     ContextKind = 1;
13301   }
13302 
13303   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13304     << var << ValueKind << ContextKind << VarDC;
13305   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13306       << var;
13307 
13308   // FIXME: Add additional diagnostic info about class etc. which prevents
13309   // capture.
13310 }
13311 
13312 
13313 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13314                                       bool &SubCapturesAreNested,
13315                                       QualType &CaptureType,
13316                                       QualType &DeclRefType) {
13317    // Check whether we've already captured it.
13318   if (CSI->CaptureMap.count(Var)) {
13319     // If we found a capture, any subcaptures are nested.
13320     SubCapturesAreNested = true;
13321 
13322     // Retrieve the capture type for this variable.
13323     CaptureType = CSI->getCapture(Var).getCaptureType();
13324 
13325     // Compute the type of an expression that refers to this variable.
13326     DeclRefType = CaptureType.getNonReferenceType();
13327 
13328     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13329     // are mutable in the sense that user can change their value - they are
13330     // private instances of the captured declarations.
13331     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13332     if (Cap.isCopyCapture() &&
13333         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13334         !(isa<CapturedRegionScopeInfo>(CSI) &&
13335           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13336       DeclRefType.addConst();
13337     return true;
13338   }
13339   return false;
13340 }
13341 
13342 // Only block literals, captured statements, and lambda expressions can
13343 // capture; other scopes don't work.
13344 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13345                                  SourceLocation Loc,
13346                                  const bool Diagnose, Sema &S) {
13347   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13348     return getLambdaAwareParentOfDeclContext(DC);
13349   else if (Var->hasLocalStorage()) {
13350     if (Diagnose)
13351        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13352   }
13353   return nullptr;
13354 }
13355 
13356 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13357 // certain types of variables (unnamed, variably modified types etc.)
13358 // so check for eligibility.
13359 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13360                                  SourceLocation Loc,
13361                                  const bool Diagnose, Sema &S) {
13362 
13363   bool IsBlock = isa<BlockScopeInfo>(CSI);
13364   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13365 
13366   // Lambdas are not allowed to capture unnamed variables
13367   // (e.g. anonymous unions).
13368   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13369   // assuming that's the intent.
13370   if (IsLambda && !Var->getDeclName()) {
13371     if (Diagnose) {
13372       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13373       S.Diag(Var->getLocation(), diag::note_declared_at);
13374     }
13375     return false;
13376   }
13377 
13378   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13379   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13380     if (Diagnose) {
13381       S.Diag(Loc, diag::err_ref_vm_type);
13382       S.Diag(Var->getLocation(), diag::note_previous_decl)
13383         << Var->getDeclName();
13384     }
13385     return false;
13386   }
13387   // Prohibit structs with flexible array members too.
13388   // We cannot capture what is in the tail end of the struct.
13389   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13390     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13391       if (Diagnose) {
13392         if (IsBlock)
13393           S.Diag(Loc, diag::err_ref_flexarray_type);
13394         else
13395           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13396             << Var->getDeclName();
13397         S.Diag(Var->getLocation(), diag::note_previous_decl)
13398           << Var->getDeclName();
13399       }
13400       return false;
13401     }
13402   }
13403   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13404   // Lambdas and captured statements are not allowed to capture __block
13405   // variables; they don't support the expected semantics.
13406   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13407     if (Diagnose) {
13408       S.Diag(Loc, diag::err_capture_block_variable)
13409         << Var->getDeclName() << !IsLambda;
13410       S.Diag(Var->getLocation(), diag::note_previous_decl)
13411         << Var->getDeclName();
13412     }
13413     return false;
13414   }
13415 
13416   return true;
13417 }
13418 
13419 // Returns true if the capture by block was successful.
13420 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13421                                  SourceLocation Loc,
13422                                  const bool BuildAndDiagnose,
13423                                  QualType &CaptureType,
13424                                  QualType &DeclRefType,
13425                                  const bool Nested,
13426                                  Sema &S) {
13427   Expr *CopyExpr = nullptr;
13428   bool ByRef = false;
13429 
13430   // Blocks are not allowed to capture arrays.
13431   if (CaptureType->isArrayType()) {
13432     if (BuildAndDiagnose) {
13433       S.Diag(Loc, diag::err_ref_array_type);
13434       S.Diag(Var->getLocation(), diag::note_previous_decl)
13435       << Var->getDeclName();
13436     }
13437     return false;
13438   }
13439 
13440   // Forbid the block-capture of autoreleasing variables.
13441   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13442     if (BuildAndDiagnose) {
13443       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13444         << /*block*/ 0;
13445       S.Diag(Var->getLocation(), diag::note_previous_decl)
13446         << Var->getDeclName();
13447     }
13448     return false;
13449   }
13450   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13451   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13452       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13453     // Block capture by reference does not change the capture or
13454     // declaration reference types.
13455     ByRef = true;
13456   } else {
13457     // Block capture by copy introduces 'const'.
13458     CaptureType = CaptureType.getNonReferenceType().withConst();
13459     DeclRefType = CaptureType;
13460 
13461     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13462       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13463         // The capture logic needs the destructor, so make sure we mark it.
13464         // Usually this is unnecessary because most local variables have
13465         // their destructors marked at declaration time, but parameters are
13466         // an exception because it's technically only the call site that
13467         // actually requires the destructor.
13468         if (isa<ParmVarDecl>(Var))
13469           S.FinalizeVarWithDestructor(Var, Record);
13470 
13471         // Enter a new evaluation context to insulate the copy
13472         // full-expression.
13473         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13474 
13475         // According to the blocks spec, the capture of a variable from
13476         // the stack requires a const copy constructor.  This is not true
13477         // of the copy/move done to move a __block variable to the heap.
13478         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13479                                                   DeclRefType.withConst(),
13480                                                   VK_LValue, Loc);
13481 
13482         ExprResult Result
13483           = S.PerformCopyInitialization(
13484               InitializedEntity::InitializeBlock(Var->getLocation(),
13485                                                   CaptureType, false),
13486               Loc, DeclRef);
13487 
13488         // Build a full-expression copy expression if initialization
13489         // succeeded and used a non-trivial constructor.  Recover from
13490         // errors by pretending that the copy isn't necessary.
13491         if (!Result.isInvalid() &&
13492             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13493                 ->isTrivial()) {
13494           Result = S.MaybeCreateExprWithCleanups(Result);
13495           CopyExpr = Result.get();
13496         }
13497       }
13498     }
13499   }
13500 
13501   // Actually capture the variable.
13502   if (BuildAndDiagnose)
13503     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13504                     SourceLocation(), CaptureType, CopyExpr);
13505 
13506   return true;
13507 
13508 }
13509 
13510 
13511 /// \brief Capture the given variable in the captured region.
13512 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13513                                     VarDecl *Var,
13514                                     SourceLocation Loc,
13515                                     const bool BuildAndDiagnose,
13516                                     QualType &CaptureType,
13517                                     QualType &DeclRefType,
13518                                     const bool RefersToCapturedVariable,
13519                                     Sema &S) {
13520   // By default, capture variables by reference.
13521   bool ByRef = true;
13522   // Using an LValue reference type is consistent with Lambdas (see below).
13523   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13524     if (S.IsOpenMPCapturedDecl(Var))
13525       DeclRefType = DeclRefType.getUnqualifiedType();
13526     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13527   }
13528 
13529   if (ByRef)
13530     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13531   else
13532     CaptureType = DeclRefType;
13533 
13534   Expr *CopyExpr = nullptr;
13535   if (BuildAndDiagnose) {
13536     // The current implementation assumes that all variables are captured
13537     // by references. Since there is no capture by copy, no expression
13538     // evaluation will be needed.
13539     RecordDecl *RD = RSI->TheRecordDecl;
13540 
13541     FieldDecl *Field
13542       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13543                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13544                           nullptr, false, ICIS_NoInit);
13545     Field->setImplicit(true);
13546     Field->setAccess(AS_private);
13547     RD->addDecl(Field);
13548 
13549     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13550                                             DeclRefType, VK_LValue, Loc);
13551     Var->setReferenced(true);
13552     Var->markUsed(S.Context);
13553   }
13554 
13555   // Actually capture the variable.
13556   if (BuildAndDiagnose)
13557     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13558                     SourceLocation(), CaptureType, CopyExpr);
13559 
13560 
13561   return true;
13562 }
13563 
13564 /// \brief Create a field within the lambda class for the variable
13565 /// being captured.
13566 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13567                                     QualType FieldType, QualType DeclRefType,
13568                                     SourceLocation Loc,
13569                                     bool RefersToCapturedVariable) {
13570   CXXRecordDecl *Lambda = LSI->Lambda;
13571 
13572   // Build the non-static data member.
13573   FieldDecl *Field
13574     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13575                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13576                         nullptr, false, ICIS_NoInit);
13577   Field->setImplicit(true);
13578   Field->setAccess(AS_private);
13579   Lambda->addDecl(Field);
13580 }
13581 
13582 /// \brief Capture the given variable in the lambda.
13583 static bool captureInLambda(LambdaScopeInfo *LSI,
13584                             VarDecl *Var,
13585                             SourceLocation Loc,
13586                             const bool BuildAndDiagnose,
13587                             QualType &CaptureType,
13588                             QualType &DeclRefType,
13589                             const bool RefersToCapturedVariable,
13590                             const Sema::TryCaptureKind Kind,
13591                             SourceLocation EllipsisLoc,
13592                             const bool IsTopScope,
13593                             Sema &S) {
13594 
13595   // Determine whether we are capturing by reference or by value.
13596   bool ByRef = false;
13597   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13598     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13599   } else {
13600     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13601   }
13602 
13603   // Compute the type of the field that will capture this variable.
13604   if (ByRef) {
13605     // C++11 [expr.prim.lambda]p15:
13606     //   An entity is captured by reference if it is implicitly or
13607     //   explicitly captured but not captured by copy. It is
13608     //   unspecified whether additional unnamed non-static data
13609     //   members are declared in the closure type for entities
13610     //   captured by reference.
13611     //
13612     // FIXME: It is not clear whether we want to build an lvalue reference
13613     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13614     // to do the former, while EDG does the latter. Core issue 1249 will
13615     // clarify, but for now we follow GCC because it's a more permissive and
13616     // easily defensible position.
13617     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13618   } else {
13619     // C++11 [expr.prim.lambda]p14:
13620     //   For each entity captured by copy, an unnamed non-static
13621     //   data member is declared in the closure type. The
13622     //   declaration order of these members is unspecified. The type
13623     //   of such a data member is the type of the corresponding
13624     //   captured entity if the entity is not a reference to an
13625     //   object, or the referenced type otherwise. [Note: If the
13626     //   captured entity is a reference to a function, the
13627     //   corresponding data member is also a reference to a
13628     //   function. - end note ]
13629     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13630       if (!RefType->getPointeeType()->isFunctionType())
13631         CaptureType = RefType->getPointeeType();
13632     }
13633 
13634     // Forbid the lambda copy-capture of autoreleasing variables.
13635     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13636       if (BuildAndDiagnose) {
13637         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13638         S.Diag(Var->getLocation(), diag::note_previous_decl)
13639           << Var->getDeclName();
13640       }
13641       return false;
13642     }
13643 
13644     // Make sure that by-copy captures are of a complete and non-abstract type.
13645     if (BuildAndDiagnose) {
13646       if (!CaptureType->isDependentType() &&
13647           S.RequireCompleteType(Loc, CaptureType,
13648                                 diag::err_capture_of_incomplete_type,
13649                                 Var->getDeclName()))
13650         return false;
13651 
13652       if (S.RequireNonAbstractType(Loc, CaptureType,
13653                                    diag::err_capture_of_abstract_type))
13654         return false;
13655     }
13656   }
13657 
13658   // Capture this variable in the lambda.
13659   if (BuildAndDiagnose)
13660     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13661                             RefersToCapturedVariable);
13662 
13663   // Compute the type of a reference to this captured variable.
13664   if (ByRef)
13665     DeclRefType = CaptureType.getNonReferenceType();
13666   else {
13667     // C++ [expr.prim.lambda]p5:
13668     //   The closure type for a lambda-expression has a public inline
13669     //   function call operator [...]. This function call operator is
13670     //   declared const (9.3.1) if and only if the lambda-expression's
13671     //   parameter-declaration-clause is not followed by mutable.
13672     DeclRefType = CaptureType.getNonReferenceType();
13673     if (!LSI->Mutable && !CaptureType->isReferenceType())
13674       DeclRefType.addConst();
13675   }
13676 
13677   // Add the capture.
13678   if (BuildAndDiagnose)
13679     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13680                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13681 
13682   return true;
13683 }
13684 
13685 bool Sema::tryCaptureVariable(
13686     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13687     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13688     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13689   // An init-capture is notionally from the context surrounding its
13690   // declaration, but its parent DC is the lambda class.
13691   DeclContext *VarDC = Var->getDeclContext();
13692   if (Var->isInitCapture())
13693     VarDC = VarDC->getParent();
13694 
13695   DeclContext *DC = CurContext;
13696   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13697       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13698   // We need to sync up the Declaration Context with the
13699   // FunctionScopeIndexToStopAt
13700   if (FunctionScopeIndexToStopAt) {
13701     unsigned FSIndex = FunctionScopes.size() - 1;
13702     while (FSIndex != MaxFunctionScopesIndex) {
13703       DC = getLambdaAwareParentOfDeclContext(DC);
13704       --FSIndex;
13705     }
13706   }
13707 
13708 
13709   // If the variable is declared in the current context, there is no need to
13710   // capture it.
13711   if (VarDC == DC) return true;
13712 
13713   // Capture global variables if it is required to use private copy of this
13714   // variable.
13715   bool IsGlobal = !Var->hasLocalStorage();
13716   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13717     return true;
13718 
13719   // Walk up the stack to determine whether we can capture the variable,
13720   // performing the "simple" checks that don't depend on type. We stop when
13721   // we've either hit the declared scope of the variable or find an existing
13722   // capture of that variable.  We start from the innermost capturing-entity
13723   // (the DC) and ensure that all intervening capturing-entities
13724   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13725   // declcontext can either capture the variable or have already captured
13726   // the variable.
13727   CaptureType = Var->getType();
13728   DeclRefType = CaptureType.getNonReferenceType();
13729   bool Nested = false;
13730   bool Explicit = (Kind != TryCapture_Implicit);
13731   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13732   do {
13733     // Only block literals, captured statements, and lambda expressions can
13734     // capture; other scopes don't work.
13735     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13736                                                               ExprLoc,
13737                                                               BuildAndDiagnose,
13738                                                               *this);
13739     // We need to check for the parent *first* because, if we *have*
13740     // private-captured a global variable, we need to recursively capture it in
13741     // intermediate blocks, lambdas, etc.
13742     if (!ParentDC) {
13743       if (IsGlobal) {
13744         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13745         break;
13746       }
13747       return true;
13748     }
13749 
13750     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13751     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13752 
13753 
13754     // Check whether we've already captured it.
13755     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13756                                              DeclRefType))
13757       break;
13758     // If we are instantiating a generic lambda call operator body,
13759     // we do not want to capture new variables.  What was captured
13760     // during either a lambdas transformation or initial parsing
13761     // should be used.
13762     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13763       if (BuildAndDiagnose) {
13764         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13765         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13766           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13767           Diag(Var->getLocation(), diag::note_previous_decl)
13768              << Var->getDeclName();
13769           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13770         } else
13771           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13772       }
13773       return true;
13774     }
13775     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13776     // certain types of variables (unnamed, variably modified types etc.)
13777     // so check for eligibility.
13778     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13779        return true;
13780 
13781     // Try to capture variable-length arrays types.
13782     if (Var->getType()->isVariablyModifiedType()) {
13783       // We're going to walk down into the type and look for VLA
13784       // expressions.
13785       QualType QTy = Var->getType();
13786       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13787         QTy = PVD->getOriginalType();
13788       captureVariablyModifiedType(Context, QTy, CSI);
13789     }
13790 
13791     if (getLangOpts().OpenMP) {
13792       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13793         // OpenMP private variables should not be captured in outer scope, so
13794         // just break here. Similarly, global variables that are captured in a
13795         // target region should not be captured outside the scope of the region.
13796         if (RSI->CapRegionKind == CR_OpenMP) {
13797           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13798           // When we detect target captures we are looking from inside the
13799           // target region, therefore we need to propagate the capture from the
13800           // enclosing region. Therefore, the capture is not initially nested.
13801           if (IsTargetCap)
13802             FunctionScopesIndex--;
13803 
13804           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13805             Nested = !IsTargetCap;
13806             DeclRefType = DeclRefType.getUnqualifiedType();
13807             CaptureType = Context.getLValueReferenceType(DeclRefType);
13808             break;
13809           }
13810         }
13811       }
13812     }
13813     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13814       // No capture-default, and this is not an explicit capture
13815       // so cannot capture this variable.
13816       if (BuildAndDiagnose) {
13817         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13818         Diag(Var->getLocation(), diag::note_previous_decl)
13819           << Var->getDeclName();
13820         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13821           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13822                diag::note_lambda_decl);
13823         // FIXME: If we error out because an outer lambda can not implicitly
13824         // capture a variable that an inner lambda explicitly captures, we
13825         // should have the inner lambda do the explicit capture - because
13826         // it makes for cleaner diagnostics later.  This would purely be done
13827         // so that the diagnostic does not misleadingly claim that a variable
13828         // can not be captured by a lambda implicitly even though it is captured
13829         // explicitly.  Suggestion:
13830         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13831         //    at the function head
13832         //  - cache the StartingDeclContext - this must be a lambda
13833         //  - captureInLambda in the innermost lambda the variable.
13834       }
13835       return true;
13836     }
13837 
13838     FunctionScopesIndex--;
13839     DC = ParentDC;
13840     Explicit = false;
13841   } while (!VarDC->Equals(DC));
13842 
13843   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13844   // computing the type of the capture at each step, checking type-specific
13845   // requirements, and adding captures if requested.
13846   // If the variable had already been captured previously, we start capturing
13847   // at the lambda nested within that one.
13848   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13849        ++I) {
13850     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13851 
13852     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13853       if (!captureInBlock(BSI, Var, ExprLoc,
13854                           BuildAndDiagnose, CaptureType,
13855                           DeclRefType, Nested, *this))
13856         return true;
13857       Nested = true;
13858     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13859       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13860                                    BuildAndDiagnose, CaptureType,
13861                                    DeclRefType, Nested, *this))
13862         return true;
13863       Nested = true;
13864     } else {
13865       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13866       if (!captureInLambda(LSI, Var, ExprLoc,
13867                            BuildAndDiagnose, CaptureType,
13868                            DeclRefType, Nested, Kind, EllipsisLoc,
13869                             /*IsTopScope*/I == N - 1, *this))
13870         return true;
13871       Nested = true;
13872     }
13873   }
13874   return false;
13875 }
13876 
13877 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13878                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13879   QualType CaptureType;
13880   QualType DeclRefType;
13881   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13882                             /*BuildAndDiagnose=*/true, CaptureType,
13883                             DeclRefType, nullptr);
13884 }
13885 
13886 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13887   QualType CaptureType;
13888   QualType DeclRefType;
13889   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13890                              /*BuildAndDiagnose=*/false, CaptureType,
13891                              DeclRefType, nullptr);
13892 }
13893 
13894 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13895   QualType CaptureType;
13896   QualType DeclRefType;
13897 
13898   // Determine whether we can capture this variable.
13899   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13900                          /*BuildAndDiagnose=*/false, CaptureType,
13901                          DeclRefType, nullptr))
13902     return QualType();
13903 
13904   return DeclRefType;
13905 }
13906 
13907 
13908 
13909 // If either the type of the variable or the initializer is dependent,
13910 // return false. Otherwise, determine whether the variable is a constant
13911 // expression. Use this if you need to know if a variable that might or
13912 // might not be dependent is truly a constant expression.
13913 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13914     ASTContext &Context) {
13915 
13916   if (Var->getType()->isDependentType())
13917     return false;
13918   const VarDecl *DefVD = nullptr;
13919   Var->getAnyInitializer(DefVD);
13920   if (!DefVD)
13921     return false;
13922   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13923   Expr *Init = cast<Expr>(Eval->Value);
13924   if (Init->isValueDependent())
13925     return false;
13926   return IsVariableAConstantExpression(Var, Context);
13927 }
13928 
13929 
13930 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13931   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13932   // an object that satisfies the requirements for appearing in a
13933   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13934   // is immediately applied."  This function handles the lvalue-to-rvalue
13935   // conversion part.
13936   MaybeODRUseExprs.erase(E->IgnoreParens());
13937 
13938   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13939   // to a variable that is a constant expression, and if so, identify it as
13940   // a reference to a variable that does not involve an odr-use of that
13941   // variable.
13942   if (LambdaScopeInfo *LSI = getCurLambda()) {
13943     Expr *SansParensExpr = E->IgnoreParens();
13944     VarDecl *Var = nullptr;
13945     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13946       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13947     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13948       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13949 
13950     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13951       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13952   }
13953 }
13954 
13955 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13956   Res = CorrectDelayedTyposInExpr(Res);
13957 
13958   if (!Res.isUsable())
13959     return Res;
13960 
13961   // If a constant-expression is a reference to a variable where we delay
13962   // deciding whether it is an odr-use, just assume we will apply the
13963   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13964   // (a non-type template argument), we have special handling anyway.
13965   UpdateMarkingForLValueToRValue(Res.get());
13966   return Res;
13967 }
13968 
13969 void Sema::CleanupVarDeclMarking() {
13970   for (Expr *E : MaybeODRUseExprs) {
13971     VarDecl *Var;
13972     SourceLocation Loc;
13973     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13974       Var = cast<VarDecl>(DRE->getDecl());
13975       Loc = DRE->getLocation();
13976     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13977       Var = cast<VarDecl>(ME->getMemberDecl());
13978       Loc = ME->getMemberLoc();
13979     } else {
13980       llvm_unreachable("Unexpected expression");
13981     }
13982 
13983     MarkVarDeclODRUsed(Var, Loc, *this,
13984                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13985   }
13986 
13987   MaybeODRUseExprs.clear();
13988 }
13989 
13990 
13991 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13992                                     VarDecl *Var, Expr *E) {
13993   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13994          "Invalid Expr argument to DoMarkVarDeclReferenced");
13995   Var->setReferenced();
13996 
13997   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13998   bool MarkODRUsed = true;
13999 
14000   // If the context is not potentially evaluated, this is not an odr-use and
14001   // does not trigger instantiation.
14002   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
14003     if (SemaRef.isUnevaluatedContext())
14004       return;
14005 
14006     // If we don't yet know whether this context is going to end up being an
14007     // evaluated context, and we're referencing a variable from an enclosing
14008     // scope, add a potential capture.
14009     //
14010     // FIXME: Is this necessary? These contexts are only used for default
14011     // arguments, where local variables can't be used.
14012     const bool RefersToEnclosingScope =
14013         (SemaRef.CurContext != Var->getDeclContext() &&
14014          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14015     if (RefersToEnclosingScope) {
14016       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
14017         // If a variable could potentially be odr-used, defer marking it so
14018         // until we finish analyzing the full expression for any
14019         // lvalue-to-rvalue
14020         // or discarded value conversions that would obviate odr-use.
14021         // Add it to the list of potential captures that will be analyzed
14022         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14023         // unless the variable is a reference that was initialized by a constant
14024         // expression (this will never need to be captured or odr-used).
14025         assert(E && "Capture variable should be used in an expression.");
14026         if (!Var->getType()->isReferenceType() ||
14027             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14028           LSI->addPotentialCapture(E->IgnoreParens());
14029       }
14030     }
14031 
14032     if (!isTemplateInstantiation(TSK))
14033       return;
14034 
14035     // Instantiate, but do not mark as odr-used, variable templates.
14036     MarkODRUsed = false;
14037   }
14038 
14039   VarTemplateSpecializationDecl *VarSpec =
14040       dyn_cast<VarTemplateSpecializationDecl>(Var);
14041   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14042          "Can't instantiate a partial template specialization.");
14043 
14044   // If this might be a member specialization of a static data member, check
14045   // the specialization is visible. We already did the checks for variable
14046   // template specializations when we created them.
14047   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14048     SemaRef.checkSpecializationVisibility(Loc, Var);
14049 
14050   // Perform implicit instantiation of static data members, static data member
14051   // templates of class templates, and variable template specializations. Delay
14052   // instantiations of variable templates, except for those that could be used
14053   // in a constant expression.
14054   if (isTemplateInstantiation(TSK)) {
14055     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14056 
14057     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14058       if (Var->getPointOfInstantiation().isInvalid()) {
14059         // This is a modification of an existing AST node. Notify listeners.
14060         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14061           L->StaticDataMemberInstantiated(Var);
14062       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14063         // Don't bother trying to instantiate it again, unless we might need
14064         // its initializer before we get to the end of the TU.
14065         TryInstantiating = false;
14066     }
14067 
14068     if (Var->getPointOfInstantiation().isInvalid())
14069       Var->setTemplateSpecializationKind(TSK, Loc);
14070 
14071     if (TryInstantiating) {
14072       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14073       bool InstantiationDependent = false;
14074       bool IsNonDependent =
14075           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14076                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14077                   : true;
14078 
14079       // Do not instantiate specializations that are still type-dependent.
14080       if (IsNonDependent) {
14081         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14082           // Do not defer instantiations of variables which could be used in a
14083           // constant expression.
14084           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14085         } else {
14086           SemaRef.PendingInstantiations
14087               .push_back(std::make_pair(Var, PointOfInstantiation));
14088         }
14089       }
14090     }
14091   }
14092 
14093   if (!MarkODRUsed)
14094     return;
14095 
14096   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14097   // the requirements for appearing in a constant expression (5.19) and, if
14098   // it is an object, the lvalue-to-rvalue conversion (4.1)
14099   // is immediately applied."  We check the first part here, and
14100   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14101   // Note that we use the C++11 definition everywhere because nothing in
14102   // C++03 depends on whether we get the C++03 version correct. The second
14103   // part does not apply to references, since they are not objects.
14104   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14105     // A reference initialized by a constant expression can never be
14106     // odr-used, so simply ignore it.
14107     if (!Var->getType()->isReferenceType())
14108       SemaRef.MaybeODRUseExprs.insert(E);
14109   } else
14110     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14111                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14112 }
14113 
14114 /// \brief Mark a variable referenced, and check whether it is odr-used
14115 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14116 /// used directly for normal expressions referring to VarDecl.
14117 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14118   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14119 }
14120 
14121 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14122                                Decl *D, Expr *E, bool MightBeOdrUse) {
14123   if (SemaRef.isInOpenMPDeclareTargetContext())
14124     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14125 
14126   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14127     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14128     return;
14129   }
14130 
14131   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14132 
14133   // If this is a call to a method via a cast, also mark the method in the
14134   // derived class used in case codegen can devirtualize the call.
14135   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14136   if (!ME)
14137     return;
14138   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14139   if (!MD)
14140     return;
14141   // Only attempt to devirtualize if this is truly a virtual call.
14142   bool IsVirtualCall = MD->isVirtual() &&
14143                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14144   if (!IsVirtualCall)
14145     return;
14146   const Expr *Base = ME->getBase();
14147   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14148   if (!MostDerivedClassDecl)
14149     return;
14150   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14151   if (!DM || DM->isPure())
14152     return;
14153   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14154 }
14155 
14156 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14157 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14158   // TODO: update this with DR# once a defect report is filed.
14159   // C++11 defect. The address of a pure member should not be an ODR use, even
14160   // if it's a qualified reference.
14161   bool OdrUse = true;
14162   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14163     if (Method->isVirtual())
14164       OdrUse = false;
14165   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14166 }
14167 
14168 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14169 void Sema::MarkMemberReferenced(MemberExpr *E) {
14170   // C++11 [basic.def.odr]p2:
14171   //   A non-overloaded function whose name appears as a potentially-evaluated
14172   //   expression or a member of a set of candidate functions, if selected by
14173   //   overload resolution when referred to from a potentially-evaluated
14174   //   expression, is odr-used, unless it is a pure virtual function and its
14175   //   name is not explicitly qualified.
14176   bool MightBeOdrUse = true;
14177   if (E->performsVirtualDispatch(getLangOpts())) {
14178     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14179       if (Method->isPure())
14180         MightBeOdrUse = false;
14181   }
14182   SourceLocation Loc = E->getMemberLoc().isValid() ?
14183                             E->getMemberLoc() : E->getLocStart();
14184   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14185 }
14186 
14187 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14188 /// marks the declaration referenced, and performs odr-use checking for
14189 /// functions and variables. This method should not be used when building a
14190 /// normal expression which refers to a variable.
14191 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14192                                  bool MightBeOdrUse) {
14193   if (MightBeOdrUse) {
14194     if (auto *VD = dyn_cast<VarDecl>(D)) {
14195       MarkVariableReferenced(Loc, VD);
14196       return;
14197     }
14198   }
14199   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14200     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14201     return;
14202   }
14203   D->setReferenced();
14204 }
14205 
14206 namespace {
14207   // Mark all of the declarations referenced
14208   // FIXME: Not fully implemented yet! We need to have a better understanding
14209   // of when we're entering
14210   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14211     Sema &S;
14212     SourceLocation Loc;
14213 
14214   public:
14215     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14216 
14217     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14218 
14219     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14220     bool TraverseRecordType(RecordType *T);
14221   };
14222 }
14223 
14224 bool MarkReferencedDecls::TraverseTemplateArgument(
14225     const TemplateArgument &Arg) {
14226   if (Arg.getKind() == TemplateArgument::Declaration) {
14227     if (Decl *D = Arg.getAsDecl())
14228       S.MarkAnyDeclReferenced(Loc, D, true);
14229   }
14230 
14231   return Inherited::TraverseTemplateArgument(Arg);
14232 }
14233 
14234 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14235   if (ClassTemplateSpecializationDecl *Spec
14236                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14237     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14238     return TraverseTemplateArguments(Args.data(), Args.size());
14239   }
14240 
14241   return true;
14242 }
14243 
14244 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14245   MarkReferencedDecls Marker(*this, Loc);
14246   Marker.TraverseType(Context.getCanonicalType(T));
14247 }
14248 
14249 namespace {
14250   /// \brief Helper class that marks all of the declarations referenced by
14251   /// potentially-evaluated subexpressions as "referenced".
14252   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14253     Sema &S;
14254     bool SkipLocalVariables;
14255 
14256   public:
14257     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14258 
14259     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14260       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14261 
14262     void VisitDeclRefExpr(DeclRefExpr *E) {
14263       // If we were asked not to visit local variables, don't.
14264       if (SkipLocalVariables) {
14265         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14266           if (VD->hasLocalStorage())
14267             return;
14268       }
14269 
14270       S.MarkDeclRefReferenced(E);
14271     }
14272 
14273     void VisitMemberExpr(MemberExpr *E) {
14274       S.MarkMemberReferenced(E);
14275       Inherited::VisitMemberExpr(E);
14276     }
14277 
14278     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14279       S.MarkFunctionReferenced(E->getLocStart(),
14280             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14281       Visit(E->getSubExpr());
14282     }
14283 
14284     void VisitCXXNewExpr(CXXNewExpr *E) {
14285       if (E->getOperatorNew())
14286         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14287       if (E->getOperatorDelete())
14288         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14289       Inherited::VisitCXXNewExpr(E);
14290     }
14291 
14292     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14293       if (E->getOperatorDelete())
14294         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14295       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14296       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14297         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14298         S.MarkFunctionReferenced(E->getLocStart(),
14299                                     S.LookupDestructor(Record));
14300       }
14301 
14302       Inherited::VisitCXXDeleteExpr(E);
14303     }
14304 
14305     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14306       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14307       Inherited::VisitCXXConstructExpr(E);
14308     }
14309 
14310     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14311       Visit(E->getExpr());
14312     }
14313 
14314     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14315       Inherited::VisitImplicitCastExpr(E);
14316 
14317       if (E->getCastKind() == CK_LValueToRValue)
14318         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14319     }
14320   };
14321 }
14322 
14323 /// \brief Mark any declarations that appear within this expression or any
14324 /// potentially-evaluated subexpressions as "referenced".
14325 ///
14326 /// \param SkipLocalVariables If true, don't mark local variables as
14327 /// 'referenced'.
14328 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14329                                             bool SkipLocalVariables) {
14330   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14331 }
14332 
14333 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14334 /// of the program being compiled.
14335 ///
14336 /// This routine emits the given diagnostic when the code currently being
14337 /// type-checked is "potentially evaluated", meaning that there is a
14338 /// possibility that the code will actually be executable. Code in sizeof()
14339 /// expressions, code used only during overload resolution, etc., are not
14340 /// potentially evaluated. This routine will suppress such diagnostics or,
14341 /// in the absolutely nutty case of potentially potentially evaluated
14342 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14343 /// later.
14344 ///
14345 /// This routine should be used for all diagnostics that describe the run-time
14346 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14347 /// Failure to do so will likely result in spurious diagnostics or failures
14348 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14349 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14350                                const PartialDiagnostic &PD) {
14351   switch (ExprEvalContexts.back().Context) {
14352   case Unevaluated:
14353   case UnevaluatedAbstract:
14354   case DiscardedStatement:
14355     // The argument will never be evaluated, so don't complain.
14356     break;
14357 
14358   case ConstantEvaluated:
14359     // Relevant diagnostics should be produced by constant evaluation.
14360     break;
14361 
14362   case PotentiallyEvaluated:
14363   case PotentiallyEvaluatedIfUsed:
14364     if (Statement && getCurFunctionOrMethodDecl()) {
14365       FunctionScopes.back()->PossiblyUnreachableDiags.
14366         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14367     }
14368     else
14369       Diag(Loc, PD);
14370 
14371     return true;
14372   }
14373 
14374   return false;
14375 }
14376 
14377 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14378                                CallExpr *CE, FunctionDecl *FD) {
14379   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14380     return false;
14381 
14382   // If we're inside a decltype's expression, don't check for a valid return
14383   // type or construct temporaries until we know whether this is the last call.
14384   if (ExprEvalContexts.back().IsDecltype) {
14385     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14386     return false;
14387   }
14388 
14389   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14390     FunctionDecl *FD;
14391     CallExpr *CE;
14392 
14393   public:
14394     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14395       : FD(FD), CE(CE) { }
14396 
14397     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14398       if (!FD) {
14399         S.Diag(Loc, diag::err_call_incomplete_return)
14400           << T << CE->getSourceRange();
14401         return;
14402       }
14403 
14404       S.Diag(Loc, diag::err_call_function_incomplete_return)
14405         << CE->getSourceRange() << FD->getDeclName() << T;
14406       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14407           << FD->getDeclName();
14408     }
14409   } Diagnoser(FD, CE);
14410 
14411   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14412     return true;
14413 
14414   return false;
14415 }
14416 
14417 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14418 // will prevent this condition from triggering, which is what we want.
14419 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14420   SourceLocation Loc;
14421 
14422   unsigned diagnostic = diag::warn_condition_is_assignment;
14423   bool IsOrAssign = false;
14424 
14425   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14426     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14427       return;
14428 
14429     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14430 
14431     // Greylist some idioms by putting them into a warning subcategory.
14432     if (ObjCMessageExpr *ME
14433           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14434       Selector Sel = ME->getSelector();
14435 
14436       // self = [<foo> init...]
14437       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14438         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14439 
14440       // <foo> = [<bar> nextObject]
14441       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14442         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14443     }
14444 
14445     Loc = Op->getOperatorLoc();
14446   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14447     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14448       return;
14449 
14450     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14451     Loc = Op->getOperatorLoc();
14452   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14453     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14454   else {
14455     // Not an assignment.
14456     return;
14457   }
14458 
14459   Diag(Loc, diagnostic) << E->getSourceRange();
14460 
14461   SourceLocation Open = E->getLocStart();
14462   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14463   Diag(Loc, diag::note_condition_assign_silence)
14464         << FixItHint::CreateInsertion(Open, "(")
14465         << FixItHint::CreateInsertion(Close, ")");
14466 
14467   if (IsOrAssign)
14468     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14469       << FixItHint::CreateReplacement(Loc, "!=");
14470   else
14471     Diag(Loc, diag::note_condition_assign_to_comparison)
14472       << FixItHint::CreateReplacement(Loc, "==");
14473 }
14474 
14475 /// \brief Redundant parentheses over an equality comparison can indicate
14476 /// that the user intended an assignment used as condition.
14477 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14478   // Don't warn if the parens came from a macro.
14479   SourceLocation parenLoc = ParenE->getLocStart();
14480   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14481     return;
14482   // Don't warn for dependent expressions.
14483   if (ParenE->isTypeDependent())
14484     return;
14485 
14486   Expr *E = ParenE->IgnoreParens();
14487 
14488   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14489     if (opE->getOpcode() == BO_EQ &&
14490         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14491                                                            == Expr::MLV_Valid) {
14492       SourceLocation Loc = opE->getOperatorLoc();
14493 
14494       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14495       SourceRange ParenERange = ParenE->getSourceRange();
14496       Diag(Loc, diag::note_equality_comparison_silence)
14497         << FixItHint::CreateRemoval(ParenERange.getBegin())
14498         << FixItHint::CreateRemoval(ParenERange.getEnd());
14499       Diag(Loc, diag::note_equality_comparison_to_assign)
14500         << FixItHint::CreateReplacement(Loc, "=");
14501     }
14502 }
14503 
14504 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14505                                        bool IsConstexpr) {
14506   DiagnoseAssignmentAsCondition(E);
14507   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14508     DiagnoseEqualityWithExtraParens(parenE);
14509 
14510   ExprResult result = CheckPlaceholderExpr(E);
14511   if (result.isInvalid()) return ExprError();
14512   E = result.get();
14513 
14514   if (!E->isTypeDependent()) {
14515     if (getLangOpts().CPlusPlus)
14516       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14517 
14518     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14519     if (ERes.isInvalid())
14520       return ExprError();
14521     E = ERes.get();
14522 
14523     QualType T = E->getType();
14524     if (!T->isScalarType()) { // C99 6.8.4.1p1
14525       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14526         << T << E->getSourceRange();
14527       return ExprError();
14528     }
14529     CheckBoolLikeConversion(E, Loc);
14530   }
14531 
14532   return E;
14533 }
14534 
14535 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14536                                            Expr *SubExpr, ConditionKind CK) {
14537   // Empty conditions are valid in for-statements.
14538   if (!SubExpr)
14539     return ConditionResult();
14540 
14541   ExprResult Cond;
14542   switch (CK) {
14543   case ConditionKind::Boolean:
14544     Cond = CheckBooleanCondition(Loc, SubExpr);
14545     break;
14546 
14547   case ConditionKind::ConstexprIf:
14548     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14549     break;
14550 
14551   case ConditionKind::Switch:
14552     Cond = CheckSwitchCondition(Loc, SubExpr);
14553     break;
14554   }
14555   if (Cond.isInvalid())
14556     return ConditionError();
14557 
14558   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14559   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14560   if (!FullExpr.get())
14561     return ConditionError();
14562 
14563   return ConditionResult(*this, nullptr, FullExpr,
14564                          CK == ConditionKind::ConstexprIf);
14565 }
14566 
14567 namespace {
14568   /// A visitor for rebuilding a call to an __unknown_any expression
14569   /// to have an appropriate type.
14570   struct RebuildUnknownAnyFunction
14571     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14572 
14573     Sema &S;
14574 
14575     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14576 
14577     ExprResult VisitStmt(Stmt *S) {
14578       llvm_unreachable("unexpected statement!");
14579     }
14580 
14581     ExprResult VisitExpr(Expr *E) {
14582       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14583         << E->getSourceRange();
14584       return ExprError();
14585     }
14586 
14587     /// Rebuild an expression which simply semantically wraps another
14588     /// expression which it shares the type and value kind of.
14589     template <class T> ExprResult rebuildSugarExpr(T *E) {
14590       ExprResult SubResult = Visit(E->getSubExpr());
14591       if (SubResult.isInvalid()) return ExprError();
14592 
14593       Expr *SubExpr = SubResult.get();
14594       E->setSubExpr(SubExpr);
14595       E->setType(SubExpr->getType());
14596       E->setValueKind(SubExpr->getValueKind());
14597       assert(E->getObjectKind() == OK_Ordinary);
14598       return E;
14599     }
14600 
14601     ExprResult VisitParenExpr(ParenExpr *E) {
14602       return rebuildSugarExpr(E);
14603     }
14604 
14605     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14606       return rebuildSugarExpr(E);
14607     }
14608 
14609     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14610       ExprResult SubResult = Visit(E->getSubExpr());
14611       if (SubResult.isInvalid()) return ExprError();
14612 
14613       Expr *SubExpr = SubResult.get();
14614       E->setSubExpr(SubExpr);
14615       E->setType(S.Context.getPointerType(SubExpr->getType()));
14616       assert(E->getValueKind() == VK_RValue);
14617       assert(E->getObjectKind() == OK_Ordinary);
14618       return E;
14619     }
14620 
14621     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14622       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14623 
14624       E->setType(VD->getType());
14625 
14626       assert(E->getValueKind() == VK_RValue);
14627       if (S.getLangOpts().CPlusPlus &&
14628           !(isa<CXXMethodDecl>(VD) &&
14629             cast<CXXMethodDecl>(VD)->isInstance()))
14630         E->setValueKind(VK_LValue);
14631 
14632       return E;
14633     }
14634 
14635     ExprResult VisitMemberExpr(MemberExpr *E) {
14636       return resolveDecl(E, E->getMemberDecl());
14637     }
14638 
14639     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14640       return resolveDecl(E, E->getDecl());
14641     }
14642   };
14643 }
14644 
14645 /// Given a function expression of unknown-any type, try to rebuild it
14646 /// to have a function type.
14647 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14648   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14649   if (Result.isInvalid()) return ExprError();
14650   return S.DefaultFunctionArrayConversion(Result.get());
14651 }
14652 
14653 namespace {
14654   /// A visitor for rebuilding an expression of type __unknown_anytype
14655   /// into one which resolves the type directly on the referring
14656   /// expression.  Strict preservation of the original source
14657   /// structure is not a goal.
14658   struct RebuildUnknownAnyExpr
14659     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14660 
14661     Sema &S;
14662 
14663     /// The current destination type.
14664     QualType DestType;
14665 
14666     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14667       : S(S), DestType(CastType) {}
14668 
14669     ExprResult VisitStmt(Stmt *S) {
14670       llvm_unreachable("unexpected statement!");
14671     }
14672 
14673     ExprResult VisitExpr(Expr *E) {
14674       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14675         << E->getSourceRange();
14676       return ExprError();
14677     }
14678 
14679     ExprResult VisitCallExpr(CallExpr *E);
14680     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14681 
14682     /// Rebuild an expression which simply semantically wraps another
14683     /// expression which it shares the type and value kind of.
14684     template <class T> ExprResult rebuildSugarExpr(T *E) {
14685       ExprResult SubResult = Visit(E->getSubExpr());
14686       if (SubResult.isInvalid()) return ExprError();
14687       Expr *SubExpr = SubResult.get();
14688       E->setSubExpr(SubExpr);
14689       E->setType(SubExpr->getType());
14690       E->setValueKind(SubExpr->getValueKind());
14691       assert(E->getObjectKind() == OK_Ordinary);
14692       return E;
14693     }
14694 
14695     ExprResult VisitParenExpr(ParenExpr *E) {
14696       return rebuildSugarExpr(E);
14697     }
14698 
14699     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14700       return rebuildSugarExpr(E);
14701     }
14702 
14703     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14704       const PointerType *Ptr = DestType->getAs<PointerType>();
14705       if (!Ptr) {
14706         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14707           << E->getSourceRange();
14708         return ExprError();
14709       }
14710       assert(E->getValueKind() == VK_RValue);
14711       assert(E->getObjectKind() == OK_Ordinary);
14712       E->setType(DestType);
14713 
14714       // Build the sub-expression as if it were an object of the pointee type.
14715       DestType = Ptr->getPointeeType();
14716       ExprResult SubResult = Visit(E->getSubExpr());
14717       if (SubResult.isInvalid()) return ExprError();
14718       E->setSubExpr(SubResult.get());
14719       return E;
14720     }
14721 
14722     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14723 
14724     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14725 
14726     ExprResult VisitMemberExpr(MemberExpr *E) {
14727       return resolveDecl(E, E->getMemberDecl());
14728     }
14729 
14730     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14731       return resolveDecl(E, E->getDecl());
14732     }
14733   };
14734 }
14735 
14736 /// Rebuilds a call expression which yielded __unknown_anytype.
14737 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14738   Expr *CalleeExpr = E->getCallee();
14739 
14740   enum FnKind {
14741     FK_MemberFunction,
14742     FK_FunctionPointer,
14743     FK_BlockPointer
14744   };
14745 
14746   FnKind Kind;
14747   QualType CalleeType = CalleeExpr->getType();
14748   if (CalleeType == S.Context.BoundMemberTy) {
14749     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14750     Kind = FK_MemberFunction;
14751     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14752   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14753     CalleeType = Ptr->getPointeeType();
14754     Kind = FK_FunctionPointer;
14755   } else {
14756     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14757     Kind = FK_BlockPointer;
14758   }
14759   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14760 
14761   // Verify that this is a legal result type of a function.
14762   if (DestType->isArrayType() || DestType->isFunctionType()) {
14763     unsigned diagID = diag::err_func_returning_array_function;
14764     if (Kind == FK_BlockPointer)
14765       diagID = diag::err_block_returning_array_function;
14766 
14767     S.Diag(E->getExprLoc(), diagID)
14768       << DestType->isFunctionType() << DestType;
14769     return ExprError();
14770   }
14771 
14772   // Otherwise, go ahead and set DestType as the call's result.
14773   E->setType(DestType.getNonLValueExprType(S.Context));
14774   E->setValueKind(Expr::getValueKindForType(DestType));
14775   assert(E->getObjectKind() == OK_Ordinary);
14776 
14777   // Rebuild the function type, replacing the result type with DestType.
14778   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14779   if (Proto) {
14780     // __unknown_anytype(...) is a special case used by the debugger when
14781     // it has no idea what a function's signature is.
14782     //
14783     // We want to build this call essentially under the K&R
14784     // unprototyped rules, but making a FunctionNoProtoType in C++
14785     // would foul up all sorts of assumptions.  However, we cannot
14786     // simply pass all arguments as variadic arguments, nor can we
14787     // portably just call the function under a non-variadic type; see
14788     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14789     // However, it turns out that in practice it is generally safe to
14790     // call a function declared as "A foo(B,C,D);" under the prototype
14791     // "A foo(B,C,D,...);".  The only known exception is with the
14792     // Windows ABI, where any variadic function is implicitly cdecl
14793     // regardless of its normal CC.  Therefore we change the parameter
14794     // types to match the types of the arguments.
14795     //
14796     // This is a hack, but it is far superior to moving the
14797     // corresponding target-specific code from IR-gen to Sema/AST.
14798 
14799     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14800     SmallVector<QualType, 8> ArgTypes;
14801     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14802       ArgTypes.reserve(E->getNumArgs());
14803       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14804         Expr *Arg = E->getArg(i);
14805         QualType ArgType = Arg->getType();
14806         if (E->isLValue()) {
14807           ArgType = S.Context.getLValueReferenceType(ArgType);
14808         } else if (E->isXValue()) {
14809           ArgType = S.Context.getRValueReferenceType(ArgType);
14810         }
14811         ArgTypes.push_back(ArgType);
14812       }
14813       ParamTypes = ArgTypes;
14814     }
14815     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14816                                          Proto->getExtProtoInfo());
14817   } else {
14818     DestType = S.Context.getFunctionNoProtoType(DestType,
14819                                                 FnType->getExtInfo());
14820   }
14821 
14822   // Rebuild the appropriate pointer-to-function type.
14823   switch (Kind) {
14824   case FK_MemberFunction:
14825     // Nothing to do.
14826     break;
14827 
14828   case FK_FunctionPointer:
14829     DestType = S.Context.getPointerType(DestType);
14830     break;
14831 
14832   case FK_BlockPointer:
14833     DestType = S.Context.getBlockPointerType(DestType);
14834     break;
14835   }
14836 
14837   // Finally, we can recurse.
14838   ExprResult CalleeResult = Visit(CalleeExpr);
14839   if (!CalleeResult.isUsable()) return ExprError();
14840   E->setCallee(CalleeResult.get());
14841 
14842   // Bind a temporary if necessary.
14843   return S.MaybeBindToTemporary(E);
14844 }
14845 
14846 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14847   // Verify that this is a legal result type of a call.
14848   if (DestType->isArrayType() || DestType->isFunctionType()) {
14849     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14850       << DestType->isFunctionType() << DestType;
14851     return ExprError();
14852   }
14853 
14854   // Rewrite the method result type if available.
14855   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14856     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14857     Method->setReturnType(DestType);
14858   }
14859 
14860   // Change the type of the message.
14861   E->setType(DestType.getNonReferenceType());
14862   E->setValueKind(Expr::getValueKindForType(DestType));
14863 
14864   return S.MaybeBindToTemporary(E);
14865 }
14866 
14867 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14868   // The only case we should ever see here is a function-to-pointer decay.
14869   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14870     assert(E->getValueKind() == VK_RValue);
14871     assert(E->getObjectKind() == OK_Ordinary);
14872 
14873     E->setType(DestType);
14874 
14875     // Rebuild the sub-expression as the pointee (function) type.
14876     DestType = DestType->castAs<PointerType>()->getPointeeType();
14877 
14878     ExprResult Result = Visit(E->getSubExpr());
14879     if (!Result.isUsable()) return ExprError();
14880 
14881     E->setSubExpr(Result.get());
14882     return E;
14883   } else if (E->getCastKind() == CK_LValueToRValue) {
14884     assert(E->getValueKind() == VK_RValue);
14885     assert(E->getObjectKind() == OK_Ordinary);
14886 
14887     assert(isa<BlockPointerType>(E->getType()));
14888 
14889     E->setType(DestType);
14890 
14891     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14892     DestType = S.Context.getLValueReferenceType(DestType);
14893 
14894     ExprResult Result = Visit(E->getSubExpr());
14895     if (!Result.isUsable()) return ExprError();
14896 
14897     E->setSubExpr(Result.get());
14898     return E;
14899   } else {
14900     llvm_unreachable("Unhandled cast type!");
14901   }
14902 }
14903 
14904 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14905   ExprValueKind ValueKind = VK_LValue;
14906   QualType Type = DestType;
14907 
14908   // We know how to make this work for certain kinds of decls:
14909 
14910   //  - functions
14911   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14912     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14913       DestType = Ptr->getPointeeType();
14914       ExprResult Result = resolveDecl(E, VD);
14915       if (Result.isInvalid()) return ExprError();
14916       return S.ImpCastExprToType(Result.get(), Type,
14917                                  CK_FunctionToPointerDecay, VK_RValue);
14918     }
14919 
14920     if (!Type->isFunctionType()) {
14921       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14922         << VD << E->getSourceRange();
14923       return ExprError();
14924     }
14925     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14926       // We must match the FunctionDecl's type to the hack introduced in
14927       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14928       // type. See the lengthy commentary in that routine.
14929       QualType FDT = FD->getType();
14930       const FunctionType *FnType = FDT->castAs<FunctionType>();
14931       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14932       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14933       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14934         SourceLocation Loc = FD->getLocation();
14935         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14936                                       FD->getDeclContext(),
14937                                       Loc, Loc, FD->getNameInfo().getName(),
14938                                       DestType, FD->getTypeSourceInfo(),
14939                                       SC_None, false/*isInlineSpecified*/,
14940                                       FD->hasPrototype(),
14941                                       false/*isConstexprSpecified*/);
14942 
14943         if (FD->getQualifier())
14944           NewFD->setQualifierInfo(FD->getQualifierLoc());
14945 
14946         SmallVector<ParmVarDecl*, 16> Params;
14947         for (const auto &AI : FT->param_types()) {
14948           ParmVarDecl *Param =
14949             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14950           Param->setScopeInfo(0, Params.size());
14951           Params.push_back(Param);
14952         }
14953         NewFD->setParams(Params);
14954         DRE->setDecl(NewFD);
14955         VD = DRE->getDecl();
14956       }
14957     }
14958 
14959     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14960       if (MD->isInstance()) {
14961         ValueKind = VK_RValue;
14962         Type = S.Context.BoundMemberTy;
14963       }
14964 
14965     // Function references aren't l-values in C.
14966     if (!S.getLangOpts().CPlusPlus)
14967       ValueKind = VK_RValue;
14968 
14969   //  - variables
14970   } else if (isa<VarDecl>(VD)) {
14971     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14972       Type = RefTy->getPointeeType();
14973     } else if (Type->isFunctionType()) {
14974       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14975         << VD << E->getSourceRange();
14976       return ExprError();
14977     }
14978 
14979   //  - nothing else
14980   } else {
14981     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14982       << VD << E->getSourceRange();
14983     return ExprError();
14984   }
14985 
14986   // Modifying the declaration like this is friendly to IR-gen but
14987   // also really dangerous.
14988   VD->setType(DestType);
14989   E->setType(Type);
14990   E->setValueKind(ValueKind);
14991   return E;
14992 }
14993 
14994 /// Check a cast of an unknown-any type.  We intentionally only
14995 /// trigger this for C-style casts.
14996 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14997                                      Expr *CastExpr, CastKind &CastKind,
14998                                      ExprValueKind &VK, CXXCastPath &Path) {
14999   // The type we're casting to must be either void or complete.
15000   if (!CastType->isVoidType() &&
15001       RequireCompleteType(TypeRange.getBegin(), CastType,
15002                           diag::err_typecheck_cast_to_incomplete))
15003     return ExprError();
15004 
15005   // Rewrite the casted expression from scratch.
15006   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15007   if (!result.isUsable()) return ExprError();
15008 
15009   CastExpr = result.get();
15010   VK = CastExpr->getValueKind();
15011   CastKind = CK_NoOp;
15012 
15013   return CastExpr;
15014 }
15015 
15016 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15017   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15018 }
15019 
15020 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15021                                     Expr *arg, QualType &paramType) {
15022   // If the syntactic form of the argument is not an explicit cast of
15023   // any sort, just do default argument promotion.
15024   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15025   if (!castArg) {
15026     ExprResult result = DefaultArgumentPromotion(arg);
15027     if (result.isInvalid()) return ExprError();
15028     paramType = result.get()->getType();
15029     return result;
15030   }
15031 
15032   // Otherwise, use the type that was written in the explicit cast.
15033   assert(!arg->hasPlaceholderType());
15034   paramType = castArg->getTypeAsWritten();
15035 
15036   // Copy-initialize a parameter of that type.
15037   InitializedEntity entity =
15038     InitializedEntity::InitializeParameter(Context, paramType,
15039                                            /*consumed*/ false);
15040   return PerformCopyInitialization(entity, callLoc, arg);
15041 }
15042 
15043 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15044   Expr *orig = E;
15045   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15046   while (true) {
15047     E = E->IgnoreParenImpCasts();
15048     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15049       E = call->getCallee();
15050       diagID = diag::err_uncasted_call_of_unknown_any;
15051     } else {
15052       break;
15053     }
15054   }
15055 
15056   SourceLocation loc;
15057   NamedDecl *d;
15058   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15059     loc = ref->getLocation();
15060     d = ref->getDecl();
15061   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15062     loc = mem->getMemberLoc();
15063     d = mem->getMemberDecl();
15064   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15065     diagID = diag::err_uncasted_call_of_unknown_any;
15066     loc = msg->getSelectorStartLoc();
15067     d = msg->getMethodDecl();
15068     if (!d) {
15069       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15070         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15071         << orig->getSourceRange();
15072       return ExprError();
15073     }
15074   } else {
15075     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15076       << E->getSourceRange();
15077     return ExprError();
15078   }
15079 
15080   S.Diag(loc, diagID) << d << orig->getSourceRange();
15081 
15082   // Never recoverable.
15083   return ExprError();
15084 }
15085 
15086 /// Check for operands with placeholder types and complain if found.
15087 /// Returns true if there was an error and no recovery was possible.
15088 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15089   if (!getLangOpts().CPlusPlus) {
15090     // C cannot handle TypoExpr nodes on either side of a binop because it
15091     // doesn't handle dependent types properly, so make sure any TypoExprs have
15092     // been dealt with before checking the operands.
15093     ExprResult Result = CorrectDelayedTyposInExpr(E);
15094     if (!Result.isUsable()) return ExprError();
15095     E = Result.get();
15096   }
15097 
15098   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15099   if (!placeholderType) return E;
15100 
15101   switch (placeholderType->getKind()) {
15102 
15103   // Overloaded expressions.
15104   case BuiltinType::Overload: {
15105     // Try to resolve a single function template specialization.
15106     // This is obligatory.
15107     ExprResult Result = E;
15108     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15109       return Result;
15110 
15111     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15112     // leaves Result unchanged on failure.
15113     Result = E;
15114     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15115       return Result;
15116 
15117     // If that failed, try to recover with a call.
15118     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15119                          /*complain*/ true);
15120     return Result;
15121   }
15122 
15123   // Bound member functions.
15124   case BuiltinType::BoundMember: {
15125     ExprResult result = E;
15126     const Expr *BME = E->IgnoreParens();
15127     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15128     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15129     if (isa<CXXPseudoDestructorExpr>(BME)) {
15130       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15131     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15132       if (ME->getMemberNameInfo().getName().getNameKind() ==
15133           DeclarationName::CXXDestructorName)
15134         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15135     }
15136     tryToRecoverWithCall(result, PD,
15137                          /*complain*/ true);
15138     return result;
15139   }
15140 
15141   // ARC unbridged casts.
15142   case BuiltinType::ARCUnbridgedCast: {
15143     Expr *realCast = stripARCUnbridgedCast(E);
15144     diagnoseARCUnbridgedCast(realCast);
15145     return realCast;
15146   }
15147 
15148   // Expressions of unknown type.
15149   case BuiltinType::UnknownAny:
15150     return diagnoseUnknownAnyExpr(*this, E);
15151 
15152   // Pseudo-objects.
15153   case BuiltinType::PseudoObject:
15154     return checkPseudoObjectRValue(E);
15155 
15156   case BuiltinType::BuiltinFn: {
15157     // Accept __noop without parens by implicitly converting it to a call expr.
15158     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15159     if (DRE) {
15160       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15161       if (FD->getBuiltinID() == Builtin::BI__noop) {
15162         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15163                               CK_BuiltinFnToFnPtr).get();
15164         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15165                                       VK_RValue, SourceLocation());
15166       }
15167     }
15168 
15169     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15170     return ExprError();
15171   }
15172 
15173   // Expressions of unknown type.
15174   case BuiltinType::OMPArraySection:
15175     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15176     return ExprError();
15177 
15178   // Everything else should be impossible.
15179 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15180   case BuiltinType::Id:
15181 #include "clang/Basic/OpenCLImageTypes.def"
15182 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15183 #define PLACEHOLDER_TYPE(Id, SingletonId)
15184 #include "clang/AST/BuiltinTypes.def"
15185     break;
15186   }
15187 
15188   llvm_unreachable("invalid placeholder type!");
15189 }
15190 
15191 bool Sema::CheckCaseExpression(Expr *E) {
15192   if (E->isTypeDependent())
15193     return true;
15194   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15195     return E->getType()->isIntegralOrEnumerationType();
15196   return false;
15197 }
15198 
15199 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15200 ExprResult
15201 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15202   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15203          "Unknown Objective-C Boolean value!");
15204   QualType BoolT = Context.ObjCBuiltinBoolTy;
15205   if (!Context.getBOOLDecl()) {
15206     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15207                         Sema::LookupOrdinaryName);
15208     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15209       NamedDecl *ND = Result.getFoundDecl();
15210       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15211         Context.setBOOLDecl(TD);
15212     }
15213   }
15214   if (Context.getBOOLDecl())
15215     BoolT = Context.getBOOLType();
15216   return new (Context)
15217       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15218 }
15219 
15220 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15221     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15222     SourceLocation RParen) {
15223 
15224   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15225 
15226   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15227                            [&](const AvailabilitySpec &Spec) {
15228                              return Spec.getPlatform() == Platform;
15229                            });
15230 
15231   VersionTuple Version;
15232   if (Spec != AvailSpecs.end())
15233     Version = Spec->getVersion();
15234 
15235   return new (Context)
15236       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15237 }
15238