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         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
84       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
85       if (DC && !DC->hasAttr<UnusedAttr>())
86         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
87     }
88   }
89 }
90 
91 /// \brief Emit a note explaining that this function is deleted.
92 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
93   assert(Decl->isDeleted());
94 
95   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
96 
97   if (Method && Method->isDeleted() && Method->isDefaulted()) {
98     // If the method was explicitly defaulted, point at that declaration.
99     if (!Method->isImplicit())
100       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
101 
102     // Try to diagnose why this special member function was implicitly
103     // deleted. This might fail, if that reason no longer applies.
104     CXXSpecialMember CSM = getSpecialMember(Method);
105     if (CSM != CXXInvalid)
106       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
107 
108     return;
109   }
110 
111   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
112   if (Ctor && Ctor->isInheritingConstructor())
113     return NoteDeletedInheritingConstructor(Ctor);
114 
115   Diag(Decl->getLocation(), diag::note_availability_specified_here)
116     << Decl << true;
117 }
118 
119 /// \brief Determine whether a FunctionDecl was ever declared with an
120 /// explicit storage class.
121 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
122   for (auto I : D->redecls()) {
123     if (I->getStorageClass() != SC_None)
124       return true;
125   }
126   return false;
127 }
128 
129 /// \brief Check whether we're in an extern inline function and referring to a
130 /// variable or function with internal linkage (C11 6.7.4p3).
131 ///
132 /// This is only a warning because we used to silently accept this code, but
133 /// in many cases it will not behave correctly. This is not enabled in C++ mode
134 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
135 /// and so while there may still be user mistakes, most of the time we can't
136 /// prove that there are errors.
137 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
138                                                       const NamedDecl *D,
139                                                       SourceLocation Loc) {
140   // This is disabled under C++; there are too many ways for this to fire in
141   // contexts where the warning is a false positive, or where it is technically
142   // correct but benign.
143   if (S.getLangOpts().CPlusPlus)
144     return;
145 
146   // Check if this is an inlined function or method.
147   FunctionDecl *Current = S.getCurFunctionDecl();
148   if (!Current)
149     return;
150   if (!Current->isInlined())
151     return;
152   if (!Current->isExternallyVisible())
153     return;
154 
155   // Check if the decl has internal linkage.
156   if (D->getFormalLinkage() != InternalLinkage)
157     return;
158 
159   // Downgrade from ExtWarn to Extension if
160   //  (1) the supposedly external inline function is in the main file,
161   //      and probably won't be included anywhere else.
162   //  (2) the thing we're referencing is a pure function.
163   //  (3) the thing we're referencing is another inline function.
164   // This last can give us false negatives, but it's better than warning on
165   // wrappers for simple C library functions.
166   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
167   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
168   if (!DowngradeWarning && UsedFn)
169     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
170 
171   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
172                                : diag::ext_internal_in_extern_inline)
173     << /*IsVar=*/!UsedFn << D;
174 
175   S.MaybeSuggestAddingStaticToDecl(Current);
176 
177   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
178       << D;
179 }
180 
181 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
182   const FunctionDecl *First = Cur->getFirstDecl();
183 
184   // Suggest "static" on the function, if possible.
185   if (!hasAnyExplicitStorageClass(First)) {
186     SourceLocation DeclBegin = First->getSourceRange().getBegin();
187     Diag(DeclBegin, diag::note_convert_inline_to_static)
188       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
189   }
190 }
191 
192 /// \brief Determine whether the use of this declaration is valid, and
193 /// emit any corresponding diagnostics.
194 ///
195 /// This routine diagnoses various problems with referencing
196 /// declarations that can occur when using a declaration. For example,
197 /// it might warn if a deprecated or unavailable declaration is being
198 /// used, or produce an error (and return true) if a C++0x deleted
199 /// function is being used.
200 ///
201 /// \returns true if there was an error (this declaration cannot be
202 /// referenced), false otherwise.
203 ///
204 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
205                              const ObjCInterfaceDecl *UnknownObjCClass,
206                              bool ObjCPropertyAccess,
207                              bool AvoidPartialAvailabilityChecks) {
208   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
209     // If there were any diagnostics suppressed by template argument deduction,
210     // emit them now.
211     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
212     if (Pos != SuppressedDiagnostics.end()) {
213       for (const PartialDiagnosticAt &Suppressed : Pos->second)
214         Diag(Suppressed.first, Suppressed.second);
215 
216       // Clear out the list of suppressed diagnostics, so that we don't emit
217       // them again for this specialization. However, we don't obsolete this
218       // entry from the table, because we want to avoid ever emitting these
219       // diagnostics again.
220       Pos->second.clear();
221     }
222 
223     // C++ [basic.start.main]p3:
224     //   The function 'main' shall not be used within a program.
225     if (cast<FunctionDecl>(D)->isMain())
226       Diag(Loc, diag::ext_main_used);
227   }
228 
229   // See if this is an auto-typed variable whose initializer we are parsing.
230   if (ParsingInitForAutoVars.count(D)) {
231     if (isa<BindingDecl>(D)) {
232       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
233         << D->getDeclName();
234     } else {
235       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
236         << D->getDeclName() << cast<VarDecl>(D)->getType();
237     }
238     return true;
239   }
240 
241   // See if this is a deleted function.
242   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
243     if (FD->isDeleted()) {
244       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
245       if (Ctor && Ctor->isInheritingConstructor())
246         Diag(Loc, diag::err_deleted_inherited_ctor_use)
247             << Ctor->getParent()
248             << Ctor->getInheritedConstructor().getConstructor()->getParent();
249       else
250         Diag(Loc, diag::err_deleted_function_use);
251       NoteDeletedFunction(FD);
252       return true;
253     }
254 
255     // If the function has a deduced return type, and we can't deduce it,
256     // then we can't use it either.
257     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
258         DeduceReturnType(FD, Loc))
259       return true;
260 
261     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
262       return true;
263   }
264 
265   auto getReferencedObjCProp = [](const NamedDecl *D) ->
266                                       const ObjCPropertyDecl * {
267     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
268       return MD->findPropertyDecl();
269     return nullptr;
270   };
271   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
272     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
273       return true;
274   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
275       return true;
276   }
277 
278   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
279   // Only the variables omp_in and omp_out are allowed in the combiner.
280   // Only the variables omp_priv and omp_orig are allowed in the
281   // initializer-clause.
282   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
283   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
284       isa<VarDecl>(D)) {
285     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
286         << getCurFunction()->HasOMPDeclareReductionCombiner;
287     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
288     return true;
289   }
290 
291   DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess,
292                              AvoidPartialAvailabilityChecks);
293 
294   DiagnoseUnusedOfDecl(*this, D, Loc);
295 
296   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
297 
298   return false;
299 }
300 
301 /// \brief Retrieve the message suffix that should be added to a
302 /// diagnostic complaining about the given function being deleted or
303 /// unavailable.
304 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
305   std::string Message;
306   if (FD->getAvailability(&Message))
307     return ": " + Message;
308 
309   return std::string();
310 }
311 
312 /// DiagnoseSentinelCalls - This routine checks whether a call or
313 /// message-send is to a declaration with the sentinel attribute, and
314 /// if so, it checks that the requirements of the sentinel are
315 /// satisfied.
316 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
317                                  ArrayRef<Expr *> Args) {
318   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
319   if (!attr)
320     return;
321 
322   // The number of formal parameters of the declaration.
323   unsigned numFormalParams;
324 
325   // The kind of declaration.  This is also an index into a %select in
326   // the diagnostic.
327   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
328 
329   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
330     numFormalParams = MD->param_size();
331     calleeType = CT_Method;
332   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
333     numFormalParams = FD->param_size();
334     calleeType = CT_Function;
335   } else if (isa<VarDecl>(D)) {
336     QualType type = cast<ValueDecl>(D)->getType();
337     const FunctionType *fn = nullptr;
338     if (const PointerType *ptr = type->getAs<PointerType>()) {
339       fn = ptr->getPointeeType()->getAs<FunctionType>();
340       if (!fn) return;
341       calleeType = CT_Function;
342     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
343       fn = ptr->getPointeeType()->castAs<FunctionType>();
344       calleeType = CT_Block;
345     } else {
346       return;
347     }
348 
349     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
350       numFormalParams = proto->getNumParams();
351     } else {
352       numFormalParams = 0;
353     }
354   } else {
355     return;
356   }
357 
358   // "nullPos" is the number of formal parameters at the end which
359   // effectively count as part of the variadic arguments.  This is
360   // useful if you would prefer to not have *any* formal parameters,
361   // but the language forces you to have at least one.
362   unsigned nullPos = attr->getNullPos();
363   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
364   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
365 
366   // The number of arguments which should follow the sentinel.
367   unsigned numArgsAfterSentinel = attr->getSentinel();
368 
369   // If there aren't enough arguments for all the formal parameters,
370   // the sentinel, and the args after the sentinel, complain.
371   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
372     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
373     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
374     return;
375   }
376 
377   // Otherwise, find the sentinel expression.
378   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
379   if (!sentinelExpr) return;
380   if (sentinelExpr->isValueDependent()) return;
381   if (Context.isSentinelNullExpr(sentinelExpr)) return;
382 
383   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
384   // or 'NULL' if those are actually defined in the context.  Only use
385   // 'nil' for ObjC methods, where it's much more likely that the
386   // variadic arguments form a list of object pointers.
387   SourceLocation MissingNilLoc
388     = getLocForEndOfToken(sentinelExpr->getLocEnd());
389   std::string NullValue;
390   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
391     NullValue = "nil";
392   else if (getLangOpts().CPlusPlus11)
393     NullValue = "nullptr";
394   else if (PP.isMacroDefined("NULL"))
395     NullValue = "NULL";
396   else
397     NullValue = "(void*) 0";
398 
399   if (MissingNilLoc.isInvalid())
400     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
401   else
402     Diag(MissingNilLoc, diag::warn_missing_sentinel)
403       << int(calleeType)
404       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
405   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
406 }
407 
408 SourceRange Sema::getExprRange(Expr *E) const {
409   return E ? E->getSourceRange() : SourceRange();
410 }
411 
412 //===----------------------------------------------------------------------===//
413 //  Standard Promotions and Conversions
414 //===----------------------------------------------------------------------===//
415 
416 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
417 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
418   // Handle any placeholder expressions which made it here.
419   if (E->getType()->isPlaceholderType()) {
420     ExprResult result = CheckPlaceholderExpr(E);
421     if (result.isInvalid()) return ExprError();
422     E = result.get();
423   }
424 
425   QualType Ty = E->getType();
426   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
427 
428   if (Ty->isFunctionType()) {
429     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
430       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
431         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
432           return ExprError();
433 
434     E = ImpCastExprToType(E, Context.getPointerType(Ty),
435                           CK_FunctionToPointerDecay).get();
436   } else if (Ty->isArrayType()) {
437     // In C90 mode, arrays only promote to pointers if the array expression is
438     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
439     // type 'array of type' is converted to an expression that has type 'pointer
440     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
441     // that has type 'array of type' ...".  The relevant change is "an lvalue"
442     // (C90) to "an expression" (C99).
443     //
444     // C++ 4.2p1:
445     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
446     // T" can be converted to an rvalue of type "pointer to T".
447     //
448     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
449       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
450                             CK_ArrayToPointerDecay).get();
451   }
452   return E;
453 }
454 
455 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
456   // Check to see if we are dereferencing a null pointer.  If so,
457   // and if not volatile-qualified, this is undefined behavior that the
458   // optimizer will delete, so warn about it.  People sometimes try to use this
459   // to get a deterministic trap and are surprised by clang's behavior.  This
460   // only handles the pattern "*null", which is a very syntactic check.
461   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
462     if (UO->getOpcode() == UO_Deref &&
463         UO->getSubExpr()->IgnoreParenCasts()->
464           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
465         !UO->getType().isVolatileQualified()) {
466     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
467                           S.PDiag(diag::warn_indirection_through_null)
468                             << UO->getSubExpr()->getSourceRange());
469     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
470                         S.PDiag(diag::note_indirection_through_null));
471   }
472 }
473 
474 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
475                                     SourceLocation AssignLoc,
476                                     const Expr* RHS) {
477   const ObjCIvarDecl *IV = OIRE->getDecl();
478   if (!IV)
479     return;
480 
481   DeclarationName MemberName = IV->getDeclName();
482   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
483   if (!Member || !Member->isStr("isa"))
484     return;
485 
486   const Expr *Base = OIRE->getBase();
487   QualType BaseType = Base->getType();
488   if (OIRE->isArrow())
489     BaseType = BaseType->getPointeeType();
490   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
491     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
492       ObjCInterfaceDecl *ClassDeclared = nullptr;
493       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
494       if (!ClassDeclared->getSuperClass()
495           && (*ClassDeclared->ivar_begin()) == IV) {
496         if (RHS) {
497           NamedDecl *ObjectSetClass =
498             S.LookupSingleName(S.TUScope,
499                                &S.Context.Idents.get("object_setClass"),
500                                SourceLocation(), S.LookupOrdinaryName);
501           if (ObjectSetClass) {
502             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
503             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
504             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
505             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
506                                                      AssignLoc), ",") <<
507             FixItHint::CreateInsertion(RHSLocEnd, ")");
508           }
509           else
510             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
511         } else {
512           NamedDecl *ObjectGetClass =
513             S.LookupSingleName(S.TUScope,
514                                &S.Context.Idents.get("object_getClass"),
515                                SourceLocation(), S.LookupOrdinaryName);
516           if (ObjectGetClass)
517             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
518             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
519             FixItHint::CreateReplacement(
520                                          SourceRange(OIRE->getOpLoc(),
521                                                      OIRE->getLocEnd()), ")");
522           else
523             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
524         }
525         S.Diag(IV->getLocation(), diag::note_ivar_decl);
526       }
527     }
528 }
529 
530 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
531   // Handle any placeholder expressions which made it here.
532   if (E->getType()->isPlaceholderType()) {
533     ExprResult result = CheckPlaceholderExpr(E);
534     if (result.isInvalid()) return ExprError();
535     E = result.get();
536   }
537 
538   // C++ [conv.lval]p1:
539   //   A glvalue of a non-function, non-array type T can be
540   //   converted to a prvalue.
541   if (!E->isGLValue()) return E;
542 
543   QualType T = E->getType();
544   assert(!T.isNull() && "r-value conversion on typeless expression?");
545 
546   // We don't want to throw lvalue-to-rvalue casts on top of
547   // expressions of certain types in C++.
548   if (getLangOpts().CPlusPlus &&
549       (E->getType() == Context.OverloadTy ||
550        T->isDependentType() ||
551        T->isRecordType()))
552     return E;
553 
554   // The C standard is actually really unclear on this point, and
555   // DR106 tells us what the result should be but not why.  It's
556   // generally best to say that void types just doesn't undergo
557   // lvalue-to-rvalue at all.  Note that expressions of unqualified
558   // 'void' type are never l-values, but qualified void can be.
559   if (T->isVoidType())
560     return E;
561 
562   // OpenCL usually rejects direct accesses to values of 'half' type.
563   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
564       T->isHalfType()) {
565     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
566       << 0 << T;
567     return ExprError();
568   }
569 
570   CheckForNullPointerDereference(*this, E);
571   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
572     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
573                                      &Context.Idents.get("object_getClass"),
574                                      SourceLocation(), LookupOrdinaryName);
575     if (ObjectGetClass)
576       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
577         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
578         FixItHint::CreateReplacement(
579                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
580     else
581       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
582   }
583   else if (const ObjCIvarRefExpr *OIRE =
584             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
585     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
586 
587   // C++ [conv.lval]p1:
588   //   [...] If T is a non-class type, the type of the prvalue is the
589   //   cv-unqualified version of T. Otherwise, the type of the
590   //   rvalue is T.
591   //
592   // C99 6.3.2.1p2:
593   //   If the lvalue has qualified type, the value has the unqualified
594   //   version of the type of the lvalue; otherwise, the value has the
595   //   type of the lvalue.
596   if (T.hasQualifiers())
597     T = T.getUnqualifiedType();
598 
599   // Under the MS ABI, lock down the inheritance model now.
600   if (T->isMemberPointerType() &&
601       Context.getTargetInfo().getCXXABI().isMicrosoft())
602     (void)isCompleteType(E->getExprLoc(), T);
603 
604   UpdateMarkingForLValueToRValue(E);
605 
606   // Loading a __weak object implicitly retains the value, so we need a cleanup to
607   // balance that.
608   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
609     Cleanup.setExprNeedsCleanups(true);
610 
611   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
612                                             nullptr, VK_RValue);
613 
614   // C11 6.3.2.1p2:
615   //   ... if the lvalue has atomic type, the value has the non-atomic version
616   //   of the type of the lvalue ...
617   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
618     T = Atomic->getValueType().getUnqualifiedType();
619     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
620                                    nullptr, VK_RValue);
621   }
622 
623   return Res;
624 }
625 
626 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
627   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
628   if (Res.isInvalid())
629     return ExprError();
630   Res = DefaultLvalueConversion(Res.get());
631   if (Res.isInvalid())
632     return ExprError();
633   return Res;
634 }
635 
636 /// CallExprUnaryConversions - a special case of an unary conversion
637 /// performed on a function designator of a call expression.
638 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
639   QualType Ty = E->getType();
640   ExprResult Res = E;
641   // Only do implicit cast for a function type, but not for a pointer
642   // to function type.
643   if (Ty->isFunctionType()) {
644     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
645                             CK_FunctionToPointerDecay).get();
646     if (Res.isInvalid())
647       return ExprError();
648   }
649   Res = DefaultLvalueConversion(Res.get());
650   if (Res.isInvalid())
651     return ExprError();
652   return Res.get();
653 }
654 
655 /// UsualUnaryConversions - Performs various conversions that are common to most
656 /// operators (C99 6.3). The conversions of array and function types are
657 /// sometimes suppressed. For example, the array->pointer conversion doesn't
658 /// apply if the array is an argument to the sizeof or address (&) operators.
659 /// In these instances, this routine should *not* be called.
660 ExprResult Sema::UsualUnaryConversions(Expr *E) {
661   // First, convert to an r-value.
662   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
663   if (Res.isInvalid())
664     return ExprError();
665   E = Res.get();
666 
667   QualType Ty = E->getType();
668   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
669 
670   // Half FP have to be promoted to float unless it is natively supported
671   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
672     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
673 
674   // Try to perform integral promotions if the object has a theoretically
675   // promotable type.
676   if (Ty->isIntegralOrUnscopedEnumerationType()) {
677     // C99 6.3.1.1p2:
678     //
679     //   The following may be used in an expression wherever an int or
680     //   unsigned int may be used:
681     //     - an object or expression with an integer type whose integer
682     //       conversion rank is less than or equal to the rank of int
683     //       and unsigned int.
684     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
685     //
686     //   If an int can represent all values of the original type, the
687     //   value is converted to an int; otherwise, it is converted to an
688     //   unsigned int. These are called the integer promotions. All
689     //   other types are unchanged by the integer promotions.
690 
691     QualType PTy = Context.isPromotableBitField(E);
692     if (!PTy.isNull()) {
693       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
694       return E;
695     }
696     if (Ty->isPromotableIntegerType()) {
697       QualType PT = Context.getPromotedIntegerType(Ty);
698       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
699       return E;
700     }
701   }
702   return E;
703 }
704 
705 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
706 /// do not have a prototype. Arguments that have type float or __fp16
707 /// are promoted to double. All other argument types are converted by
708 /// UsualUnaryConversions().
709 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
710   QualType Ty = E->getType();
711   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
712 
713   ExprResult Res = UsualUnaryConversions(E);
714   if (Res.isInvalid())
715     return ExprError();
716   E = Res.get();
717 
718   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
719   // promote to double.
720   // Note that default argument promotion applies only to float (and
721   // half/fp16); it does not apply to _Float16.
722   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
723   if (BTy && (BTy->getKind() == BuiltinType::Half ||
724               BTy->getKind() == BuiltinType::Float)) {
725     if (getLangOpts().OpenCL &&
726         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
727         if (BTy->getKind() == BuiltinType::Half) {
728             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
729         }
730     } else {
731       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
732     }
733   }
734 
735   // C++ performs lvalue-to-rvalue conversion as a default argument
736   // promotion, even on class types, but note:
737   //   C++11 [conv.lval]p2:
738   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
739   //     operand or a subexpression thereof the value contained in the
740   //     referenced object is not accessed. Otherwise, if the glvalue
741   //     has a class type, the conversion copy-initializes a temporary
742   //     of type T from the glvalue and the result of the conversion
743   //     is a prvalue for the temporary.
744   // FIXME: add some way to gate this entire thing for correctness in
745   // potentially potentially evaluated contexts.
746   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
747     ExprResult Temp = PerformCopyInitialization(
748                        InitializedEntity::InitializeTemporary(E->getType()),
749                                                 E->getExprLoc(), E);
750     if (Temp.isInvalid())
751       return ExprError();
752     E = Temp.get();
753   }
754 
755   return E;
756 }
757 
758 /// Determine the degree of POD-ness for an expression.
759 /// Incomplete types are considered POD, since this check can be performed
760 /// when we're in an unevaluated context.
761 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
762   if (Ty->isIncompleteType()) {
763     // C++11 [expr.call]p7:
764     //   After these conversions, if the argument does not have arithmetic,
765     //   enumeration, pointer, pointer to member, or class type, the program
766     //   is ill-formed.
767     //
768     // Since we've already performed array-to-pointer and function-to-pointer
769     // decay, the only such type in C++ is cv void. This also handles
770     // initializer lists as variadic arguments.
771     if (Ty->isVoidType())
772       return VAK_Invalid;
773 
774     if (Ty->isObjCObjectType())
775       return VAK_Invalid;
776     return VAK_Valid;
777   }
778 
779   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
780     return VAK_Invalid;
781 
782   if (Ty.isCXX98PODType(Context))
783     return VAK_Valid;
784 
785   // C++11 [expr.call]p7:
786   //   Passing a potentially-evaluated argument of class type (Clause 9)
787   //   having a non-trivial copy constructor, a non-trivial move constructor,
788   //   or a non-trivial destructor, with no corresponding parameter,
789   //   is conditionally-supported with implementation-defined semantics.
790   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
791     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
792       if (!Record->hasNonTrivialCopyConstructor() &&
793           !Record->hasNonTrivialMoveConstructor() &&
794           !Record->hasNonTrivialDestructor())
795         return VAK_ValidInCXX11;
796 
797   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
798     return VAK_Valid;
799 
800   if (Ty->isObjCObjectType())
801     return VAK_Invalid;
802 
803   if (getLangOpts().MSVCCompat)
804     return VAK_MSVCUndefined;
805 
806   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
807   // permitted to reject them. We should consider doing so.
808   return VAK_Undefined;
809 }
810 
811 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
812   // Don't allow one to pass an Objective-C interface to a vararg.
813   const QualType &Ty = E->getType();
814   VarArgKind VAK = isValidVarArgType(Ty);
815 
816   // Complain about passing non-POD types through varargs.
817   switch (VAK) {
818   case VAK_ValidInCXX11:
819     DiagRuntimeBehavior(
820         E->getLocStart(), nullptr,
821         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
822           << Ty << CT);
823     LLVM_FALLTHROUGH;
824   case VAK_Valid:
825     if (Ty->isRecordType()) {
826       // This is unlikely to be what the user intended. If the class has a
827       // 'c_str' member function, the user probably meant to call that.
828       DiagRuntimeBehavior(E->getLocStart(), nullptr,
829                           PDiag(diag::warn_pass_class_arg_to_vararg)
830                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
831     }
832     break;
833 
834   case VAK_Undefined:
835   case VAK_MSVCUndefined:
836     DiagRuntimeBehavior(
837         E->getLocStart(), nullptr,
838         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
839           << getLangOpts().CPlusPlus11 << Ty << CT);
840     break;
841 
842   case VAK_Invalid:
843     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
844       Diag(E->getLocStart(),
845            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
846     else if (Ty->isObjCObjectType())
847       DiagRuntimeBehavior(
848           E->getLocStart(), nullptr,
849           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
850             << Ty << CT);
851     else
852       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
853         << isa<InitListExpr>(E) << Ty << CT;
854     break;
855   }
856 }
857 
858 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
859 /// will create a trap if the resulting type is not a POD type.
860 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
861                                                   FunctionDecl *FDecl) {
862   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
863     // Strip the unbridged-cast placeholder expression off, if applicable.
864     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
865         (CT == VariadicMethod ||
866          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
867       E = stripARCUnbridgedCast(E);
868 
869     // Otherwise, do normal placeholder checking.
870     } else {
871       ExprResult ExprRes = CheckPlaceholderExpr(E);
872       if (ExprRes.isInvalid())
873         return ExprError();
874       E = ExprRes.get();
875     }
876   }
877 
878   ExprResult ExprRes = DefaultArgumentPromotion(E);
879   if (ExprRes.isInvalid())
880     return ExprError();
881   E = ExprRes.get();
882 
883   // Diagnostics regarding non-POD argument types are
884   // emitted along with format string checking in Sema::CheckFunctionCall().
885   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
886     // Turn this into a trap.
887     CXXScopeSpec SS;
888     SourceLocation TemplateKWLoc;
889     UnqualifiedId Name;
890     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
891                        E->getLocStart());
892     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
893                                           Name, true, false);
894     if (TrapFn.isInvalid())
895       return ExprError();
896 
897     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
898                                     E->getLocStart(), None,
899                                     E->getLocEnd());
900     if (Call.isInvalid())
901       return ExprError();
902 
903     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
904                                   Call.get(), E);
905     if (Comma.isInvalid())
906       return ExprError();
907     return Comma.get();
908   }
909 
910   if (!getLangOpts().CPlusPlus &&
911       RequireCompleteType(E->getExprLoc(), E->getType(),
912                           diag::err_call_incomplete_argument))
913     return ExprError();
914 
915   return E;
916 }
917 
918 /// \brief Converts an integer to complex float type.  Helper function of
919 /// UsualArithmeticConversions()
920 ///
921 /// \return false if the integer expression is an integer type and is
922 /// successfully converted to the complex type.
923 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
924                                                   ExprResult &ComplexExpr,
925                                                   QualType IntTy,
926                                                   QualType ComplexTy,
927                                                   bool SkipCast) {
928   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
929   if (SkipCast) return false;
930   if (IntTy->isIntegerType()) {
931     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
932     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
933     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
934                                   CK_FloatingRealToComplex);
935   } else {
936     assert(IntTy->isComplexIntegerType());
937     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
938                                   CK_IntegralComplexToFloatingComplex);
939   }
940   return false;
941 }
942 
943 /// \brief Handle arithmetic conversion with complex types.  Helper function of
944 /// UsualArithmeticConversions()
945 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
946                                              ExprResult &RHS, QualType LHSType,
947                                              QualType RHSType,
948                                              bool IsCompAssign) {
949   // if we have an integer operand, the result is the complex type.
950   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
951                                              /*skipCast*/false))
952     return LHSType;
953   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
954                                              /*skipCast*/IsCompAssign))
955     return RHSType;
956 
957   // This handles complex/complex, complex/float, or float/complex.
958   // When both operands are complex, the shorter operand is converted to the
959   // type of the longer, and that is the type of the result. This corresponds
960   // to what is done when combining two real floating-point operands.
961   // The fun begins when size promotion occur across type domains.
962   // From H&S 6.3.4: When one operand is complex and the other is a real
963   // floating-point type, the less precise type is converted, within it's
964   // real or complex domain, to the precision of the other type. For example,
965   // when combining a "long double" with a "double _Complex", the
966   // "double _Complex" is promoted to "long double _Complex".
967 
968   // Compute the rank of the two types, regardless of whether they are complex.
969   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
970 
971   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
972   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
973   QualType LHSElementType =
974       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
975   QualType RHSElementType =
976       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
977 
978   QualType ResultType = S.Context.getComplexType(LHSElementType);
979   if (Order < 0) {
980     // Promote the precision of the LHS if not an assignment.
981     ResultType = S.Context.getComplexType(RHSElementType);
982     if (!IsCompAssign) {
983       if (LHSComplexType)
984         LHS =
985             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
986       else
987         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
988     }
989   } else if (Order > 0) {
990     // Promote the precision of the RHS.
991     if (RHSComplexType)
992       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
993     else
994       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
995   }
996   return ResultType;
997 }
998 
999 /// \brief Handle arithmetic conversion from integer to float.  Helper function
1000 /// of UsualArithmeticConversions()
1001 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1002                                            ExprResult &IntExpr,
1003                                            QualType FloatTy, QualType IntTy,
1004                                            bool ConvertFloat, bool ConvertInt) {
1005   if (IntTy->isIntegerType()) {
1006     if (ConvertInt)
1007       // Convert intExpr to the lhs floating point type.
1008       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1009                                     CK_IntegralToFloating);
1010     return FloatTy;
1011   }
1012 
1013   // Convert both sides to the appropriate complex float.
1014   assert(IntTy->isComplexIntegerType());
1015   QualType result = S.Context.getComplexType(FloatTy);
1016 
1017   // _Complex int -> _Complex float
1018   if (ConvertInt)
1019     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1020                                   CK_IntegralComplexToFloatingComplex);
1021 
1022   // float -> _Complex float
1023   if (ConvertFloat)
1024     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1025                                     CK_FloatingRealToComplex);
1026 
1027   return result;
1028 }
1029 
1030 /// \brief Handle arithmethic conversion with floating point types.  Helper
1031 /// function of UsualArithmeticConversions()
1032 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1033                                       ExprResult &RHS, QualType LHSType,
1034                                       QualType RHSType, bool IsCompAssign) {
1035   bool LHSFloat = LHSType->isRealFloatingType();
1036   bool RHSFloat = RHSType->isRealFloatingType();
1037 
1038   // If we have two real floating types, convert the smaller operand
1039   // to the bigger result.
1040   if (LHSFloat && RHSFloat) {
1041     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1042     if (order > 0) {
1043       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1044       return LHSType;
1045     }
1046 
1047     assert(order < 0 && "illegal float comparison");
1048     if (!IsCompAssign)
1049       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1050     return RHSType;
1051   }
1052 
1053   if (LHSFloat) {
1054     // Half FP has to be promoted to float unless it is natively supported
1055     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1056       LHSType = S.Context.FloatTy;
1057 
1058     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1059                                       /*convertFloat=*/!IsCompAssign,
1060                                       /*convertInt=*/ true);
1061   }
1062   assert(RHSFloat);
1063   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1064                                     /*convertInt=*/ true,
1065                                     /*convertFloat=*/!IsCompAssign);
1066 }
1067 
1068 /// \brief Diagnose attempts to convert between __float128 and long double if
1069 /// there is no support for such conversion. Helper function of
1070 /// UsualArithmeticConversions().
1071 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1072                                       QualType RHSType) {
1073   /*  No issue converting if at least one of the types is not a floating point
1074       type or the two types have the same rank.
1075   */
1076   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1077       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1078     return false;
1079 
1080   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1081          "The remaining types must be floating point types.");
1082 
1083   auto *LHSComplex = LHSType->getAs<ComplexType>();
1084   auto *RHSComplex = RHSType->getAs<ComplexType>();
1085 
1086   QualType LHSElemType = LHSComplex ?
1087     LHSComplex->getElementType() : LHSType;
1088   QualType RHSElemType = RHSComplex ?
1089     RHSComplex->getElementType() : RHSType;
1090 
1091   // No issue if the two types have the same representation
1092   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1093       &S.Context.getFloatTypeSemantics(RHSElemType))
1094     return false;
1095 
1096   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1097                                 RHSElemType == S.Context.LongDoubleTy);
1098   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1099                             RHSElemType == S.Context.Float128Ty);
1100 
1101   // We've handled the situation where __float128 and long double have the same
1102   // representation. We allow all conversions for all possible long double types
1103   // except PPC's double double.
1104   return Float128AndLongDouble &&
1105     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1106      &llvm::APFloat::PPCDoubleDouble());
1107 }
1108 
1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1110 
1111 namespace {
1112 /// These helper callbacks are placed in an anonymous namespace to
1113 /// permit their use as function template parameters.
1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1115   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1116 }
1117 
1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1119   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1120                              CK_IntegralComplexCast);
1121 }
1122 }
1123 
1124 /// \brief Handle integer arithmetic conversions.  Helper function of
1125 /// UsualArithmeticConversions()
1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1128                                         ExprResult &RHS, QualType LHSType,
1129                                         QualType RHSType, bool IsCompAssign) {
1130   // The rules for this case are in C99 6.3.1.8
1131   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1132   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1133   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1134   if (LHSSigned == RHSSigned) {
1135     // Same signedness; use the higher-ranked type
1136     if (order >= 0) {
1137       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1138       return LHSType;
1139     } else if (!IsCompAssign)
1140       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1141     return RHSType;
1142   } else if (order != (LHSSigned ? 1 : -1)) {
1143     // The unsigned type has greater than or equal rank to the
1144     // signed type, so use the unsigned type
1145     if (RHSSigned) {
1146       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1147       return LHSType;
1148     } else if (!IsCompAssign)
1149       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1150     return RHSType;
1151   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1152     // The two types are different widths; if we are here, that
1153     // means the signed type is larger than the unsigned type, so
1154     // use the signed type.
1155     if (LHSSigned) {
1156       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1157       return LHSType;
1158     } else if (!IsCompAssign)
1159       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1160     return RHSType;
1161   } else {
1162     // The signed type is higher-ranked than the unsigned type,
1163     // but isn't actually any bigger (like unsigned int and long
1164     // on most 32-bit systems).  Use the unsigned type corresponding
1165     // to the signed type.
1166     QualType result =
1167       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1168     RHS = (*doRHSCast)(S, RHS.get(), result);
1169     if (!IsCompAssign)
1170       LHS = (*doLHSCast)(S, LHS.get(), result);
1171     return result;
1172   }
1173 }
1174 
1175 /// \brief Handle conversions with GCC complex int extension.  Helper function
1176 /// of UsualArithmeticConversions()
1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1178                                            ExprResult &RHS, QualType LHSType,
1179                                            QualType RHSType,
1180                                            bool IsCompAssign) {
1181   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1182   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1183 
1184   if (LHSComplexInt && RHSComplexInt) {
1185     QualType LHSEltType = LHSComplexInt->getElementType();
1186     QualType RHSEltType = RHSComplexInt->getElementType();
1187     QualType ScalarType =
1188       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1189         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1190 
1191     return S.Context.getComplexType(ScalarType);
1192   }
1193 
1194   if (LHSComplexInt) {
1195     QualType LHSEltType = LHSComplexInt->getElementType();
1196     QualType ScalarType =
1197       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1198         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1199     QualType ComplexType = S.Context.getComplexType(ScalarType);
1200     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1201                               CK_IntegralRealToComplex);
1202 
1203     return ComplexType;
1204   }
1205 
1206   assert(RHSComplexInt);
1207 
1208   QualType RHSEltType = RHSComplexInt->getElementType();
1209   QualType ScalarType =
1210     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1211       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1212   QualType ComplexType = S.Context.getComplexType(ScalarType);
1213 
1214   if (!IsCompAssign)
1215     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1216                               CK_IntegralRealToComplex);
1217   return ComplexType;
1218 }
1219 
1220 /// UsualArithmeticConversions - Performs various conversions that are common to
1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1222 /// routine returns the first non-arithmetic type found. The client is
1223 /// responsible for emitting appropriate error diagnostics.
1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1225                                           bool IsCompAssign) {
1226   if (!IsCompAssign) {
1227     LHS = UsualUnaryConversions(LHS.get());
1228     if (LHS.isInvalid())
1229       return QualType();
1230   }
1231 
1232   RHS = UsualUnaryConversions(RHS.get());
1233   if (RHS.isInvalid())
1234     return QualType();
1235 
1236   // For conversion purposes, we ignore any qualifiers.
1237   // For example, "const float" and "float" are equivalent.
1238   QualType LHSType =
1239     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1240   QualType RHSType =
1241     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1242 
1243   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1244   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1245     LHSType = AtomicLHS->getValueType();
1246 
1247   // If both types are identical, no conversion is needed.
1248   if (LHSType == RHSType)
1249     return LHSType;
1250 
1251   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1252   // The caller can deal with this (e.g. pointer + int).
1253   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1254     return QualType();
1255 
1256   // Apply unary and bitfield promotions to the LHS's type.
1257   QualType LHSUnpromotedType = LHSType;
1258   if (LHSType->isPromotableIntegerType())
1259     LHSType = Context.getPromotedIntegerType(LHSType);
1260   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1261   if (!LHSBitfieldPromoteTy.isNull())
1262     LHSType = LHSBitfieldPromoteTy;
1263   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1264     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1265 
1266   // If both types are identical, no conversion is needed.
1267   if (LHSType == RHSType)
1268     return LHSType;
1269 
1270   // At this point, we have two different arithmetic types.
1271 
1272   // Diagnose attempts to convert between __float128 and long double where
1273   // such conversions currently can't be handled.
1274   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1275     return QualType();
1276 
1277   // Handle complex types first (C99 6.3.1.8p1).
1278   if (LHSType->isComplexType() || RHSType->isComplexType())
1279     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1280                                         IsCompAssign);
1281 
1282   // Now handle "real" floating types (i.e. float, double, long double).
1283   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1284     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1285                                  IsCompAssign);
1286 
1287   // Handle GCC complex int extension.
1288   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1289     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1290                                       IsCompAssign);
1291 
1292   // Finally, we have two differing integer types.
1293   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1294            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1295 }
1296 
1297 
1298 //===----------------------------------------------------------------------===//
1299 //  Semantic Analysis for various Expression Types
1300 //===----------------------------------------------------------------------===//
1301 
1302 
1303 ExprResult
1304 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1305                                 SourceLocation DefaultLoc,
1306                                 SourceLocation RParenLoc,
1307                                 Expr *ControllingExpr,
1308                                 ArrayRef<ParsedType> ArgTypes,
1309                                 ArrayRef<Expr *> ArgExprs) {
1310   unsigned NumAssocs = ArgTypes.size();
1311   assert(NumAssocs == ArgExprs.size());
1312 
1313   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1314   for (unsigned i = 0; i < NumAssocs; ++i) {
1315     if (ArgTypes[i])
1316       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1317     else
1318       Types[i] = nullptr;
1319   }
1320 
1321   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1322                                              ControllingExpr,
1323                                              llvm::makeArrayRef(Types, NumAssocs),
1324                                              ArgExprs);
1325   delete [] Types;
1326   return ER;
1327 }
1328 
1329 ExprResult
1330 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1331                                  SourceLocation DefaultLoc,
1332                                  SourceLocation RParenLoc,
1333                                  Expr *ControllingExpr,
1334                                  ArrayRef<TypeSourceInfo *> Types,
1335                                  ArrayRef<Expr *> Exprs) {
1336   unsigned NumAssocs = Types.size();
1337   assert(NumAssocs == Exprs.size());
1338 
1339   // Decay and strip qualifiers for the controlling expression type, and handle
1340   // placeholder type replacement. See committee discussion from WG14 DR423.
1341   {
1342     EnterExpressionEvaluationContext Unevaluated(
1343         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1344     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1345     if (R.isInvalid())
1346       return ExprError();
1347     ControllingExpr = R.get();
1348   }
1349 
1350   // The controlling expression is an unevaluated operand, so side effects are
1351   // likely unintended.
1352   if (!inTemplateInstantiation() &&
1353       ControllingExpr->HasSideEffects(Context, false))
1354     Diag(ControllingExpr->getExprLoc(),
1355          diag::warn_side_effects_unevaluated_context);
1356 
1357   bool TypeErrorFound = false,
1358        IsResultDependent = ControllingExpr->isTypeDependent(),
1359        ContainsUnexpandedParameterPack
1360          = ControllingExpr->containsUnexpandedParameterPack();
1361 
1362   for (unsigned i = 0; i < NumAssocs; ++i) {
1363     if (Exprs[i]->containsUnexpandedParameterPack())
1364       ContainsUnexpandedParameterPack = true;
1365 
1366     if (Types[i]) {
1367       if (Types[i]->getType()->containsUnexpandedParameterPack())
1368         ContainsUnexpandedParameterPack = true;
1369 
1370       if (Types[i]->getType()->isDependentType()) {
1371         IsResultDependent = true;
1372       } else {
1373         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1374         // complete object type other than a variably modified type."
1375         unsigned D = 0;
1376         if (Types[i]->getType()->isIncompleteType())
1377           D = diag::err_assoc_type_incomplete;
1378         else if (!Types[i]->getType()->isObjectType())
1379           D = diag::err_assoc_type_nonobject;
1380         else if (Types[i]->getType()->isVariablyModifiedType())
1381           D = diag::err_assoc_type_variably_modified;
1382 
1383         if (D != 0) {
1384           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1385             << Types[i]->getTypeLoc().getSourceRange()
1386             << Types[i]->getType();
1387           TypeErrorFound = true;
1388         }
1389 
1390         // C11 6.5.1.1p2 "No two generic associations in the same generic
1391         // selection shall specify compatible types."
1392         for (unsigned j = i+1; j < NumAssocs; ++j)
1393           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1394               Context.typesAreCompatible(Types[i]->getType(),
1395                                          Types[j]->getType())) {
1396             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1397                  diag::err_assoc_compatible_types)
1398               << Types[j]->getTypeLoc().getSourceRange()
1399               << Types[j]->getType()
1400               << Types[i]->getType();
1401             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1402                  diag::note_compat_assoc)
1403               << Types[i]->getTypeLoc().getSourceRange()
1404               << Types[i]->getType();
1405             TypeErrorFound = true;
1406           }
1407       }
1408     }
1409   }
1410   if (TypeErrorFound)
1411     return ExprError();
1412 
1413   // If we determined that the generic selection is result-dependent, don't
1414   // try to compute the result expression.
1415   if (IsResultDependent)
1416     return new (Context) GenericSelectionExpr(
1417         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1418         ContainsUnexpandedParameterPack);
1419 
1420   SmallVector<unsigned, 1> CompatIndices;
1421   unsigned DefaultIndex = -1U;
1422   for (unsigned i = 0; i < NumAssocs; ++i) {
1423     if (!Types[i])
1424       DefaultIndex = i;
1425     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1426                                         Types[i]->getType()))
1427       CompatIndices.push_back(i);
1428   }
1429 
1430   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1431   // type compatible with at most one of the types named in its generic
1432   // association list."
1433   if (CompatIndices.size() > 1) {
1434     // We strip parens here because the controlling expression is typically
1435     // parenthesized in macro definitions.
1436     ControllingExpr = ControllingExpr->IgnoreParens();
1437     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1438       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1439       << (unsigned) CompatIndices.size();
1440     for (unsigned I : CompatIndices) {
1441       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1442            diag::note_compat_assoc)
1443         << Types[I]->getTypeLoc().getSourceRange()
1444         << Types[I]->getType();
1445     }
1446     return ExprError();
1447   }
1448 
1449   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1450   // its controlling expression shall have type compatible with exactly one of
1451   // the types named in its generic association list."
1452   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1453     // We strip parens here because the controlling expression is typically
1454     // parenthesized in macro definitions.
1455     ControllingExpr = ControllingExpr->IgnoreParens();
1456     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1457       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1458     return ExprError();
1459   }
1460 
1461   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1462   // type name that is compatible with the type of the controlling expression,
1463   // then the result expression of the generic selection is the expression
1464   // in that generic association. Otherwise, the result expression of the
1465   // generic selection is the expression in the default generic association."
1466   unsigned ResultIndex =
1467     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1468 
1469   return new (Context) GenericSelectionExpr(
1470       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1471       ContainsUnexpandedParameterPack, ResultIndex);
1472 }
1473 
1474 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1475 /// location of the token and the offset of the ud-suffix within it.
1476 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1477                                      unsigned Offset) {
1478   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1479                                         S.getLangOpts());
1480 }
1481 
1482 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1483 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1484 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1485                                                  IdentifierInfo *UDSuffix,
1486                                                  SourceLocation UDSuffixLoc,
1487                                                  ArrayRef<Expr*> Args,
1488                                                  SourceLocation LitEndLoc) {
1489   assert(Args.size() <= 2 && "too many arguments for literal operator");
1490 
1491   QualType ArgTy[2];
1492   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1493     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1494     if (ArgTy[ArgIdx]->isArrayType())
1495       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1496   }
1497 
1498   DeclarationName OpName =
1499     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1500   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1501   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1502 
1503   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1504   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1505                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1506                               /*AllowStringTemplate*/ false,
1507                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1508     return ExprError();
1509 
1510   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1511 }
1512 
1513 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1514 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1515 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1516 /// multiple tokens.  However, the common case is that StringToks points to one
1517 /// string.
1518 ///
1519 ExprResult
1520 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1521   assert(!StringToks.empty() && "Must have at least one string!");
1522 
1523   StringLiteralParser Literal(StringToks, PP);
1524   if (Literal.hadError)
1525     return ExprError();
1526 
1527   SmallVector<SourceLocation, 4> StringTokLocs;
1528   for (const Token &Tok : StringToks)
1529     StringTokLocs.push_back(Tok.getLocation());
1530 
1531   QualType CharTy = Context.CharTy;
1532   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1533   if (Literal.isWide()) {
1534     CharTy = Context.getWideCharType();
1535     Kind = StringLiteral::Wide;
1536   } else if (Literal.isUTF8()) {
1537     Kind = StringLiteral::UTF8;
1538   } else if (Literal.isUTF16()) {
1539     CharTy = Context.Char16Ty;
1540     Kind = StringLiteral::UTF16;
1541   } else if (Literal.isUTF32()) {
1542     CharTy = Context.Char32Ty;
1543     Kind = StringLiteral::UTF32;
1544   } else if (Literal.isPascal()) {
1545     CharTy = Context.UnsignedCharTy;
1546   }
1547 
1548   QualType CharTyConst = CharTy;
1549   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1550   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1551     CharTyConst.addConst();
1552 
1553   // Get an array type for the string, according to C99 6.4.5.  This includes
1554   // the nul terminator character as well as the string length for pascal
1555   // strings.
1556   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1557                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1558                                  ArrayType::Normal, 0);
1559 
1560   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1561   if (getLangOpts().OpenCL) {
1562     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1563   }
1564 
1565   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1566   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1567                                              Kind, Literal.Pascal, StrTy,
1568                                              &StringTokLocs[0],
1569                                              StringTokLocs.size());
1570   if (Literal.getUDSuffix().empty())
1571     return Lit;
1572 
1573   // We're building a user-defined literal.
1574   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1575   SourceLocation UDSuffixLoc =
1576     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1577                    Literal.getUDSuffixOffset());
1578 
1579   // Make sure we're allowed user-defined literals here.
1580   if (!UDLScope)
1581     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1582 
1583   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1584   //   operator "" X (str, len)
1585   QualType SizeType = Context.getSizeType();
1586 
1587   DeclarationName OpName =
1588     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1589   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1590   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1591 
1592   QualType ArgTy[] = {
1593     Context.getArrayDecayedType(StrTy), SizeType
1594   };
1595 
1596   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1597   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1598                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1599                                 /*AllowStringTemplate*/ true,
1600                                 /*DiagnoseMissing*/ true)) {
1601 
1602   case LOLR_Cooked: {
1603     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1604     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1605                                                     StringTokLocs[0]);
1606     Expr *Args[] = { Lit, LenArg };
1607 
1608     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1609   }
1610 
1611   case LOLR_StringTemplate: {
1612     TemplateArgumentListInfo ExplicitArgs;
1613 
1614     unsigned CharBits = Context.getIntWidth(CharTy);
1615     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1616     llvm::APSInt Value(CharBits, CharIsUnsigned);
1617 
1618     TemplateArgument TypeArg(CharTy);
1619     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1620     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1621 
1622     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1623       Value = Lit->getCodeUnit(I);
1624       TemplateArgument Arg(Context, Value, CharTy);
1625       TemplateArgumentLocInfo ArgInfo;
1626       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1627     }
1628     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1629                                     &ExplicitArgs);
1630   }
1631   case LOLR_Raw:
1632   case LOLR_Template:
1633   case LOLR_ErrorNoDiagnostic:
1634     llvm_unreachable("unexpected literal operator lookup result");
1635   case LOLR_Error:
1636     return ExprError();
1637   }
1638   llvm_unreachable("unexpected literal operator lookup result");
1639 }
1640 
1641 ExprResult
1642 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1643                        SourceLocation Loc,
1644                        const CXXScopeSpec *SS) {
1645   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1646   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1647 }
1648 
1649 /// BuildDeclRefExpr - Build an expression that references a
1650 /// declaration that does not require a closure capture.
1651 ExprResult
1652 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1653                        const DeclarationNameInfo &NameInfo,
1654                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1655                        const TemplateArgumentListInfo *TemplateArgs) {
1656   bool RefersToCapturedVariable =
1657       isa<VarDecl>(D) &&
1658       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1659 
1660   DeclRefExpr *E;
1661   if (isa<VarTemplateSpecializationDecl>(D)) {
1662     VarTemplateSpecializationDecl *VarSpec =
1663         cast<VarTemplateSpecializationDecl>(D);
1664 
1665     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1666                                         : NestedNameSpecifierLoc(),
1667                             VarSpec->getTemplateKeywordLoc(), D,
1668                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1669                             FoundD, TemplateArgs);
1670   } else {
1671     assert(!TemplateArgs && "No template arguments for non-variable"
1672                             " template specialization references");
1673     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1674                                         : NestedNameSpecifierLoc(),
1675                             SourceLocation(), D, RefersToCapturedVariable,
1676                             NameInfo, Ty, VK, FoundD);
1677   }
1678 
1679   MarkDeclRefReferenced(E);
1680 
1681   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1682       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1683       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1684       recordUseOfEvaluatedWeak(E);
1685 
1686   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1687   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1688     FD = IFD->getAnonField();
1689   if (FD) {
1690     UnusedPrivateFields.remove(FD);
1691     // Just in case we're building an illegal pointer-to-member.
1692     if (FD->isBitField())
1693       E->setObjectKind(OK_BitField);
1694   }
1695 
1696   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1697   // designates a bit-field.
1698   if (auto *BD = dyn_cast<BindingDecl>(D))
1699     if (auto *BE = BD->getBinding())
1700       E->setObjectKind(BE->getObjectKind());
1701 
1702   return E;
1703 }
1704 
1705 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1706 /// possibly a list of template arguments.
1707 ///
1708 /// If this produces template arguments, it is permitted to call
1709 /// DecomposeTemplateName.
1710 ///
1711 /// This actually loses a lot of source location information for
1712 /// non-standard name kinds; we should consider preserving that in
1713 /// some way.
1714 void
1715 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1716                              TemplateArgumentListInfo &Buffer,
1717                              DeclarationNameInfo &NameInfo,
1718                              const TemplateArgumentListInfo *&TemplateArgs) {
1719   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1720     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1721     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1722 
1723     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1724                                        Id.TemplateId->NumArgs);
1725     translateTemplateArguments(TemplateArgsPtr, Buffer);
1726 
1727     TemplateName TName = Id.TemplateId->Template.get();
1728     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1729     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1730     TemplateArgs = &Buffer;
1731   } else {
1732     NameInfo = GetNameFromUnqualifiedId(Id);
1733     TemplateArgs = nullptr;
1734   }
1735 }
1736 
1737 static void emitEmptyLookupTypoDiagnostic(
1738     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1739     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1740     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1741   DeclContext *Ctx =
1742       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1743   if (!TC) {
1744     // Emit a special diagnostic for failed member lookups.
1745     // FIXME: computing the declaration context might fail here (?)
1746     if (Ctx)
1747       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1748                                                  << SS.getRange();
1749     else
1750       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1751     return;
1752   }
1753 
1754   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1755   bool DroppedSpecifier =
1756       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1757   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1758                         ? diag::note_implicit_param_decl
1759                         : diag::note_previous_decl;
1760   if (!Ctx)
1761     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1762                          SemaRef.PDiag(NoteID));
1763   else
1764     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1765                                  << Typo << Ctx << DroppedSpecifier
1766                                  << SS.getRange(),
1767                          SemaRef.PDiag(NoteID));
1768 }
1769 
1770 /// Diagnose an empty lookup.
1771 ///
1772 /// \return false if new lookup candidates were found
1773 bool
1774 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1775                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1776                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1777                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1778   DeclarationName Name = R.getLookupName();
1779 
1780   unsigned diagnostic = diag::err_undeclared_var_use;
1781   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1782   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1783       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1784       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1785     diagnostic = diag::err_undeclared_use;
1786     diagnostic_suggest = diag::err_undeclared_use_suggest;
1787   }
1788 
1789   // If the original lookup was an unqualified lookup, fake an
1790   // unqualified lookup.  This is useful when (for example) the
1791   // original lookup would not have found something because it was a
1792   // dependent name.
1793   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1794   while (DC) {
1795     if (isa<CXXRecordDecl>(DC)) {
1796       LookupQualifiedName(R, DC);
1797 
1798       if (!R.empty()) {
1799         // Don't give errors about ambiguities in this lookup.
1800         R.suppressDiagnostics();
1801 
1802         // During a default argument instantiation the CurContext points
1803         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1804         // function parameter list, hence add an explicit check.
1805         bool isDefaultArgument =
1806             !CodeSynthesisContexts.empty() &&
1807             CodeSynthesisContexts.back().Kind ==
1808                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1809         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1810         bool isInstance = CurMethod &&
1811                           CurMethod->isInstance() &&
1812                           DC == CurMethod->getParent() && !isDefaultArgument;
1813 
1814         // Give a code modification hint to insert 'this->'.
1815         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1816         // Actually quite difficult!
1817         if (getLangOpts().MSVCCompat)
1818           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1819         if (isInstance) {
1820           Diag(R.getNameLoc(), diagnostic) << Name
1821             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1822           CheckCXXThisCapture(R.getNameLoc());
1823         } else {
1824           Diag(R.getNameLoc(), diagnostic) << Name;
1825         }
1826 
1827         // Do we really want to note all of these?
1828         for (NamedDecl *D : R)
1829           Diag(D->getLocation(), diag::note_dependent_var_use);
1830 
1831         // Return true if we are inside a default argument instantiation
1832         // and the found name refers to an instance member function, otherwise
1833         // the function calling DiagnoseEmptyLookup will try to create an
1834         // implicit member call and this is wrong for default argument.
1835         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1836           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1837           return true;
1838         }
1839 
1840         // Tell the callee to try to recover.
1841         return false;
1842       }
1843 
1844       R.clear();
1845     }
1846 
1847     // In Microsoft mode, if we are performing lookup from within a friend
1848     // function definition declared at class scope then we must set
1849     // DC to the lexical parent to be able to search into the parent
1850     // class.
1851     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1852         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1853         DC->getLexicalParent()->isRecord())
1854       DC = DC->getLexicalParent();
1855     else
1856       DC = DC->getParent();
1857   }
1858 
1859   // We didn't find anything, so try to correct for a typo.
1860   TypoCorrection Corrected;
1861   if (S && Out) {
1862     SourceLocation TypoLoc = R.getNameLoc();
1863     assert(!ExplicitTemplateArgs &&
1864            "Diagnosing an empty lookup with explicit template args!");
1865     *Out = CorrectTypoDelayed(
1866         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1867         [=](const TypoCorrection &TC) {
1868           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1869                                         diagnostic, diagnostic_suggest);
1870         },
1871         nullptr, CTK_ErrorRecovery);
1872     if (*Out)
1873       return true;
1874   } else if (S && (Corrected =
1875                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1876                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1877     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1878     bool DroppedSpecifier =
1879         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1880     R.setLookupName(Corrected.getCorrection());
1881 
1882     bool AcceptableWithRecovery = false;
1883     bool AcceptableWithoutRecovery = false;
1884     NamedDecl *ND = Corrected.getFoundDecl();
1885     if (ND) {
1886       if (Corrected.isOverloaded()) {
1887         OverloadCandidateSet OCS(R.getNameLoc(),
1888                                  OverloadCandidateSet::CSK_Normal);
1889         OverloadCandidateSet::iterator Best;
1890         for (NamedDecl *CD : Corrected) {
1891           if (FunctionTemplateDecl *FTD =
1892                    dyn_cast<FunctionTemplateDecl>(CD))
1893             AddTemplateOverloadCandidate(
1894                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1895                 Args, OCS);
1896           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1897             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1898               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1899                                    Args, OCS);
1900         }
1901         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1902         case OR_Success:
1903           ND = Best->FoundDecl;
1904           Corrected.setCorrectionDecl(ND);
1905           break;
1906         default:
1907           // FIXME: Arbitrarily pick the first declaration for the note.
1908           Corrected.setCorrectionDecl(ND);
1909           break;
1910         }
1911       }
1912       R.addDecl(ND);
1913       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1914         CXXRecordDecl *Record = nullptr;
1915         if (Corrected.getCorrectionSpecifier()) {
1916           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1917           Record = Ty->getAsCXXRecordDecl();
1918         }
1919         if (!Record)
1920           Record = cast<CXXRecordDecl>(
1921               ND->getDeclContext()->getRedeclContext());
1922         R.setNamingClass(Record);
1923       }
1924 
1925       auto *UnderlyingND = ND->getUnderlyingDecl();
1926       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1927                                isa<FunctionTemplateDecl>(UnderlyingND);
1928       // FIXME: If we ended up with a typo for a type name or
1929       // Objective-C class name, we're in trouble because the parser
1930       // is in the wrong place to recover. Suggest the typo
1931       // correction, but don't make it a fix-it since we're not going
1932       // to recover well anyway.
1933       AcceptableWithoutRecovery =
1934           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1935     } else {
1936       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1937       // because we aren't able to recover.
1938       AcceptableWithoutRecovery = true;
1939     }
1940 
1941     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1942       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1943                             ? diag::note_implicit_param_decl
1944                             : diag::note_previous_decl;
1945       if (SS.isEmpty())
1946         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1947                      PDiag(NoteID), AcceptableWithRecovery);
1948       else
1949         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1950                                   << Name << computeDeclContext(SS, false)
1951                                   << DroppedSpecifier << SS.getRange(),
1952                      PDiag(NoteID), AcceptableWithRecovery);
1953 
1954       // Tell the callee whether to try to recover.
1955       return !AcceptableWithRecovery;
1956     }
1957   }
1958   R.clear();
1959 
1960   // Emit a special diagnostic for failed member lookups.
1961   // FIXME: computing the declaration context might fail here (?)
1962   if (!SS.isEmpty()) {
1963     Diag(R.getNameLoc(), diag::err_no_member)
1964       << Name << computeDeclContext(SS, false)
1965       << SS.getRange();
1966     return true;
1967   }
1968 
1969   // Give up, we can't recover.
1970   Diag(R.getNameLoc(), diagnostic) << Name;
1971   return true;
1972 }
1973 
1974 /// In Microsoft mode, if we are inside a template class whose parent class has
1975 /// dependent base classes, and we can't resolve an unqualified identifier, then
1976 /// assume the identifier is a member of a dependent base class.  We can only
1977 /// recover successfully in static methods, instance methods, and other contexts
1978 /// where 'this' is available.  This doesn't precisely match MSVC's
1979 /// instantiation model, but it's close enough.
1980 static Expr *
1981 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1982                                DeclarationNameInfo &NameInfo,
1983                                SourceLocation TemplateKWLoc,
1984                                const TemplateArgumentListInfo *TemplateArgs) {
1985   // Only try to recover from lookup into dependent bases in static methods or
1986   // contexts where 'this' is available.
1987   QualType ThisType = S.getCurrentThisType();
1988   const CXXRecordDecl *RD = nullptr;
1989   if (!ThisType.isNull())
1990     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1991   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1992     RD = MD->getParent();
1993   if (!RD || !RD->hasAnyDependentBases())
1994     return nullptr;
1995 
1996   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1997   // is available, suggest inserting 'this->' as a fixit.
1998   SourceLocation Loc = NameInfo.getLoc();
1999   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2000   DB << NameInfo.getName() << RD;
2001 
2002   if (!ThisType.isNull()) {
2003     DB << FixItHint::CreateInsertion(Loc, "this->");
2004     return CXXDependentScopeMemberExpr::Create(
2005         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2006         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2007         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2008   }
2009 
2010   // Synthesize a fake NNS that points to the derived class.  This will
2011   // perform name lookup during template instantiation.
2012   CXXScopeSpec SS;
2013   auto *NNS =
2014       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2015   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2016   return DependentScopeDeclRefExpr::Create(
2017       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2018       TemplateArgs);
2019 }
2020 
2021 ExprResult
2022 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2023                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2024                         bool HasTrailingLParen, bool IsAddressOfOperand,
2025                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2026                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2027   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2028          "cannot be direct & operand and have a trailing lparen");
2029   if (SS.isInvalid())
2030     return ExprError();
2031 
2032   TemplateArgumentListInfo TemplateArgsBuffer;
2033 
2034   // Decompose the UnqualifiedId into the following data.
2035   DeclarationNameInfo NameInfo;
2036   const TemplateArgumentListInfo *TemplateArgs;
2037   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2038 
2039   DeclarationName Name = NameInfo.getName();
2040   IdentifierInfo *II = Name.getAsIdentifierInfo();
2041   SourceLocation NameLoc = NameInfo.getLoc();
2042 
2043   if (II && II->isEditorPlaceholder()) {
2044     // FIXME: When typed placeholders are supported we can create a typed
2045     // placeholder expression node.
2046     return ExprError();
2047   }
2048 
2049   // C++ [temp.dep.expr]p3:
2050   //   An id-expression is type-dependent if it contains:
2051   //     -- an identifier that was declared with a dependent type,
2052   //        (note: handled after lookup)
2053   //     -- a template-id that is dependent,
2054   //        (note: handled in BuildTemplateIdExpr)
2055   //     -- a conversion-function-id that specifies a dependent type,
2056   //     -- a nested-name-specifier that contains a class-name that
2057   //        names a dependent type.
2058   // Determine whether this is a member of an unknown specialization;
2059   // we need to handle these differently.
2060   bool DependentID = false;
2061   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2062       Name.getCXXNameType()->isDependentType()) {
2063     DependentID = true;
2064   } else if (SS.isSet()) {
2065     if (DeclContext *DC = computeDeclContext(SS, false)) {
2066       if (RequireCompleteDeclContext(SS, DC))
2067         return ExprError();
2068     } else {
2069       DependentID = true;
2070     }
2071   }
2072 
2073   if (DependentID)
2074     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2075                                       IsAddressOfOperand, TemplateArgs);
2076 
2077   // Perform the required lookup.
2078   LookupResult R(*this, NameInfo,
2079                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2080                      ? LookupObjCImplicitSelfParam
2081                      : LookupOrdinaryName);
2082   if (TemplateArgs) {
2083     // Lookup the template name again to correctly establish the context in
2084     // which it was found. This is really unfortunate as we already did the
2085     // lookup to determine that it was a template name in the first place. If
2086     // this becomes a performance hit, we can work harder to preserve those
2087     // results until we get here but it's likely not worth it.
2088     bool MemberOfUnknownSpecialization;
2089     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2090                        MemberOfUnknownSpecialization);
2091 
2092     if (MemberOfUnknownSpecialization ||
2093         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2094       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2095                                         IsAddressOfOperand, TemplateArgs);
2096   } else {
2097     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2098     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2099 
2100     // If the result might be in a dependent base class, this is a dependent
2101     // id-expression.
2102     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2103       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2104                                         IsAddressOfOperand, TemplateArgs);
2105 
2106     // If this reference is in an Objective-C method, then we need to do
2107     // some special Objective-C lookup, too.
2108     if (IvarLookupFollowUp) {
2109       ExprResult E(LookupInObjCMethod(R, S, II, true));
2110       if (E.isInvalid())
2111         return ExprError();
2112 
2113       if (Expr *Ex = E.getAs<Expr>())
2114         return Ex;
2115     }
2116   }
2117 
2118   if (R.isAmbiguous())
2119     return ExprError();
2120 
2121   // This could be an implicitly declared function reference (legal in C90,
2122   // extension in C99, forbidden in C++).
2123   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2124     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2125     if (D) R.addDecl(D);
2126   }
2127 
2128   // Determine whether this name might be a candidate for
2129   // argument-dependent lookup.
2130   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2131 
2132   if (R.empty() && !ADL) {
2133     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2134       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2135                                                    TemplateKWLoc, TemplateArgs))
2136         return E;
2137     }
2138 
2139     // Don't diagnose an empty lookup for inline assembly.
2140     if (IsInlineAsmIdentifier)
2141       return ExprError();
2142 
2143     // If this name wasn't predeclared and if this is not a function
2144     // call, diagnose the problem.
2145     TypoExpr *TE = nullptr;
2146     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2147         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2148     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2149     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2150            "Typo correction callback misconfigured");
2151     if (CCC) {
2152       // Make sure the callback knows what the typo being diagnosed is.
2153       CCC->setTypoName(II);
2154       if (SS.isValid())
2155         CCC->setTypoNNS(SS.getScopeRep());
2156     }
2157     if (DiagnoseEmptyLookup(S, SS, R,
2158                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2159                             nullptr, None, &TE)) {
2160       if (TE && KeywordReplacement) {
2161         auto &State = getTypoExprState(TE);
2162         auto BestTC = State.Consumer->getNextCorrection();
2163         if (BestTC.isKeyword()) {
2164           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2165           if (State.DiagHandler)
2166             State.DiagHandler(BestTC);
2167           KeywordReplacement->startToken();
2168           KeywordReplacement->setKind(II->getTokenID());
2169           KeywordReplacement->setIdentifierInfo(II);
2170           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2171           // Clean up the state associated with the TypoExpr, since it has
2172           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2173           clearDelayedTypo(TE);
2174           // Signal that a correction to a keyword was performed by returning a
2175           // valid-but-null ExprResult.
2176           return (Expr*)nullptr;
2177         }
2178         State.Consumer->resetCorrectionStream();
2179       }
2180       return TE ? TE : ExprError();
2181     }
2182 
2183     assert(!R.empty() &&
2184            "DiagnoseEmptyLookup returned false but added no results");
2185 
2186     // If we found an Objective-C instance variable, let
2187     // LookupInObjCMethod build the appropriate expression to
2188     // reference the ivar.
2189     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2190       R.clear();
2191       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2192       // In a hopelessly buggy code, Objective-C instance variable
2193       // lookup fails and no expression will be built to reference it.
2194       if (!E.isInvalid() && !E.get())
2195         return ExprError();
2196       return E;
2197     }
2198   }
2199 
2200   // This is guaranteed from this point on.
2201   assert(!R.empty() || ADL);
2202 
2203   // Check whether this might be a C++ implicit instance member access.
2204   // C++ [class.mfct.non-static]p3:
2205   //   When an id-expression that is not part of a class member access
2206   //   syntax and not used to form a pointer to member is used in the
2207   //   body of a non-static member function of class X, if name lookup
2208   //   resolves the name in the id-expression to a non-static non-type
2209   //   member of some class C, the id-expression is transformed into a
2210   //   class member access expression using (*this) as the
2211   //   postfix-expression to the left of the . operator.
2212   //
2213   // But we don't actually need to do this for '&' operands if R
2214   // resolved to a function or overloaded function set, because the
2215   // expression is ill-formed if it actually works out to be a
2216   // non-static member function:
2217   //
2218   // C++ [expr.ref]p4:
2219   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2220   //   [t]he expression can be used only as the left-hand operand of a
2221   //   member function call.
2222   //
2223   // There are other safeguards against such uses, but it's important
2224   // to get this right here so that we don't end up making a
2225   // spuriously dependent expression if we're inside a dependent
2226   // instance method.
2227   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2228     bool MightBeImplicitMember;
2229     if (!IsAddressOfOperand)
2230       MightBeImplicitMember = true;
2231     else if (!SS.isEmpty())
2232       MightBeImplicitMember = false;
2233     else if (R.isOverloadedResult())
2234       MightBeImplicitMember = false;
2235     else if (R.isUnresolvableResult())
2236       MightBeImplicitMember = true;
2237     else
2238       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2239                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2240                               isa<MSPropertyDecl>(R.getFoundDecl());
2241 
2242     if (MightBeImplicitMember)
2243       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2244                                              R, TemplateArgs, S);
2245   }
2246 
2247   if (TemplateArgs || TemplateKWLoc.isValid()) {
2248 
2249     // In C++1y, if this is a variable template id, then check it
2250     // in BuildTemplateIdExpr().
2251     // The single lookup result must be a variable template declaration.
2252     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2253         Id.TemplateId->Kind == TNK_Var_template) {
2254       assert(R.getAsSingle<VarTemplateDecl>() &&
2255              "There should only be one declaration found.");
2256     }
2257 
2258     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2259   }
2260 
2261   return BuildDeclarationNameExpr(SS, R, ADL);
2262 }
2263 
2264 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2265 /// declaration name, generally during template instantiation.
2266 /// There's a large number of things which don't need to be done along
2267 /// this path.
2268 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2269     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2270     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2271   DeclContext *DC = computeDeclContext(SS, false);
2272   if (!DC)
2273     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2274                                      NameInfo, /*TemplateArgs=*/nullptr);
2275 
2276   if (RequireCompleteDeclContext(SS, DC))
2277     return ExprError();
2278 
2279   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2280   LookupQualifiedName(R, DC);
2281 
2282   if (R.isAmbiguous())
2283     return ExprError();
2284 
2285   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2286     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2287                                      NameInfo, /*TemplateArgs=*/nullptr);
2288 
2289   if (R.empty()) {
2290     Diag(NameInfo.getLoc(), diag::err_no_member)
2291       << NameInfo.getName() << DC << SS.getRange();
2292     return ExprError();
2293   }
2294 
2295   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2296     // Diagnose a missing typename if this resolved unambiguously to a type in
2297     // a dependent context.  If we can recover with a type, downgrade this to
2298     // a warning in Microsoft compatibility mode.
2299     unsigned DiagID = diag::err_typename_missing;
2300     if (RecoveryTSI && getLangOpts().MSVCCompat)
2301       DiagID = diag::ext_typename_missing;
2302     SourceLocation Loc = SS.getBeginLoc();
2303     auto D = Diag(Loc, DiagID);
2304     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2305       << SourceRange(Loc, NameInfo.getEndLoc());
2306 
2307     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2308     // context.
2309     if (!RecoveryTSI)
2310       return ExprError();
2311 
2312     // Only issue the fixit if we're prepared to recover.
2313     D << FixItHint::CreateInsertion(Loc, "typename ");
2314 
2315     // Recover by pretending this was an elaborated type.
2316     QualType Ty = Context.getTypeDeclType(TD);
2317     TypeLocBuilder TLB;
2318     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2319 
2320     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2321     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2322     QTL.setElaboratedKeywordLoc(SourceLocation());
2323     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2324 
2325     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2326 
2327     return ExprEmpty();
2328   }
2329 
2330   // Defend against this resolving to an implicit member access. We usually
2331   // won't get here if this might be a legitimate a class member (we end up in
2332   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2333   // a pointer-to-member or in an unevaluated context in C++11.
2334   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2335     return BuildPossibleImplicitMemberExpr(SS,
2336                                            /*TemplateKWLoc=*/SourceLocation(),
2337                                            R, /*TemplateArgs=*/nullptr, S);
2338 
2339   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2340 }
2341 
2342 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2343 /// detected that we're currently inside an ObjC method.  Perform some
2344 /// additional lookup.
2345 ///
2346 /// Ideally, most of this would be done by lookup, but there's
2347 /// actually quite a lot of extra work involved.
2348 ///
2349 /// Returns a null sentinel to indicate trivial success.
2350 ExprResult
2351 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2352                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2353   SourceLocation Loc = Lookup.getNameLoc();
2354   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2355 
2356   // Check for error condition which is already reported.
2357   if (!CurMethod)
2358     return ExprError();
2359 
2360   // There are two cases to handle here.  1) scoped lookup could have failed,
2361   // in which case we should look for an ivar.  2) scoped lookup could have
2362   // found a decl, but that decl is outside the current instance method (i.e.
2363   // a global variable).  In these two cases, we do a lookup for an ivar with
2364   // this name, if the lookup sucedes, we replace it our current decl.
2365 
2366   // If we're in a class method, we don't normally want to look for
2367   // ivars.  But if we don't find anything else, and there's an
2368   // ivar, that's an error.
2369   bool IsClassMethod = CurMethod->isClassMethod();
2370 
2371   bool LookForIvars;
2372   if (Lookup.empty())
2373     LookForIvars = true;
2374   else if (IsClassMethod)
2375     LookForIvars = false;
2376   else
2377     LookForIvars = (Lookup.isSingleResult() &&
2378                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2379   ObjCInterfaceDecl *IFace = nullptr;
2380   if (LookForIvars) {
2381     IFace = CurMethod->getClassInterface();
2382     ObjCInterfaceDecl *ClassDeclared;
2383     ObjCIvarDecl *IV = nullptr;
2384     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2385       // Diagnose using an ivar in a class method.
2386       if (IsClassMethod)
2387         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2388                          << IV->getDeclName());
2389 
2390       // If we're referencing an invalid decl, just return this as a silent
2391       // error node.  The error diagnostic was already emitted on the decl.
2392       if (IV->isInvalidDecl())
2393         return ExprError();
2394 
2395       // Check if referencing a field with __attribute__((deprecated)).
2396       if (DiagnoseUseOfDecl(IV, Loc))
2397         return ExprError();
2398 
2399       // Diagnose the use of an ivar outside of the declaring class.
2400       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2401           !declaresSameEntity(ClassDeclared, IFace) &&
2402           !getLangOpts().DebuggerSupport)
2403         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2404 
2405       // FIXME: This should use a new expr for a direct reference, don't
2406       // turn this into Self->ivar, just return a BareIVarExpr or something.
2407       IdentifierInfo &II = Context.Idents.get("self");
2408       UnqualifiedId SelfName;
2409       SelfName.setIdentifier(&II, SourceLocation());
2410       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2411       CXXScopeSpec SelfScopeSpec;
2412       SourceLocation TemplateKWLoc;
2413       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2414                                               SelfName, false, false);
2415       if (SelfExpr.isInvalid())
2416         return ExprError();
2417 
2418       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2419       if (SelfExpr.isInvalid())
2420         return ExprError();
2421 
2422       MarkAnyDeclReferenced(Loc, IV, true);
2423 
2424       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2425       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2426           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2427         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2428 
2429       ObjCIvarRefExpr *Result = new (Context)
2430           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2431                           IV->getLocation(), SelfExpr.get(), true, true);
2432 
2433       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2434         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2435           recordUseOfEvaluatedWeak(Result);
2436       }
2437       if (getLangOpts().ObjCAutoRefCount) {
2438         if (CurContext->isClosure())
2439           Diag(Loc, diag::warn_implicitly_retains_self)
2440             << FixItHint::CreateInsertion(Loc, "self->");
2441       }
2442 
2443       return Result;
2444     }
2445   } else if (CurMethod->isInstanceMethod()) {
2446     // We should warn if a local variable hides an ivar.
2447     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2448       ObjCInterfaceDecl *ClassDeclared;
2449       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2450         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2451             declaresSameEntity(IFace, ClassDeclared))
2452           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2453       }
2454     }
2455   } else if (Lookup.isSingleResult() &&
2456              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2457     // If accessing a stand-alone ivar in a class method, this is an error.
2458     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2459       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2460                        << IV->getDeclName());
2461   }
2462 
2463   if (Lookup.empty() && II && AllowBuiltinCreation) {
2464     // FIXME. Consolidate this with similar code in LookupName.
2465     if (unsigned BuiltinID = II->getBuiltinID()) {
2466       if (!(getLangOpts().CPlusPlus &&
2467             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2468         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2469                                            S, Lookup.isForRedeclaration(),
2470                                            Lookup.getNameLoc());
2471         if (D) Lookup.addDecl(D);
2472       }
2473     }
2474   }
2475   // Sentinel value saying that we didn't do anything special.
2476   return ExprResult((Expr *)nullptr);
2477 }
2478 
2479 /// \brief Cast a base object to a member's actual type.
2480 ///
2481 /// Logically this happens in three phases:
2482 ///
2483 /// * First we cast from the base type to the naming class.
2484 ///   The naming class is the class into which we were looking
2485 ///   when we found the member;  it's the qualifier type if a
2486 ///   qualifier was provided, and otherwise it's the base type.
2487 ///
2488 /// * Next we cast from the naming class to the declaring class.
2489 ///   If the member we found was brought into a class's scope by
2490 ///   a using declaration, this is that class;  otherwise it's
2491 ///   the class declaring the member.
2492 ///
2493 /// * Finally we cast from the declaring class to the "true"
2494 ///   declaring class of the member.  This conversion does not
2495 ///   obey access control.
2496 ExprResult
2497 Sema::PerformObjectMemberConversion(Expr *From,
2498                                     NestedNameSpecifier *Qualifier,
2499                                     NamedDecl *FoundDecl,
2500                                     NamedDecl *Member) {
2501   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2502   if (!RD)
2503     return From;
2504 
2505   QualType DestRecordType;
2506   QualType DestType;
2507   QualType FromRecordType;
2508   QualType FromType = From->getType();
2509   bool PointerConversions = false;
2510   if (isa<FieldDecl>(Member)) {
2511     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2512 
2513     if (FromType->getAs<PointerType>()) {
2514       DestType = Context.getPointerType(DestRecordType);
2515       FromRecordType = FromType->getPointeeType();
2516       PointerConversions = true;
2517     } else {
2518       DestType = DestRecordType;
2519       FromRecordType = FromType;
2520     }
2521   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2522     if (Method->isStatic())
2523       return From;
2524 
2525     DestType = Method->getThisType(Context);
2526     DestRecordType = DestType->getPointeeType();
2527 
2528     if (FromType->getAs<PointerType>()) {
2529       FromRecordType = FromType->getPointeeType();
2530       PointerConversions = true;
2531     } else {
2532       FromRecordType = FromType;
2533       DestType = DestRecordType;
2534     }
2535   } else {
2536     // No conversion necessary.
2537     return From;
2538   }
2539 
2540   if (DestType->isDependentType() || FromType->isDependentType())
2541     return From;
2542 
2543   // If the unqualified types are the same, no conversion is necessary.
2544   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2545     return From;
2546 
2547   SourceRange FromRange = From->getSourceRange();
2548   SourceLocation FromLoc = FromRange.getBegin();
2549 
2550   ExprValueKind VK = From->getValueKind();
2551 
2552   // C++ [class.member.lookup]p8:
2553   //   [...] Ambiguities can often be resolved by qualifying a name with its
2554   //   class name.
2555   //
2556   // If the member was a qualified name and the qualified referred to a
2557   // specific base subobject type, we'll cast to that intermediate type
2558   // first and then to the object in which the member is declared. That allows
2559   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2560   //
2561   //   class Base { public: int x; };
2562   //   class Derived1 : public Base { };
2563   //   class Derived2 : public Base { };
2564   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2565   //
2566   //   void VeryDerived::f() {
2567   //     x = 17; // error: ambiguous base subobjects
2568   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2569   //   }
2570   if (Qualifier && Qualifier->getAsType()) {
2571     QualType QType = QualType(Qualifier->getAsType(), 0);
2572     assert(QType->isRecordType() && "lookup done with non-record type");
2573 
2574     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2575 
2576     // In C++98, the qualifier type doesn't actually have to be a base
2577     // type of the object type, in which case we just ignore it.
2578     // Otherwise build the appropriate casts.
2579     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2580       CXXCastPath BasePath;
2581       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2582                                        FromLoc, FromRange, &BasePath))
2583         return ExprError();
2584 
2585       if (PointerConversions)
2586         QType = Context.getPointerType(QType);
2587       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2588                                VK, &BasePath).get();
2589 
2590       FromType = QType;
2591       FromRecordType = QRecordType;
2592 
2593       // If the qualifier type was the same as the destination type,
2594       // we're done.
2595       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2596         return From;
2597     }
2598   }
2599 
2600   bool IgnoreAccess = false;
2601 
2602   // If we actually found the member through a using declaration, cast
2603   // down to the using declaration's type.
2604   //
2605   // Pointer equality is fine here because only one declaration of a
2606   // class ever has member declarations.
2607   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2608     assert(isa<UsingShadowDecl>(FoundDecl));
2609     QualType URecordType = Context.getTypeDeclType(
2610                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2611 
2612     // We only need to do this if the naming-class to declaring-class
2613     // conversion is non-trivial.
2614     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2615       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2616       CXXCastPath BasePath;
2617       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2618                                        FromLoc, FromRange, &BasePath))
2619         return ExprError();
2620 
2621       QualType UType = URecordType;
2622       if (PointerConversions)
2623         UType = Context.getPointerType(UType);
2624       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2625                                VK, &BasePath).get();
2626       FromType = UType;
2627       FromRecordType = URecordType;
2628     }
2629 
2630     // We don't do access control for the conversion from the
2631     // declaring class to the true declaring class.
2632     IgnoreAccess = true;
2633   }
2634 
2635   CXXCastPath BasePath;
2636   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2637                                    FromLoc, FromRange, &BasePath,
2638                                    IgnoreAccess))
2639     return ExprError();
2640 
2641   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2642                            VK, &BasePath);
2643 }
2644 
2645 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2646                                       const LookupResult &R,
2647                                       bool HasTrailingLParen) {
2648   // Only when used directly as the postfix-expression of a call.
2649   if (!HasTrailingLParen)
2650     return false;
2651 
2652   // Never if a scope specifier was provided.
2653   if (SS.isSet())
2654     return false;
2655 
2656   // Only in C++ or ObjC++.
2657   if (!getLangOpts().CPlusPlus)
2658     return false;
2659 
2660   // Turn off ADL when we find certain kinds of declarations during
2661   // normal lookup:
2662   for (NamedDecl *D : R) {
2663     // C++0x [basic.lookup.argdep]p3:
2664     //     -- a declaration of a class member
2665     // Since using decls preserve this property, we check this on the
2666     // original decl.
2667     if (D->isCXXClassMember())
2668       return false;
2669 
2670     // C++0x [basic.lookup.argdep]p3:
2671     //     -- a block-scope function declaration that is not a
2672     //        using-declaration
2673     // NOTE: we also trigger this for function templates (in fact, we
2674     // don't check the decl type at all, since all other decl types
2675     // turn off ADL anyway).
2676     if (isa<UsingShadowDecl>(D))
2677       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2678     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2679       return false;
2680 
2681     // C++0x [basic.lookup.argdep]p3:
2682     //     -- a declaration that is neither a function or a function
2683     //        template
2684     // And also for builtin functions.
2685     if (isa<FunctionDecl>(D)) {
2686       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2687 
2688       // But also builtin functions.
2689       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2690         return false;
2691     } else if (!isa<FunctionTemplateDecl>(D))
2692       return false;
2693   }
2694 
2695   return true;
2696 }
2697 
2698 
2699 /// Diagnoses obvious problems with the use of the given declaration
2700 /// as an expression.  This is only actually called for lookups that
2701 /// were not overloaded, and it doesn't promise that the declaration
2702 /// will in fact be used.
2703 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2704   if (D->isInvalidDecl())
2705     return true;
2706 
2707   if (isa<TypedefNameDecl>(D)) {
2708     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2709     return true;
2710   }
2711 
2712   if (isa<ObjCInterfaceDecl>(D)) {
2713     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2714     return true;
2715   }
2716 
2717   if (isa<NamespaceDecl>(D)) {
2718     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2719     return true;
2720   }
2721 
2722   return false;
2723 }
2724 
2725 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2726                                           LookupResult &R, bool NeedsADL,
2727                                           bool AcceptInvalidDecl) {
2728   // If this is a single, fully-resolved result and we don't need ADL,
2729   // just build an ordinary singleton decl ref.
2730   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2731     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2732                                     R.getRepresentativeDecl(), nullptr,
2733                                     AcceptInvalidDecl);
2734 
2735   // We only need to check the declaration if there's exactly one
2736   // result, because in the overloaded case the results can only be
2737   // functions and function templates.
2738   if (R.isSingleResult() &&
2739       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2740     return ExprError();
2741 
2742   // Otherwise, just build an unresolved lookup expression.  Suppress
2743   // any lookup-related diagnostics; we'll hash these out later, when
2744   // we've picked a target.
2745   R.suppressDiagnostics();
2746 
2747   UnresolvedLookupExpr *ULE
2748     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2749                                    SS.getWithLocInContext(Context),
2750                                    R.getLookupNameInfo(),
2751                                    NeedsADL, R.isOverloadedResult(),
2752                                    R.begin(), R.end());
2753 
2754   return ULE;
2755 }
2756 
2757 static void
2758 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2759                                    ValueDecl *var, DeclContext *DC);
2760 
2761 /// \brief Complete semantic analysis for a reference to the given declaration.
2762 ExprResult Sema::BuildDeclarationNameExpr(
2763     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2764     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2765     bool AcceptInvalidDecl) {
2766   assert(D && "Cannot refer to a NULL declaration");
2767   assert(!isa<FunctionTemplateDecl>(D) &&
2768          "Cannot refer unambiguously to a function template");
2769 
2770   SourceLocation Loc = NameInfo.getLoc();
2771   if (CheckDeclInExpr(*this, Loc, D))
2772     return ExprError();
2773 
2774   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2775     // Specifically diagnose references to class templates that are missing
2776     // a template argument list.
2777     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2778                                            << Template << SS.getRange();
2779     Diag(Template->getLocation(), diag::note_template_decl_here);
2780     return ExprError();
2781   }
2782 
2783   // Make sure that we're referring to a value.
2784   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2785   if (!VD) {
2786     Diag(Loc, diag::err_ref_non_value)
2787       << D << SS.getRange();
2788     Diag(D->getLocation(), diag::note_declared_at);
2789     return ExprError();
2790   }
2791 
2792   // Check whether this declaration can be used. Note that we suppress
2793   // this check when we're going to perform argument-dependent lookup
2794   // on this function name, because this might not be the function
2795   // that overload resolution actually selects.
2796   if (DiagnoseUseOfDecl(VD, Loc))
2797     return ExprError();
2798 
2799   // Only create DeclRefExpr's for valid Decl's.
2800   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2801     return ExprError();
2802 
2803   // Handle members of anonymous structs and unions.  If we got here,
2804   // and the reference is to a class member indirect field, then this
2805   // must be the subject of a pointer-to-member expression.
2806   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2807     if (!indirectField->isCXXClassMember())
2808       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2809                                                       indirectField);
2810 
2811   {
2812     QualType type = VD->getType();
2813     if (type.isNull())
2814       return ExprError();
2815     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2816       // C++ [except.spec]p17:
2817       //   An exception-specification is considered to be needed when:
2818       //   - in an expression, the function is the unique lookup result or
2819       //     the selected member of a set of overloaded functions.
2820       ResolveExceptionSpec(Loc, FPT);
2821       type = VD->getType();
2822     }
2823     ExprValueKind valueKind = VK_RValue;
2824 
2825     switch (D->getKind()) {
2826     // Ignore all the non-ValueDecl kinds.
2827 #define ABSTRACT_DECL(kind)
2828 #define VALUE(type, base)
2829 #define DECL(type, base) \
2830     case Decl::type:
2831 #include "clang/AST/DeclNodes.inc"
2832       llvm_unreachable("invalid value decl kind");
2833 
2834     // These shouldn't make it here.
2835     case Decl::ObjCAtDefsField:
2836     case Decl::ObjCIvar:
2837       llvm_unreachable("forming non-member reference to ivar?");
2838 
2839     // Enum constants are always r-values and never references.
2840     // Unresolved using declarations are dependent.
2841     case Decl::EnumConstant:
2842     case Decl::UnresolvedUsingValue:
2843     case Decl::OMPDeclareReduction:
2844       valueKind = VK_RValue;
2845       break;
2846 
2847     // Fields and indirect fields that got here must be for
2848     // pointer-to-member expressions; we just call them l-values for
2849     // internal consistency, because this subexpression doesn't really
2850     // exist in the high-level semantics.
2851     case Decl::Field:
2852     case Decl::IndirectField:
2853       assert(getLangOpts().CPlusPlus &&
2854              "building reference to field in C?");
2855 
2856       // These can't have reference type in well-formed programs, but
2857       // for internal consistency we do this anyway.
2858       type = type.getNonReferenceType();
2859       valueKind = VK_LValue;
2860       break;
2861 
2862     // Non-type template parameters are either l-values or r-values
2863     // depending on the type.
2864     case Decl::NonTypeTemplateParm: {
2865       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2866         type = reftype->getPointeeType();
2867         valueKind = VK_LValue; // even if the parameter is an r-value reference
2868         break;
2869       }
2870 
2871       // For non-references, we need to strip qualifiers just in case
2872       // the template parameter was declared as 'const int' or whatever.
2873       valueKind = VK_RValue;
2874       type = type.getUnqualifiedType();
2875       break;
2876     }
2877 
2878     case Decl::Var:
2879     case Decl::VarTemplateSpecialization:
2880     case Decl::VarTemplatePartialSpecialization:
2881     case Decl::Decomposition:
2882     case Decl::OMPCapturedExpr:
2883       // In C, "extern void blah;" is valid and is an r-value.
2884       if (!getLangOpts().CPlusPlus &&
2885           !type.hasQualifiers() &&
2886           type->isVoidType()) {
2887         valueKind = VK_RValue;
2888         break;
2889       }
2890       LLVM_FALLTHROUGH;
2891 
2892     case Decl::ImplicitParam:
2893     case Decl::ParmVar: {
2894       // These are always l-values.
2895       valueKind = VK_LValue;
2896       type = type.getNonReferenceType();
2897 
2898       // FIXME: Does the addition of const really only apply in
2899       // potentially-evaluated contexts? Since the variable isn't actually
2900       // captured in an unevaluated context, it seems that the answer is no.
2901       if (!isUnevaluatedContext()) {
2902         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2903         if (!CapturedType.isNull())
2904           type = CapturedType;
2905       }
2906 
2907       break;
2908     }
2909 
2910     case Decl::Binding: {
2911       // These are always lvalues.
2912       valueKind = VK_LValue;
2913       type = type.getNonReferenceType();
2914       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2915       // decides how that's supposed to work.
2916       auto *BD = cast<BindingDecl>(VD);
2917       if (BD->getDeclContext()->isFunctionOrMethod() &&
2918           BD->getDeclContext() != CurContext)
2919         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2920       break;
2921     }
2922 
2923     case Decl::Function: {
2924       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2925         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2926           type = Context.BuiltinFnTy;
2927           valueKind = VK_RValue;
2928           break;
2929         }
2930       }
2931 
2932       const FunctionType *fty = type->castAs<FunctionType>();
2933 
2934       // If we're referring to a function with an __unknown_anytype
2935       // result type, make the entire expression __unknown_anytype.
2936       if (fty->getReturnType() == Context.UnknownAnyTy) {
2937         type = Context.UnknownAnyTy;
2938         valueKind = VK_RValue;
2939         break;
2940       }
2941 
2942       // Functions are l-values in C++.
2943       if (getLangOpts().CPlusPlus) {
2944         valueKind = VK_LValue;
2945         break;
2946       }
2947 
2948       // C99 DR 316 says that, if a function type comes from a
2949       // function definition (without a prototype), that type is only
2950       // used for checking compatibility. Therefore, when referencing
2951       // the function, we pretend that we don't have the full function
2952       // type.
2953       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2954           isa<FunctionProtoType>(fty))
2955         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2956                                               fty->getExtInfo());
2957 
2958       // Functions are r-values in C.
2959       valueKind = VK_RValue;
2960       break;
2961     }
2962 
2963     case Decl::CXXDeductionGuide:
2964       llvm_unreachable("building reference to deduction guide");
2965 
2966     case Decl::MSProperty:
2967       valueKind = VK_LValue;
2968       break;
2969 
2970     case Decl::CXXMethod:
2971       // If we're referring to a method with an __unknown_anytype
2972       // result type, make the entire expression __unknown_anytype.
2973       // This should only be possible with a type written directly.
2974       if (const FunctionProtoType *proto
2975             = dyn_cast<FunctionProtoType>(VD->getType()))
2976         if (proto->getReturnType() == Context.UnknownAnyTy) {
2977           type = Context.UnknownAnyTy;
2978           valueKind = VK_RValue;
2979           break;
2980         }
2981 
2982       // C++ methods are l-values if static, r-values if non-static.
2983       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2984         valueKind = VK_LValue;
2985         break;
2986       }
2987       LLVM_FALLTHROUGH;
2988 
2989     case Decl::CXXConversion:
2990     case Decl::CXXDestructor:
2991     case Decl::CXXConstructor:
2992       valueKind = VK_RValue;
2993       break;
2994     }
2995 
2996     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2997                             TemplateArgs);
2998   }
2999 }
3000 
3001 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3002                                     SmallString<32> &Target) {
3003   Target.resize(CharByteWidth * (Source.size() + 1));
3004   char *ResultPtr = &Target[0];
3005   const llvm::UTF8 *ErrorPtr;
3006   bool success =
3007       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3008   (void)success;
3009   assert(success);
3010   Target.resize(ResultPtr - &Target[0]);
3011 }
3012 
3013 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3014                                      PredefinedExpr::IdentType IT) {
3015   // Pick the current block, lambda, captured statement or function.
3016   Decl *currentDecl = nullptr;
3017   if (const BlockScopeInfo *BSI = getCurBlock())
3018     currentDecl = BSI->TheDecl;
3019   else if (const LambdaScopeInfo *LSI = getCurLambda())
3020     currentDecl = LSI->CallOperator;
3021   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3022     currentDecl = CSI->TheCapturedDecl;
3023   else
3024     currentDecl = getCurFunctionOrMethodDecl();
3025 
3026   if (!currentDecl) {
3027     Diag(Loc, diag::ext_predef_outside_function);
3028     currentDecl = Context.getTranslationUnitDecl();
3029   }
3030 
3031   QualType ResTy;
3032   StringLiteral *SL = nullptr;
3033   if (cast<DeclContext>(currentDecl)->isDependentContext())
3034     ResTy = Context.DependentTy;
3035   else {
3036     // Pre-defined identifiers are of type char[x], where x is the length of
3037     // the string.
3038     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3039     unsigned Length = Str.length();
3040 
3041     llvm::APInt LengthI(32, Length + 1);
3042     if (IT == PredefinedExpr::LFunction) {
3043       ResTy = Context.WideCharTy.withConst();
3044       SmallString<32> RawChars;
3045       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3046                               Str, RawChars);
3047       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3048                                            /*IndexTypeQuals*/ 0);
3049       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3050                                  /*Pascal*/ false, ResTy, Loc);
3051     } else {
3052       ResTy = Context.CharTy.withConst();
3053       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3054                                            /*IndexTypeQuals*/ 0);
3055       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3056                                  /*Pascal*/ false, ResTy, Loc);
3057     }
3058   }
3059 
3060   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3061 }
3062 
3063 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3064   PredefinedExpr::IdentType IT;
3065 
3066   switch (Kind) {
3067   default: llvm_unreachable("Unknown simple primary expr!");
3068   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3069   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3070   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3071   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3072   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3073   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3074   }
3075 
3076   return BuildPredefinedExpr(Loc, IT);
3077 }
3078 
3079 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3080   SmallString<16> CharBuffer;
3081   bool Invalid = false;
3082   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3083   if (Invalid)
3084     return ExprError();
3085 
3086   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3087                             PP, Tok.getKind());
3088   if (Literal.hadError())
3089     return ExprError();
3090 
3091   QualType Ty;
3092   if (Literal.isWide())
3093     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3094   else if (Literal.isUTF16())
3095     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3096   else if (Literal.isUTF32())
3097     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3098   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3099     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3100   else
3101     Ty = Context.CharTy;  // 'x' -> char in C++
3102 
3103   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3104   if (Literal.isWide())
3105     Kind = CharacterLiteral::Wide;
3106   else if (Literal.isUTF16())
3107     Kind = CharacterLiteral::UTF16;
3108   else if (Literal.isUTF32())
3109     Kind = CharacterLiteral::UTF32;
3110   else if (Literal.isUTF8())
3111     Kind = CharacterLiteral::UTF8;
3112 
3113   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3114                                              Tok.getLocation());
3115 
3116   if (Literal.getUDSuffix().empty())
3117     return Lit;
3118 
3119   // We're building a user-defined literal.
3120   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3121   SourceLocation UDSuffixLoc =
3122     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3123 
3124   // Make sure we're allowed user-defined literals here.
3125   if (!UDLScope)
3126     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3127 
3128   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3129   //   operator "" X (ch)
3130   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3131                                         Lit, Tok.getLocation());
3132 }
3133 
3134 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3135   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3136   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3137                                 Context.IntTy, Loc);
3138 }
3139 
3140 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3141                                   QualType Ty, SourceLocation Loc) {
3142   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3143 
3144   using llvm::APFloat;
3145   APFloat Val(Format);
3146 
3147   APFloat::opStatus result = Literal.GetFloatValue(Val);
3148 
3149   // Overflow is always an error, but underflow is only an error if
3150   // we underflowed to zero (APFloat reports denormals as underflow).
3151   if ((result & APFloat::opOverflow) ||
3152       ((result & APFloat::opUnderflow) && Val.isZero())) {
3153     unsigned diagnostic;
3154     SmallString<20> buffer;
3155     if (result & APFloat::opOverflow) {
3156       diagnostic = diag::warn_float_overflow;
3157       APFloat::getLargest(Format).toString(buffer);
3158     } else {
3159       diagnostic = diag::warn_float_underflow;
3160       APFloat::getSmallest(Format).toString(buffer);
3161     }
3162 
3163     S.Diag(Loc, diagnostic)
3164       << Ty
3165       << StringRef(buffer.data(), buffer.size());
3166   }
3167 
3168   bool isExact = (result == APFloat::opOK);
3169   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3170 }
3171 
3172 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3173   assert(E && "Invalid expression");
3174 
3175   if (E->isValueDependent())
3176     return false;
3177 
3178   QualType QT = E->getType();
3179   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3180     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3181     return true;
3182   }
3183 
3184   llvm::APSInt ValueAPS;
3185   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3186 
3187   if (R.isInvalid())
3188     return true;
3189 
3190   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3191   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3192     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3193         << ValueAPS.toString(10) << ValueIsPositive;
3194     return true;
3195   }
3196 
3197   return false;
3198 }
3199 
3200 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3201   // Fast path for a single digit (which is quite common).  A single digit
3202   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3203   if (Tok.getLength() == 1) {
3204     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3205     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3206   }
3207 
3208   SmallString<128> SpellingBuffer;
3209   // NumericLiteralParser wants to overread by one character.  Add padding to
3210   // the buffer in case the token is copied to the buffer.  If getSpelling()
3211   // returns a StringRef to the memory buffer, it should have a null char at
3212   // the EOF, so it is also safe.
3213   SpellingBuffer.resize(Tok.getLength() + 1);
3214 
3215   // Get the spelling of the token, which eliminates trigraphs, etc.
3216   bool Invalid = false;
3217   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3218   if (Invalid)
3219     return ExprError();
3220 
3221   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3222   if (Literal.hadError)
3223     return ExprError();
3224 
3225   if (Literal.hasUDSuffix()) {
3226     // We're building a user-defined literal.
3227     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3228     SourceLocation UDSuffixLoc =
3229       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3230 
3231     // Make sure we're allowed user-defined literals here.
3232     if (!UDLScope)
3233       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3234 
3235     QualType CookedTy;
3236     if (Literal.isFloatingLiteral()) {
3237       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3238       // long double, the literal is treated as a call of the form
3239       //   operator "" X (f L)
3240       CookedTy = Context.LongDoubleTy;
3241     } else {
3242       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3243       // unsigned long long, the literal is treated as a call of the form
3244       //   operator "" X (n ULL)
3245       CookedTy = Context.UnsignedLongLongTy;
3246     }
3247 
3248     DeclarationName OpName =
3249       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3250     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3251     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3252 
3253     SourceLocation TokLoc = Tok.getLocation();
3254 
3255     // Perform literal operator lookup to determine if we're building a raw
3256     // literal or a cooked one.
3257     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3258     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3259                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3260                                   /*AllowStringTemplate*/ false,
3261                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3262     case LOLR_ErrorNoDiagnostic:
3263       // Lookup failure for imaginary constants isn't fatal, there's still the
3264       // GNU extension producing _Complex types.
3265       break;
3266     case LOLR_Error:
3267       return ExprError();
3268     case LOLR_Cooked: {
3269       Expr *Lit;
3270       if (Literal.isFloatingLiteral()) {
3271         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3272       } else {
3273         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3274         if (Literal.GetIntegerValue(ResultVal))
3275           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3276               << /* Unsigned */ 1;
3277         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3278                                      Tok.getLocation());
3279       }
3280       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3281     }
3282 
3283     case LOLR_Raw: {
3284       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3285       // literal is treated as a call of the form
3286       //   operator "" X ("n")
3287       unsigned Length = Literal.getUDSuffixOffset();
3288       QualType StrTy = Context.getConstantArrayType(
3289           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3290           ArrayType::Normal, 0);
3291       Expr *Lit = StringLiteral::Create(
3292           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3293           /*Pascal*/false, StrTy, &TokLoc, 1);
3294       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3295     }
3296 
3297     case LOLR_Template: {
3298       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3299       // template), L is treated as a call fo the form
3300       //   operator "" X <'c1', 'c2', ... 'ck'>()
3301       // where n is the source character sequence c1 c2 ... ck.
3302       TemplateArgumentListInfo ExplicitArgs;
3303       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3304       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3305       llvm::APSInt Value(CharBits, CharIsUnsigned);
3306       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3307         Value = TokSpelling[I];
3308         TemplateArgument Arg(Context, Value, Context.CharTy);
3309         TemplateArgumentLocInfo ArgInfo;
3310         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3311       }
3312       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3313                                       &ExplicitArgs);
3314     }
3315     case LOLR_StringTemplate:
3316       llvm_unreachable("unexpected literal operator lookup result");
3317     }
3318   }
3319 
3320   Expr *Res;
3321 
3322   if (Literal.isFloatingLiteral()) {
3323     QualType Ty;
3324     if (Literal.isHalf){
3325       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3326         Ty = Context.HalfTy;
3327       else {
3328         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3329         return ExprError();
3330       }
3331     } else if (Literal.isFloat)
3332       Ty = Context.FloatTy;
3333     else if (Literal.isLong)
3334       Ty = Context.LongDoubleTy;
3335     else if (Literal.isFloat16)
3336       Ty = Context.Float16Ty;
3337     else if (Literal.isFloat128)
3338       Ty = Context.Float128Ty;
3339     else
3340       Ty = Context.DoubleTy;
3341 
3342     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3343 
3344     if (Ty == Context.DoubleTy) {
3345       if (getLangOpts().SinglePrecisionConstants) {
3346         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3347         if (BTy->getKind() != BuiltinType::Float) {
3348           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3349         }
3350       } else if (getLangOpts().OpenCL &&
3351                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3352         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3353         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3354         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3355       }
3356     }
3357   } else if (!Literal.isIntegerLiteral()) {
3358     return ExprError();
3359   } else {
3360     QualType Ty;
3361 
3362     // 'long long' is a C99 or C++11 feature.
3363     if (!getLangOpts().C99 && Literal.isLongLong) {
3364       if (getLangOpts().CPlusPlus)
3365         Diag(Tok.getLocation(),
3366              getLangOpts().CPlusPlus11 ?
3367              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3368       else
3369         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3370     }
3371 
3372     // Get the value in the widest-possible width.
3373     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3374     llvm::APInt ResultVal(MaxWidth, 0);
3375 
3376     if (Literal.GetIntegerValue(ResultVal)) {
3377       // If this value didn't fit into uintmax_t, error and force to ull.
3378       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3379           << /* Unsigned */ 1;
3380       Ty = Context.UnsignedLongLongTy;
3381       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3382              "long long is not intmax_t?");
3383     } else {
3384       // If this value fits into a ULL, try to figure out what else it fits into
3385       // according to the rules of C99 6.4.4.1p5.
3386 
3387       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3388       // be an unsigned int.
3389       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3390 
3391       // Check from smallest to largest, picking the smallest type we can.
3392       unsigned Width = 0;
3393 
3394       // Microsoft specific integer suffixes are explicitly sized.
3395       if (Literal.MicrosoftInteger) {
3396         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3397           Width = 8;
3398           Ty = Context.CharTy;
3399         } else {
3400           Width = Literal.MicrosoftInteger;
3401           Ty = Context.getIntTypeForBitwidth(Width,
3402                                              /*Signed=*/!Literal.isUnsigned);
3403         }
3404       }
3405 
3406       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3407         // Are int/unsigned possibilities?
3408         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3409 
3410         // Does it fit in a unsigned int?
3411         if (ResultVal.isIntN(IntSize)) {
3412           // Does it fit in a signed int?
3413           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3414             Ty = Context.IntTy;
3415           else if (AllowUnsigned)
3416             Ty = Context.UnsignedIntTy;
3417           Width = IntSize;
3418         }
3419       }
3420 
3421       // Are long/unsigned long possibilities?
3422       if (Ty.isNull() && !Literal.isLongLong) {
3423         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3424 
3425         // Does it fit in a unsigned long?
3426         if (ResultVal.isIntN(LongSize)) {
3427           // Does it fit in a signed long?
3428           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3429             Ty = Context.LongTy;
3430           else if (AllowUnsigned)
3431             Ty = Context.UnsignedLongTy;
3432           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3433           // is compatible.
3434           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3435             const unsigned LongLongSize =
3436                 Context.getTargetInfo().getLongLongWidth();
3437             Diag(Tok.getLocation(),
3438                  getLangOpts().CPlusPlus
3439                      ? Literal.isLong
3440                            ? diag::warn_old_implicitly_unsigned_long_cxx
3441                            : /*C++98 UB*/ diag::
3442                                  ext_old_implicitly_unsigned_long_cxx
3443                      : diag::warn_old_implicitly_unsigned_long)
3444                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3445                                             : /*will be ill-formed*/ 1);
3446             Ty = Context.UnsignedLongTy;
3447           }
3448           Width = LongSize;
3449         }
3450       }
3451 
3452       // Check long long if needed.
3453       if (Ty.isNull()) {
3454         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3455 
3456         // Does it fit in a unsigned long long?
3457         if (ResultVal.isIntN(LongLongSize)) {
3458           // Does it fit in a signed long long?
3459           // To be compatible with MSVC, hex integer literals ending with the
3460           // LL or i64 suffix are always signed in Microsoft mode.
3461           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3462               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3463             Ty = Context.LongLongTy;
3464           else if (AllowUnsigned)
3465             Ty = Context.UnsignedLongLongTy;
3466           Width = LongLongSize;
3467         }
3468       }
3469 
3470       // If we still couldn't decide a type, we probably have something that
3471       // does not fit in a signed long long, but has no U suffix.
3472       if (Ty.isNull()) {
3473         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3474         Ty = Context.UnsignedLongLongTy;
3475         Width = Context.getTargetInfo().getLongLongWidth();
3476       }
3477 
3478       if (ResultVal.getBitWidth() != Width)
3479         ResultVal = ResultVal.trunc(Width);
3480     }
3481     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3482   }
3483 
3484   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3485   if (Literal.isImaginary) {
3486     Res = new (Context) ImaginaryLiteral(Res,
3487                                         Context.getComplexType(Res->getType()));
3488 
3489     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3490   }
3491   return Res;
3492 }
3493 
3494 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3495   assert(E && "ActOnParenExpr() missing expr");
3496   return new (Context) ParenExpr(L, R, E);
3497 }
3498 
3499 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3500                                          SourceLocation Loc,
3501                                          SourceRange ArgRange) {
3502   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3503   // scalar or vector data type argument..."
3504   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3505   // type (C99 6.2.5p18) or void.
3506   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3507     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3508       << T << ArgRange;
3509     return true;
3510   }
3511 
3512   assert((T->isVoidType() || !T->isIncompleteType()) &&
3513          "Scalar types should always be complete");
3514   return false;
3515 }
3516 
3517 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3518                                            SourceLocation Loc,
3519                                            SourceRange ArgRange,
3520                                            UnaryExprOrTypeTrait TraitKind) {
3521   // Invalid types must be hard errors for SFINAE in C++.
3522   if (S.LangOpts.CPlusPlus)
3523     return true;
3524 
3525   // C99 6.5.3.4p1:
3526   if (T->isFunctionType() &&
3527       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3528     // sizeof(function)/alignof(function) is allowed as an extension.
3529     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3530       << TraitKind << ArgRange;
3531     return false;
3532   }
3533 
3534   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3535   // this is an error (OpenCL v1.1 s6.3.k)
3536   if (T->isVoidType()) {
3537     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3538                                         : diag::ext_sizeof_alignof_void_type;
3539     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3540     return false;
3541   }
3542 
3543   return true;
3544 }
3545 
3546 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3547                                              SourceLocation Loc,
3548                                              SourceRange ArgRange,
3549                                              UnaryExprOrTypeTrait TraitKind) {
3550   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3551   // runtime doesn't allow it.
3552   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3553     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3554       << T << (TraitKind == UETT_SizeOf)
3555       << ArgRange;
3556     return true;
3557   }
3558 
3559   return false;
3560 }
3561 
3562 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3563 /// pointer type is equal to T) and emit a warning if it is.
3564 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3565                                      Expr *E) {
3566   // Don't warn if the operation changed the type.
3567   if (T != E->getType())
3568     return;
3569 
3570   // Now look for array decays.
3571   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3572   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3573     return;
3574 
3575   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3576                                              << ICE->getType()
3577                                              << ICE->getSubExpr()->getType();
3578 }
3579 
3580 /// \brief Check the constraints on expression operands to unary type expression
3581 /// and type traits.
3582 ///
3583 /// Completes any types necessary and validates the constraints on the operand
3584 /// expression. The logic mostly mirrors the type-based overload, but may modify
3585 /// the expression as it completes the type for that expression through template
3586 /// instantiation, etc.
3587 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3588                                             UnaryExprOrTypeTrait ExprKind) {
3589   QualType ExprTy = E->getType();
3590   assert(!ExprTy->isReferenceType());
3591 
3592   if (ExprKind == UETT_VecStep)
3593     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3594                                         E->getSourceRange());
3595 
3596   // Whitelist some types as extensions
3597   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3598                                       E->getSourceRange(), ExprKind))
3599     return false;
3600 
3601   // 'alignof' applied to an expression only requires the base element type of
3602   // the expression to be complete. 'sizeof' requires the expression's type to
3603   // be complete (and will attempt to complete it if it's an array of unknown
3604   // bound).
3605   if (ExprKind == UETT_AlignOf) {
3606     if (RequireCompleteType(E->getExprLoc(),
3607                             Context.getBaseElementType(E->getType()),
3608                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3609                             E->getSourceRange()))
3610       return true;
3611   } else {
3612     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3613                                 ExprKind, E->getSourceRange()))
3614       return true;
3615   }
3616 
3617   // Completing the expression's type may have changed it.
3618   ExprTy = E->getType();
3619   assert(!ExprTy->isReferenceType());
3620 
3621   if (ExprTy->isFunctionType()) {
3622     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3623       << ExprKind << E->getSourceRange();
3624     return true;
3625   }
3626 
3627   // The operand for sizeof and alignof is in an unevaluated expression context,
3628   // so side effects could result in unintended consequences.
3629   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3630       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3631     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3632 
3633   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3634                                        E->getSourceRange(), ExprKind))
3635     return true;
3636 
3637   if (ExprKind == UETT_SizeOf) {
3638     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3639       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3640         QualType OType = PVD->getOriginalType();
3641         QualType Type = PVD->getType();
3642         if (Type->isPointerType() && OType->isArrayType()) {
3643           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3644             << Type << OType;
3645           Diag(PVD->getLocation(), diag::note_declared_at);
3646         }
3647       }
3648     }
3649 
3650     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3651     // decays into a pointer and returns an unintended result. This is most
3652     // likely a typo for "sizeof(array) op x".
3653     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3654       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3655                                BO->getLHS());
3656       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3657                                BO->getRHS());
3658     }
3659   }
3660 
3661   return false;
3662 }
3663 
3664 /// \brief Check the constraints on operands to unary expression and type
3665 /// traits.
3666 ///
3667 /// This will complete any types necessary, and validate the various constraints
3668 /// on those operands.
3669 ///
3670 /// The UsualUnaryConversions() function is *not* called by this routine.
3671 /// C99 6.3.2.1p[2-4] all state:
3672 ///   Except when it is the operand of the sizeof operator ...
3673 ///
3674 /// C++ [expr.sizeof]p4
3675 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3676 ///   standard conversions are not applied to the operand of sizeof.
3677 ///
3678 /// This policy is followed for all of the unary trait expressions.
3679 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3680                                             SourceLocation OpLoc,
3681                                             SourceRange ExprRange,
3682                                             UnaryExprOrTypeTrait ExprKind) {
3683   if (ExprType->isDependentType())
3684     return false;
3685 
3686   // C++ [expr.sizeof]p2:
3687   //     When applied to a reference or a reference type, the result
3688   //     is the size of the referenced type.
3689   // C++11 [expr.alignof]p3:
3690   //     When alignof is applied to a reference type, the result
3691   //     shall be the alignment of the referenced type.
3692   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3693     ExprType = Ref->getPointeeType();
3694 
3695   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3696   //   When alignof or _Alignof is applied to an array type, the result
3697   //   is the alignment of the element type.
3698   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3699     ExprType = Context.getBaseElementType(ExprType);
3700 
3701   if (ExprKind == UETT_VecStep)
3702     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3703 
3704   // Whitelist some types as extensions
3705   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3706                                       ExprKind))
3707     return false;
3708 
3709   if (RequireCompleteType(OpLoc, ExprType,
3710                           diag::err_sizeof_alignof_incomplete_type,
3711                           ExprKind, ExprRange))
3712     return true;
3713 
3714   if (ExprType->isFunctionType()) {
3715     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3716       << ExprKind << ExprRange;
3717     return true;
3718   }
3719 
3720   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3721                                        ExprKind))
3722     return true;
3723 
3724   return false;
3725 }
3726 
3727 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3728   E = E->IgnoreParens();
3729 
3730   // Cannot know anything else if the expression is dependent.
3731   if (E->isTypeDependent())
3732     return false;
3733 
3734   if (E->getObjectKind() == OK_BitField) {
3735     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3736        << 1 << E->getSourceRange();
3737     return true;
3738   }
3739 
3740   ValueDecl *D = nullptr;
3741   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3742     D = DRE->getDecl();
3743   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3744     D = ME->getMemberDecl();
3745   }
3746 
3747   // If it's a field, require the containing struct to have a
3748   // complete definition so that we can compute the layout.
3749   //
3750   // This can happen in C++11 onwards, either by naming the member
3751   // in a way that is not transformed into a member access expression
3752   // (in an unevaluated operand, for instance), or by naming the member
3753   // in a trailing-return-type.
3754   //
3755   // For the record, since __alignof__ on expressions is a GCC
3756   // extension, GCC seems to permit this but always gives the
3757   // nonsensical answer 0.
3758   //
3759   // We don't really need the layout here --- we could instead just
3760   // directly check for all the appropriate alignment-lowing
3761   // attributes --- but that would require duplicating a lot of
3762   // logic that just isn't worth duplicating for such a marginal
3763   // use-case.
3764   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3765     // Fast path this check, since we at least know the record has a
3766     // definition if we can find a member of it.
3767     if (!FD->getParent()->isCompleteDefinition()) {
3768       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3769         << E->getSourceRange();
3770       return true;
3771     }
3772 
3773     // Otherwise, if it's a field, and the field doesn't have
3774     // reference type, then it must have a complete type (or be a
3775     // flexible array member, which we explicitly want to
3776     // white-list anyway), which makes the following checks trivial.
3777     if (!FD->getType()->isReferenceType())
3778       return false;
3779   }
3780 
3781   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3782 }
3783 
3784 bool Sema::CheckVecStepExpr(Expr *E) {
3785   E = E->IgnoreParens();
3786 
3787   // Cannot know anything else if the expression is dependent.
3788   if (E->isTypeDependent())
3789     return false;
3790 
3791   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3792 }
3793 
3794 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3795                                         CapturingScopeInfo *CSI) {
3796   assert(T->isVariablyModifiedType());
3797   assert(CSI != nullptr);
3798 
3799   // We're going to walk down into the type and look for VLA expressions.
3800   do {
3801     const Type *Ty = T.getTypePtr();
3802     switch (Ty->getTypeClass()) {
3803 #define TYPE(Class, Base)
3804 #define ABSTRACT_TYPE(Class, Base)
3805 #define NON_CANONICAL_TYPE(Class, Base)
3806 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3807 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3808 #include "clang/AST/TypeNodes.def"
3809       T = QualType();
3810       break;
3811     // These types are never variably-modified.
3812     case Type::Builtin:
3813     case Type::Complex:
3814     case Type::Vector:
3815     case Type::ExtVector:
3816     case Type::Record:
3817     case Type::Enum:
3818     case Type::Elaborated:
3819     case Type::TemplateSpecialization:
3820     case Type::ObjCObject:
3821     case Type::ObjCInterface:
3822     case Type::ObjCObjectPointer:
3823     case Type::ObjCTypeParam:
3824     case Type::Pipe:
3825       llvm_unreachable("type class is never variably-modified!");
3826     case Type::Adjusted:
3827       T = cast<AdjustedType>(Ty)->getOriginalType();
3828       break;
3829     case Type::Decayed:
3830       T = cast<DecayedType>(Ty)->getPointeeType();
3831       break;
3832     case Type::Pointer:
3833       T = cast<PointerType>(Ty)->getPointeeType();
3834       break;
3835     case Type::BlockPointer:
3836       T = cast<BlockPointerType>(Ty)->getPointeeType();
3837       break;
3838     case Type::LValueReference:
3839     case Type::RValueReference:
3840       T = cast<ReferenceType>(Ty)->getPointeeType();
3841       break;
3842     case Type::MemberPointer:
3843       T = cast<MemberPointerType>(Ty)->getPointeeType();
3844       break;
3845     case Type::ConstantArray:
3846     case Type::IncompleteArray:
3847       // Losing element qualification here is fine.
3848       T = cast<ArrayType>(Ty)->getElementType();
3849       break;
3850     case Type::VariableArray: {
3851       // Losing element qualification here is fine.
3852       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3853 
3854       // Unknown size indication requires no size computation.
3855       // Otherwise, evaluate and record it.
3856       if (auto Size = VAT->getSizeExpr()) {
3857         if (!CSI->isVLATypeCaptured(VAT)) {
3858           RecordDecl *CapRecord = nullptr;
3859           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3860             CapRecord = LSI->Lambda;
3861           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3862             CapRecord = CRSI->TheRecordDecl;
3863           }
3864           if (CapRecord) {
3865             auto ExprLoc = Size->getExprLoc();
3866             auto SizeType = Context.getSizeType();
3867             // Build the non-static data member.
3868             auto Field =
3869                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3870                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3871                                   /*BW*/ nullptr, /*Mutable*/ false,
3872                                   /*InitStyle*/ ICIS_NoInit);
3873             Field->setImplicit(true);
3874             Field->setAccess(AS_private);
3875             Field->setCapturedVLAType(VAT);
3876             CapRecord->addDecl(Field);
3877 
3878             CSI->addVLATypeCapture(ExprLoc, SizeType);
3879           }
3880         }
3881       }
3882       T = VAT->getElementType();
3883       break;
3884     }
3885     case Type::FunctionProto:
3886     case Type::FunctionNoProto:
3887       T = cast<FunctionType>(Ty)->getReturnType();
3888       break;
3889     case Type::Paren:
3890     case Type::TypeOf:
3891     case Type::UnaryTransform:
3892     case Type::Attributed:
3893     case Type::SubstTemplateTypeParm:
3894     case Type::PackExpansion:
3895       // Keep walking after single level desugaring.
3896       T = T.getSingleStepDesugaredType(Context);
3897       break;
3898     case Type::Typedef:
3899       T = cast<TypedefType>(Ty)->desugar();
3900       break;
3901     case Type::Decltype:
3902       T = cast<DecltypeType>(Ty)->desugar();
3903       break;
3904     case Type::Auto:
3905     case Type::DeducedTemplateSpecialization:
3906       T = cast<DeducedType>(Ty)->getDeducedType();
3907       break;
3908     case Type::TypeOfExpr:
3909       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3910       break;
3911     case Type::Atomic:
3912       T = cast<AtomicType>(Ty)->getValueType();
3913       break;
3914     }
3915   } while (!T.isNull() && T->isVariablyModifiedType());
3916 }
3917 
3918 /// \brief Build a sizeof or alignof expression given a type operand.
3919 ExprResult
3920 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3921                                      SourceLocation OpLoc,
3922                                      UnaryExprOrTypeTrait ExprKind,
3923                                      SourceRange R) {
3924   if (!TInfo)
3925     return ExprError();
3926 
3927   QualType T = TInfo->getType();
3928 
3929   if (!T->isDependentType() &&
3930       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3931     return ExprError();
3932 
3933   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3934     if (auto *TT = T->getAs<TypedefType>()) {
3935       for (auto I = FunctionScopes.rbegin(),
3936                 E = std::prev(FunctionScopes.rend());
3937            I != E; ++I) {
3938         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3939         if (CSI == nullptr)
3940           break;
3941         DeclContext *DC = nullptr;
3942         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3943           DC = LSI->CallOperator;
3944         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3945           DC = CRSI->TheCapturedDecl;
3946         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3947           DC = BSI->TheDecl;
3948         if (DC) {
3949           if (DC->containsDecl(TT->getDecl()))
3950             break;
3951           captureVariablyModifiedType(Context, T, CSI);
3952         }
3953       }
3954     }
3955   }
3956 
3957   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3958   return new (Context) UnaryExprOrTypeTraitExpr(
3959       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3960 }
3961 
3962 /// \brief Build a sizeof or alignof expression given an expression
3963 /// operand.
3964 ExprResult
3965 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3966                                      UnaryExprOrTypeTrait ExprKind) {
3967   ExprResult PE = CheckPlaceholderExpr(E);
3968   if (PE.isInvalid())
3969     return ExprError();
3970 
3971   E = PE.get();
3972 
3973   // Verify that the operand is valid.
3974   bool isInvalid = false;
3975   if (E->isTypeDependent()) {
3976     // Delay type-checking for type-dependent expressions.
3977   } else if (ExprKind == UETT_AlignOf) {
3978     isInvalid = CheckAlignOfExpr(*this, E);
3979   } else if (ExprKind == UETT_VecStep) {
3980     isInvalid = CheckVecStepExpr(E);
3981   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3982       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3983       isInvalid = true;
3984   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3985     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3986     isInvalid = true;
3987   } else {
3988     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3989   }
3990 
3991   if (isInvalid)
3992     return ExprError();
3993 
3994   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3995     PE = TransformToPotentiallyEvaluated(E);
3996     if (PE.isInvalid()) return ExprError();
3997     E = PE.get();
3998   }
3999 
4000   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4001   return new (Context) UnaryExprOrTypeTraitExpr(
4002       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4003 }
4004 
4005 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4006 /// expr and the same for @c alignof and @c __alignof
4007 /// Note that the ArgRange is invalid if isType is false.
4008 ExprResult
4009 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4010                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4011                                     void *TyOrEx, SourceRange ArgRange) {
4012   // If error parsing type, ignore.
4013   if (!TyOrEx) return ExprError();
4014 
4015   if (IsType) {
4016     TypeSourceInfo *TInfo;
4017     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4018     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4019   }
4020 
4021   Expr *ArgEx = (Expr *)TyOrEx;
4022   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4023   return Result;
4024 }
4025 
4026 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4027                                      bool IsReal) {
4028   if (V.get()->isTypeDependent())
4029     return S.Context.DependentTy;
4030 
4031   // _Real and _Imag are only l-values for normal l-values.
4032   if (V.get()->getObjectKind() != OK_Ordinary) {
4033     V = S.DefaultLvalueConversion(V.get());
4034     if (V.isInvalid())
4035       return QualType();
4036   }
4037 
4038   // These operators return the element type of a complex type.
4039   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4040     return CT->getElementType();
4041 
4042   // Otherwise they pass through real integer and floating point types here.
4043   if (V.get()->getType()->isArithmeticType())
4044     return V.get()->getType();
4045 
4046   // Test for placeholders.
4047   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4048   if (PR.isInvalid()) return QualType();
4049   if (PR.get() != V.get()) {
4050     V = PR;
4051     return CheckRealImagOperand(S, V, Loc, IsReal);
4052   }
4053 
4054   // Reject anything else.
4055   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4056     << (IsReal ? "__real" : "__imag");
4057   return QualType();
4058 }
4059 
4060 
4061 
4062 ExprResult
4063 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4064                           tok::TokenKind Kind, Expr *Input) {
4065   UnaryOperatorKind Opc;
4066   switch (Kind) {
4067   default: llvm_unreachable("Unknown unary op!");
4068   case tok::plusplus:   Opc = UO_PostInc; break;
4069   case tok::minusminus: Opc = UO_PostDec; break;
4070   }
4071 
4072   // Since this might is a postfix expression, get rid of ParenListExprs.
4073   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4074   if (Result.isInvalid()) return ExprError();
4075   Input = Result.get();
4076 
4077   return BuildUnaryOp(S, OpLoc, Opc, Input);
4078 }
4079 
4080 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4081 ///
4082 /// \return true on error
4083 static bool checkArithmeticOnObjCPointer(Sema &S,
4084                                          SourceLocation opLoc,
4085                                          Expr *op) {
4086   assert(op->getType()->isObjCObjectPointerType());
4087   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4088       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4089     return false;
4090 
4091   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4092     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4093     << op->getSourceRange();
4094   return true;
4095 }
4096 
4097 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4098   auto *BaseNoParens = Base->IgnoreParens();
4099   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4100     return MSProp->getPropertyDecl()->getType()->isArrayType();
4101   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4102 }
4103 
4104 ExprResult
4105 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4106                               Expr *idx, SourceLocation rbLoc) {
4107   if (base && !base->getType().isNull() &&
4108       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4109     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4110                                     /*Length=*/nullptr, rbLoc);
4111 
4112   // Since this might be a postfix expression, get rid of ParenListExprs.
4113   if (isa<ParenListExpr>(base)) {
4114     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4115     if (result.isInvalid()) return ExprError();
4116     base = result.get();
4117   }
4118 
4119   // Handle any non-overload placeholder types in the base and index
4120   // expressions.  We can't handle overloads here because the other
4121   // operand might be an overloadable type, in which case the overload
4122   // resolution for the operator overload should get the first crack
4123   // at the overload.
4124   bool IsMSPropertySubscript = false;
4125   if (base->getType()->isNonOverloadPlaceholderType()) {
4126     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4127     if (!IsMSPropertySubscript) {
4128       ExprResult result = CheckPlaceholderExpr(base);
4129       if (result.isInvalid())
4130         return ExprError();
4131       base = result.get();
4132     }
4133   }
4134   if (idx->getType()->isNonOverloadPlaceholderType()) {
4135     ExprResult result = CheckPlaceholderExpr(idx);
4136     if (result.isInvalid()) return ExprError();
4137     idx = result.get();
4138   }
4139 
4140   // Build an unanalyzed expression if either operand is type-dependent.
4141   if (getLangOpts().CPlusPlus &&
4142       (base->isTypeDependent() || idx->isTypeDependent())) {
4143     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4144                                             VK_LValue, OK_Ordinary, rbLoc);
4145   }
4146 
4147   // MSDN, property (C++)
4148   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4149   // This attribute can also be used in the declaration of an empty array in a
4150   // class or structure definition. For example:
4151   // __declspec(property(get=GetX, put=PutX)) int x[];
4152   // The above statement indicates that x[] can be used with one or more array
4153   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4154   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4155   if (IsMSPropertySubscript) {
4156     // Build MS property subscript expression if base is MS property reference
4157     // or MS property subscript.
4158     return new (Context) MSPropertySubscriptExpr(
4159         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4160   }
4161 
4162   // Use C++ overloaded-operator rules if either operand has record
4163   // type.  The spec says to do this if either type is *overloadable*,
4164   // but enum types can't declare subscript operators or conversion
4165   // operators, so there's nothing interesting for overload resolution
4166   // to do if there aren't any record types involved.
4167   //
4168   // ObjC pointers have their own subscripting logic that is not tied
4169   // to overload resolution and so should not take this path.
4170   if (getLangOpts().CPlusPlus &&
4171       (base->getType()->isRecordType() ||
4172        (!base->getType()->isObjCObjectPointerType() &&
4173         idx->getType()->isRecordType()))) {
4174     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4175   }
4176 
4177   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4178 }
4179 
4180 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4181                                           Expr *LowerBound,
4182                                           SourceLocation ColonLoc, Expr *Length,
4183                                           SourceLocation RBLoc) {
4184   if (Base->getType()->isPlaceholderType() &&
4185       !Base->getType()->isSpecificPlaceholderType(
4186           BuiltinType::OMPArraySection)) {
4187     ExprResult Result = CheckPlaceholderExpr(Base);
4188     if (Result.isInvalid())
4189       return ExprError();
4190     Base = Result.get();
4191   }
4192   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4193     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4194     if (Result.isInvalid())
4195       return ExprError();
4196     Result = DefaultLvalueConversion(Result.get());
4197     if (Result.isInvalid())
4198       return ExprError();
4199     LowerBound = Result.get();
4200   }
4201   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4202     ExprResult Result = CheckPlaceholderExpr(Length);
4203     if (Result.isInvalid())
4204       return ExprError();
4205     Result = DefaultLvalueConversion(Result.get());
4206     if (Result.isInvalid())
4207       return ExprError();
4208     Length = Result.get();
4209   }
4210 
4211   // Build an unanalyzed expression if either operand is type-dependent.
4212   if (Base->isTypeDependent() ||
4213       (LowerBound &&
4214        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4215       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4216     return new (Context)
4217         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4218                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4219   }
4220 
4221   // Perform default conversions.
4222   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4223   QualType ResultTy;
4224   if (OriginalTy->isAnyPointerType()) {
4225     ResultTy = OriginalTy->getPointeeType();
4226   } else if (OriginalTy->isArrayType()) {
4227     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4228   } else {
4229     return ExprError(
4230         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4231         << Base->getSourceRange());
4232   }
4233   // C99 6.5.2.1p1
4234   if (LowerBound) {
4235     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4236                                                       LowerBound);
4237     if (Res.isInvalid())
4238       return ExprError(Diag(LowerBound->getExprLoc(),
4239                             diag::err_omp_typecheck_section_not_integer)
4240                        << 0 << LowerBound->getSourceRange());
4241     LowerBound = Res.get();
4242 
4243     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4244         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4245       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4246           << 0 << LowerBound->getSourceRange();
4247   }
4248   if (Length) {
4249     auto Res =
4250         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4251     if (Res.isInvalid())
4252       return ExprError(Diag(Length->getExprLoc(),
4253                             diag::err_omp_typecheck_section_not_integer)
4254                        << 1 << Length->getSourceRange());
4255     Length = Res.get();
4256 
4257     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4258         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4259       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4260           << 1 << Length->getSourceRange();
4261   }
4262 
4263   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4264   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4265   // type. Note that functions are not objects, and that (in C99 parlance)
4266   // incomplete types are not object types.
4267   if (ResultTy->isFunctionType()) {
4268     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4269         << ResultTy << Base->getSourceRange();
4270     return ExprError();
4271   }
4272 
4273   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4274                           diag::err_omp_section_incomplete_type, Base))
4275     return ExprError();
4276 
4277   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4278     llvm::APSInt LowerBoundValue;
4279     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4280       // OpenMP 4.5, [2.4 Array Sections]
4281       // The array section must be a subset of the original array.
4282       if (LowerBoundValue.isNegative()) {
4283         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4284             << LowerBound->getSourceRange();
4285         return ExprError();
4286       }
4287     }
4288   }
4289 
4290   if (Length) {
4291     llvm::APSInt LengthValue;
4292     if (Length->EvaluateAsInt(LengthValue, Context)) {
4293       // OpenMP 4.5, [2.4 Array Sections]
4294       // The length must evaluate to non-negative integers.
4295       if (LengthValue.isNegative()) {
4296         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4297             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4298             << Length->getSourceRange();
4299         return ExprError();
4300       }
4301     }
4302   } else if (ColonLoc.isValid() &&
4303              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4304                                       !OriginalTy->isVariableArrayType()))) {
4305     // OpenMP 4.5, [2.4 Array Sections]
4306     // When the size of the array dimension is not known, the length must be
4307     // specified explicitly.
4308     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4309         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4310     return ExprError();
4311   }
4312 
4313   if (!Base->getType()->isSpecificPlaceholderType(
4314           BuiltinType::OMPArraySection)) {
4315     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4316     if (Result.isInvalid())
4317       return ExprError();
4318     Base = Result.get();
4319   }
4320   return new (Context)
4321       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4322                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4323 }
4324 
4325 ExprResult
4326 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4327                                       Expr *Idx, SourceLocation RLoc) {
4328   Expr *LHSExp = Base;
4329   Expr *RHSExp = Idx;
4330 
4331   ExprValueKind VK = VK_LValue;
4332   ExprObjectKind OK = OK_Ordinary;
4333 
4334   // Per C++ core issue 1213, the result is an xvalue if either operand is
4335   // a non-lvalue array, and an lvalue otherwise.
4336   if (getLangOpts().CPlusPlus11 &&
4337       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4338        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4339     VK = VK_XValue;
4340 
4341   // Perform default conversions.
4342   if (!LHSExp->getType()->getAs<VectorType>()) {
4343     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4344     if (Result.isInvalid())
4345       return ExprError();
4346     LHSExp = Result.get();
4347   }
4348   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4349   if (Result.isInvalid())
4350     return ExprError();
4351   RHSExp = Result.get();
4352 
4353   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4354 
4355   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4356   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4357   // in the subscript position. As a result, we need to derive the array base
4358   // and index from the expression types.
4359   Expr *BaseExpr, *IndexExpr;
4360   QualType ResultType;
4361   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4362     BaseExpr = LHSExp;
4363     IndexExpr = RHSExp;
4364     ResultType = Context.DependentTy;
4365   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4366     BaseExpr = LHSExp;
4367     IndexExpr = RHSExp;
4368     ResultType = PTy->getPointeeType();
4369   } else if (const ObjCObjectPointerType *PTy =
4370                LHSTy->getAs<ObjCObjectPointerType>()) {
4371     BaseExpr = LHSExp;
4372     IndexExpr = RHSExp;
4373 
4374     // Use custom logic if this should be the pseudo-object subscript
4375     // expression.
4376     if (!LangOpts.isSubscriptPointerArithmetic())
4377       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4378                                           nullptr);
4379 
4380     ResultType = PTy->getPointeeType();
4381   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4382      // Handle the uncommon case of "123[Ptr]".
4383     BaseExpr = RHSExp;
4384     IndexExpr = LHSExp;
4385     ResultType = PTy->getPointeeType();
4386   } else if (const ObjCObjectPointerType *PTy =
4387                RHSTy->getAs<ObjCObjectPointerType>()) {
4388      // Handle the uncommon case of "123[Ptr]".
4389     BaseExpr = RHSExp;
4390     IndexExpr = LHSExp;
4391     ResultType = PTy->getPointeeType();
4392     if (!LangOpts.isSubscriptPointerArithmetic()) {
4393       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4394         << ResultType << BaseExpr->getSourceRange();
4395       return ExprError();
4396     }
4397   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4398     BaseExpr = LHSExp;    // vectors: V[123]
4399     IndexExpr = RHSExp;
4400     VK = LHSExp->getValueKind();
4401     if (VK != VK_RValue)
4402       OK = OK_VectorComponent;
4403 
4404     ResultType = VTy->getElementType();
4405     QualType BaseType = BaseExpr->getType();
4406     Qualifiers BaseQuals = BaseType.getQualifiers();
4407     Qualifiers MemberQuals = ResultType.getQualifiers();
4408     Qualifiers Combined = BaseQuals + MemberQuals;
4409     if (Combined != MemberQuals)
4410       ResultType = Context.getQualifiedType(ResultType, Combined);
4411   } else if (LHSTy->isArrayType()) {
4412     // If we see an array that wasn't promoted by
4413     // DefaultFunctionArrayLvalueConversion, it must be an array that
4414     // wasn't promoted because of the C90 rule that doesn't
4415     // allow promoting non-lvalue arrays.  Warn, then
4416     // force the promotion here.
4417     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4418         LHSExp->getSourceRange();
4419     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4420                                CK_ArrayToPointerDecay).get();
4421     LHSTy = LHSExp->getType();
4422 
4423     BaseExpr = LHSExp;
4424     IndexExpr = RHSExp;
4425     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4426   } else if (RHSTy->isArrayType()) {
4427     // Same as previous, except for 123[f().a] case
4428     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4429         RHSExp->getSourceRange();
4430     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4431                                CK_ArrayToPointerDecay).get();
4432     RHSTy = RHSExp->getType();
4433 
4434     BaseExpr = RHSExp;
4435     IndexExpr = LHSExp;
4436     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4437   } else {
4438     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4439        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4440   }
4441   // C99 6.5.2.1p1
4442   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4443     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4444                      << IndexExpr->getSourceRange());
4445 
4446   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4447        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4448          && !IndexExpr->isTypeDependent())
4449     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4450 
4451   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4452   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4453   // type. Note that Functions are not objects, and that (in C99 parlance)
4454   // incomplete types are not object types.
4455   if (ResultType->isFunctionType()) {
4456     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4457       << ResultType << BaseExpr->getSourceRange();
4458     return ExprError();
4459   }
4460 
4461   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4462     // GNU extension: subscripting on pointer to void
4463     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4464       << BaseExpr->getSourceRange();
4465 
4466     // C forbids expressions of unqualified void type from being l-values.
4467     // See IsCForbiddenLValueType.
4468     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4469   } else if (!ResultType->isDependentType() &&
4470       RequireCompleteType(LLoc, ResultType,
4471                           diag::err_subscript_incomplete_type, BaseExpr))
4472     return ExprError();
4473 
4474   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4475          !ResultType.isCForbiddenLValueType());
4476 
4477   return new (Context)
4478       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4479 }
4480 
4481 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4482                                   ParmVarDecl *Param) {
4483   if (Param->hasUnparsedDefaultArg()) {
4484     Diag(CallLoc,
4485          diag::err_use_of_default_argument_to_function_declared_later) <<
4486       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4487     Diag(UnparsedDefaultArgLocs[Param],
4488          diag::note_default_argument_declared_here);
4489     return true;
4490   }
4491 
4492   if (Param->hasUninstantiatedDefaultArg()) {
4493     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4494 
4495     EnterExpressionEvaluationContext EvalContext(
4496         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4497 
4498     // Instantiate the expression.
4499     //
4500     // FIXME: Pass in a correct Pattern argument, otherwise
4501     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4502     //
4503     // template<typename T>
4504     // struct A {
4505     //   static int FooImpl();
4506     //
4507     //   template<typename Tp>
4508     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4509     //   // template argument list [[T], [Tp]], should be [[Tp]].
4510     //   friend A<Tp> Foo(int a);
4511     // };
4512     //
4513     // template<typename T>
4514     // A<T> Foo(int a = A<T>::FooImpl());
4515     MultiLevelTemplateArgumentList MutiLevelArgList
4516       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4517 
4518     InstantiatingTemplate Inst(*this, CallLoc, Param,
4519                                MutiLevelArgList.getInnermost());
4520     if (Inst.isInvalid())
4521       return true;
4522     if (Inst.isAlreadyInstantiating()) {
4523       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4524       Param->setInvalidDecl();
4525       return true;
4526     }
4527 
4528     ExprResult Result;
4529     {
4530       // C++ [dcl.fct.default]p5:
4531       //   The names in the [default argument] expression are bound, and
4532       //   the semantic constraints are checked, at the point where the
4533       //   default argument expression appears.
4534       ContextRAII SavedContext(*this, FD);
4535       LocalInstantiationScope Local(*this);
4536       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4537                                 /*DirectInit*/false);
4538     }
4539     if (Result.isInvalid())
4540       return true;
4541 
4542     // Check the expression as an initializer for the parameter.
4543     InitializedEntity Entity
4544       = InitializedEntity::InitializeParameter(Context, Param);
4545     InitializationKind Kind
4546       = InitializationKind::CreateCopy(Param->getLocation(),
4547              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4548     Expr *ResultE = Result.getAs<Expr>();
4549 
4550     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4551     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4552     if (Result.isInvalid())
4553       return true;
4554 
4555     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4556                                  Param->getOuterLocStart());
4557     if (Result.isInvalid())
4558       return true;
4559 
4560     // Remember the instantiated default argument.
4561     Param->setDefaultArg(Result.getAs<Expr>());
4562     if (ASTMutationListener *L = getASTMutationListener()) {
4563       L->DefaultArgumentInstantiated(Param);
4564     }
4565   }
4566 
4567   // If the default argument expression is not set yet, we are building it now.
4568   if (!Param->hasInit()) {
4569     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4570     Param->setInvalidDecl();
4571     return true;
4572   }
4573 
4574   // If the default expression creates temporaries, we need to
4575   // push them to the current stack of expression temporaries so they'll
4576   // be properly destroyed.
4577   // FIXME: We should really be rebuilding the default argument with new
4578   // bound temporaries; see the comment in PR5810.
4579   // We don't need to do that with block decls, though, because
4580   // blocks in default argument expression can never capture anything.
4581   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4582     // Set the "needs cleanups" bit regardless of whether there are
4583     // any explicit objects.
4584     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4585 
4586     // Append all the objects to the cleanup list.  Right now, this
4587     // should always be a no-op, because blocks in default argument
4588     // expressions should never be able to capture anything.
4589     assert(!Init->getNumObjects() &&
4590            "default argument expression has capturing blocks?");
4591   }
4592 
4593   // We already type-checked the argument, so we know it works.
4594   // Just mark all of the declarations in this potentially-evaluated expression
4595   // as being "referenced".
4596   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4597                                    /*SkipLocalVariables=*/true);
4598   return false;
4599 }
4600 
4601 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4602                                         FunctionDecl *FD, ParmVarDecl *Param) {
4603   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4604     return ExprError();
4605   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4606 }
4607 
4608 Sema::VariadicCallType
4609 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4610                           Expr *Fn) {
4611   if (Proto && Proto->isVariadic()) {
4612     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4613       return VariadicConstructor;
4614     else if (Fn && Fn->getType()->isBlockPointerType())
4615       return VariadicBlock;
4616     else if (FDecl) {
4617       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4618         if (Method->isInstance())
4619           return VariadicMethod;
4620     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4621       return VariadicMethod;
4622     return VariadicFunction;
4623   }
4624   return VariadicDoesNotApply;
4625 }
4626 
4627 namespace {
4628 class FunctionCallCCC : public FunctionCallFilterCCC {
4629 public:
4630   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4631                   unsigned NumArgs, MemberExpr *ME)
4632       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4633         FunctionName(FuncName) {}
4634 
4635   bool ValidateCandidate(const TypoCorrection &candidate) override {
4636     if (!candidate.getCorrectionSpecifier() ||
4637         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4638       return false;
4639     }
4640 
4641     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4642   }
4643 
4644 private:
4645   const IdentifierInfo *const FunctionName;
4646 };
4647 }
4648 
4649 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4650                                                FunctionDecl *FDecl,
4651                                                ArrayRef<Expr *> Args) {
4652   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4653   DeclarationName FuncName = FDecl->getDeclName();
4654   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4655 
4656   if (TypoCorrection Corrected = S.CorrectTypo(
4657           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4658           S.getScopeForContext(S.CurContext), nullptr,
4659           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4660                                              Args.size(), ME),
4661           Sema::CTK_ErrorRecovery)) {
4662     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4663       if (Corrected.isOverloaded()) {
4664         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4665         OverloadCandidateSet::iterator Best;
4666         for (NamedDecl *CD : Corrected) {
4667           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4668             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4669                                    OCS);
4670         }
4671         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4672         case OR_Success:
4673           ND = Best->FoundDecl;
4674           Corrected.setCorrectionDecl(ND);
4675           break;
4676         default:
4677           break;
4678         }
4679       }
4680       ND = ND->getUnderlyingDecl();
4681       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4682         return Corrected;
4683     }
4684   }
4685   return TypoCorrection();
4686 }
4687 
4688 /// ConvertArgumentsForCall - Converts the arguments specified in
4689 /// Args/NumArgs to the parameter types of the function FDecl with
4690 /// function prototype Proto. Call is the call expression itself, and
4691 /// Fn is the function expression. For a C++ member function, this
4692 /// routine does not attempt to convert the object argument. Returns
4693 /// true if the call is ill-formed.
4694 bool
4695 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4696                               FunctionDecl *FDecl,
4697                               const FunctionProtoType *Proto,
4698                               ArrayRef<Expr *> Args,
4699                               SourceLocation RParenLoc,
4700                               bool IsExecConfig) {
4701   // Bail out early if calling a builtin with custom typechecking.
4702   if (FDecl)
4703     if (unsigned ID = FDecl->getBuiltinID())
4704       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4705         return false;
4706 
4707   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4708   // assignment, to the types of the corresponding parameter, ...
4709   unsigned NumParams = Proto->getNumParams();
4710   bool Invalid = false;
4711   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4712   unsigned FnKind = Fn->getType()->isBlockPointerType()
4713                        ? 1 /* block */
4714                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4715                                        : 0 /* function */);
4716 
4717   // If too few arguments are available (and we don't have default
4718   // arguments for the remaining parameters), don't make the call.
4719   if (Args.size() < NumParams) {
4720     if (Args.size() < MinArgs) {
4721       TypoCorrection TC;
4722       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4723         unsigned diag_id =
4724             MinArgs == NumParams && !Proto->isVariadic()
4725                 ? diag::err_typecheck_call_too_few_args_suggest
4726                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4727         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4728                                         << static_cast<unsigned>(Args.size())
4729                                         << TC.getCorrectionRange());
4730       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4731         Diag(RParenLoc,
4732              MinArgs == NumParams && !Proto->isVariadic()
4733                  ? diag::err_typecheck_call_too_few_args_one
4734                  : diag::err_typecheck_call_too_few_args_at_least_one)
4735             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4736       else
4737         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4738                             ? diag::err_typecheck_call_too_few_args
4739                             : diag::err_typecheck_call_too_few_args_at_least)
4740             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4741             << Fn->getSourceRange();
4742 
4743       // Emit the location of the prototype.
4744       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4745         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4746           << FDecl;
4747 
4748       return true;
4749     }
4750     Call->setNumArgs(Context, NumParams);
4751   }
4752 
4753   // If too many are passed and not variadic, error on the extras and drop
4754   // them.
4755   if (Args.size() > NumParams) {
4756     if (!Proto->isVariadic()) {
4757       TypoCorrection TC;
4758       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4759         unsigned diag_id =
4760             MinArgs == NumParams && !Proto->isVariadic()
4761                 ? diag::err_typecheck_call_too_many_args_suggest
4762                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4763         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4764                                         << static_cast<unsigned>(Args.size())
4765                                         << TC.getCorrectionRange());
4766       } else if (NumParams == 1 && FDecl &&
4767                  FDecl->getParamDecl(0)->getDeclName())
4768         Diag(Args[NumParams]->getLocStart(),
4769              MinArgs == NumParams
4770                  ? diag::err_typecheck_call_too_many_args_one
4771                  : diag::err_typecheck_call_too_many_args_at_most_one)
4772             << FnKind << FDecl->getParamDecl(0)
4773             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4774             << SourceRange(Args[NumParams]->getLocStart(),
4775                            Args.back()->getLocEnd());
4776       else
4777         Diag(Args[NumParams]->getLocStart(),
4778              MinArgs == NumParams
4779                  ? diag::err_typecheck_call_too_many_args
4780                  : diag::err_typecheck_call_too_many_args_at_most)
4781             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4782             << Fn->getSourceRange()
4783             << SourceRange(Args[NumParams]->getLocStart(),
4784                            Args.back()->getLocEnd());
4785 
4786       // Emit the location of the prototype.
4787       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4788         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4789           << FDecl;
4790 
4791       // This deletes the extra arguments.
4792       Call->setNumArgs(Context, NumParams);
4793       return true;
4794     }
4795   }
4796   SmallVector<Expr *, 8> AllArgs;
4797   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4798 
4799   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4800                                    Proto, 0, Args, AllArgs, CallType);
4801   if (Invalid)
4802     return true;
4803   unsigned TotalNumArgs = AllArgs.size();
4804   for (unsigned i = 0; i < TotalNumArgs; ++i)
4805     Call->setArg(i, AllArgs[i]);
4806 
4807   return false;
4808 }
4809 
4810 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4811                                   const FunctionProtoType *Proto,
4812                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4813                                   SmallVectorImpl<Expr *> &AllArgs,
4814                                   VariadicCallType CallType, bool AllowExplicit,
4815                                   bool IsListInitialization) {
4816   unsigned NumParams = Proto->getNumParams();
4817   bool Invalid = false;
4818   size_t ArgIx = 0;
4819   // Continue to check argument types (even if we have too few/many args).
4820   for (unsigned i = FirstParam; i < NumParams; i++) {
4821     QualType ProtoArgType = Proto->getParamType(i);
4822 
4823     Expr *Arg;
4824     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4825     if (ArgIx < Args.size()) {
4826       Arg = Args[ArgIx++];
4827 
4828       if (RequireCompleteType(Arg->getLocStart(),
4829                               ProtoArgType,
4830                               diag::err_call_incomplete_argument, Arg))
4831         return true;
4832 
4833       // Strip the unbridged-cast placeholder expression off, if applicable.
4834       bool CFAudited = false;
4835       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4836           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4837           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4838         Arg = stripARCUnbridgedCast(Arg);
4839       else if (getLangOpts().ObjCAutoRefCount &&
4840                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4841                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4842         CFAudited = true;
4843 
4844       if (Proto->getExtParameterInfo(i).isNoEscape())
4845         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4846           BE->getBlockDecl()->setDoesNotEscape();
4847 
4848       InitializedEntity Entity =
4849           Param ? InitializedEntity::InitializeParameter(Context, Param,
4850                                                          ProtoArgType)
4851                 : InitializedEntity::InitializeParameter(
4852                       Context, ProtoArgType, Proto->isParamConsumed(i));
4853 
4854       // Remember that parameter belongs to a CF audited API.
4855       if (CFAudited)
4856         Entity.setParameterCFAudited();
4857 
4858       ExprResult ArgE = PerformCopyInitialization(
4859           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4860       if (ArgE.isInvalid())
4861         return true;
4862 
4863       Arg = ArgE.getAs<Expr>();
4864     } else {
4865       assert(Param && "can't use default arguments without a known callee");
4866 
4867       ExprResult ArgExpr =
4868         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4869       if (ArgExpr.isInvalid())
4870         return true;
4871 
4872       Arg = ArgExpr.getAs<Expr>();
4873     }
4874 
4875     // Check for array bounds violations for each argument to the call. This
4876     // check only triggers warnings when the argument isn't a more complex Expr
4877     // with its own checking, such as a BinaryOperator.
4878     CheckArrayAccess(Arg);
4879 
4880     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4881     CheckStaticArrayArgument(CallLoc, Param, Arg);
4882 
4883     AllArgs.push_back(Arg);
4884   }
4885 
4886   // If this is a variadic call, handle args passed through "...".
4887   if (CallType != VariadicDoesNotApply) {
4888     // Assume that extern "C" functions with variadic arguments that
4889     // return __unknown_anytype aren't *really* variadic.
4890     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4891         FDecl->isExternC()) {
4892       for (Expr *A : Args.slice(ArgIx)) {
4893         QualType paramType; // ignored
4894         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4895         Invalid |= arg.isInvalid();
4896         AllArgs.push_back(arg.get());
4897       }
4898 
4899     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4900     } else {
4901       for (Expr *A : Args.slice(ArgIx)) {
4902         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4903         Invalid |= Arg.isInvalid();
4904         AllArgs.push_back(Arg.get());
4905       }
4906     }
4907 
4908     // Check for array bounds violations.
4909     for (Expr *A : Args.slice(ArgIx))
4910       CheckArrayAccess(A);
4911   }
4912   return Invalid;
4913 }
4914 
4915 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4916   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4917   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4918     TL = DTL.getOriginalLoc();
4919   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4920     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4921       << ATL.getLocalSourceRange();
4922 }
4923 
4924 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4925 /// array parameter, check that it is non-null, and that if it is formed by
4926 /// array-to-pointer decay, the underlying array is sufficiently large.
4927 ///
4928 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4929 /// array type derivation, then for each call to the function, the value of the
4930 /// corresponding actual argument shall provide access to the first element of
4931 /// an array with at least as many elements as specified by the size expression.
4932 void
4933 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4934                                ParmVarDecl *Param,
4935                                const Expr *ArgExpr) {
4936   // Static array parameters are not supported in C++.
4937   if (!Param || getLangOpts().CPlusPlus)
4938     return;
4939 
4940   QualType OrigTy = Param->getOriginalType();
4941 
4942   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4943   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4944     return;
4945 
4946   if (ArgExpr->isNullPointerConstant(Context,
4947                                      Expr::NPC_NeverValueDependent)) {
4948     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4949     DiagnoseCalleeStaticArrayParam(*this, Param);
4950     return;
4951   }
4952 
4953   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4954   if (!CAT)
4955     return;
4956 
4957   const ConstantArrayType *ArgCAT =
4958     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4959   if (!ArgCAT)
4960     return;
4961 
4962   if (ArgCAT->getSize().ult(CAT->getSize())) {
4963     Diag(CallLoc, diag::warn_static_array_too_small)
4964       << ArgExpr->getSourceRange()
4965       << (unsigned) ArgCAT->getSize().getZExtValue()
4966       << (unsigned) CAT->getSize().getZExtValue();
4967     DiagnoseCalleeStaticArrayParam(*this, Param);
4968   }
4969 }
4970 
4971 /// Given a function expression of unknown-any type, try to rebuild it
4972 /// to have a function type.
4973 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4974 
4975 /// Is the given type a placeholder that we need to lower out
4976 /// immediately during argument processing?
4977 static bool isPlaceholderToRemoveAsArg(QualType type) {
4978   // Placeholders are never sugared.
4979   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4980   if (!placeholder) return false;
4981 
4982   switch (placeholder->getKind()) {
4983   // Ignore all the non-placeholder types.
4984 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4985   case BuiltinType::Id:
4986 #include "clang/Basic/OpenCLImageTypes.def"
4987 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4988 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4989 #include "clang/AST/BuiltinTypes.def"
4990     return false;
4991 
4992   // We cannot lower out overload sets; they might validly be resolved
4993   // by the call machinery.
4994   case BuiltinType::Overload:
4995     return false;
4996 
4997   // Unbridged casts in ARC can be handled in some call positions and
4998   // should be left in place.
4999   case BuiltinType::ARCUnbridgedCast:
5000     return false;
5001 
5002   // Pseudo-objects should be converted as soon as possible.
5003   case BuiltinType::PseudoObject:
5004     return true;
5005 
5006   // The debugger mode could theoretically but currently does not try
5007   // to resolve unknown-typed arguments based on known parameter types.
5008   case BuiltinType::UnknownAny:
5009     return true;
5010 
5011   // These are always invalid as call arguments and should be reported.
5012   case BuiltinType::BoundMember:
5013   case BuiltinType::BuiltinFn:
5014   case BuiltinType::OMPArraySection:
5015     return true;
5016 
5017   }
5018   llvm_unreachable("bad builtin type kind");
5019 }
5020 
5021 /// Check an argument list for placeholders that we won't try to
5022 /// handle later.
5023 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5024   // Apply this processing to all the arguments at once instead of
5025   // dying at the first failure.
5026   bool hasInvalid = false;
5027   for (size_t i = 0, e = args.size(); i != e; i++) {
5028     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5029       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5030       if (result.isInvalid()) hasInvalid = true;
5031       else args[i] = result.get();
5032     } else if (hasInvalid) {
5033       (void)S.CorrectDelayedTyposInExpr(args[i]);
5034     }
5035   }
5036   return hasInvalid;
5037 }
5038 
5039 /// If a builtin function has a pointer argument with no explicit address
5040 /// space, then it should be able to accept a pointer to any address
5041 /// space as input.  In order to do this, we need to replace the
5042 /// standard builtin declaration with one that uses the same address space
5043 /// as the call.
5044 ///
5045 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5046 ///                  it does not contain any pointer arguments without
5047 ///                  an address space qualifer.  Otherwise the rewritten
5048 ///                  FunctionDecl is returned.
5049 /// TODO: Handle pointer return types.
5050 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5051                                                 const FunctionDecl *FDecl,
5052                                                 MultiExprArg ArgExprs) {
5053 
5054   QualType DeclType = FDecl->getType();
5055   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5056 
5057   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5058       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5059     return nullptr;
5060 
5061   bool NeedsNewDecl = false;
5062   unsigned i = 0;
5063   SmallVector<QualType, 8> OverloadParams;
5064 
5065   for (QualType ParamType : FT->param_types()) {
5066 
5067     // Convert array arguments to pointer to simplify type lookup.
5068     ExprResult ArgRes =
5069         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5070     if (ArgRes.isInvalid())
5071       return nullptr;
5072     Expr *Arg = ArgRes.get();
5073     QualType ArgType = Arg->getType();
5074     if (!ParamType->isPointerType() ||
5075         ParamType.getQualifiers().hasAddressSpace() ||
5076         !ArgType->isPointerType() ||
5077         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5078       OverloadParams.push_back(ParamType);
5079       continue;
5080     }
5081 
5082     NeedsNewDecl = true;
5083     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5084 
5085     QualType PointeeType = ParamType->getPointeeType();
5086     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5087     OverloadParams.push_back(Context.getPointerType(PointeeType));
5088   }
5089 
5090   if (!NeedsNewDecl)
5091     return nullptr;
5092 
5093   FunctionProtoType::ExtProtoInfo EPI;
5094   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5095                                                 OverloadParams, EPI);
5096   DeclContext *Parent = Context.getTranslationUnitDecl();
5097   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5098                                                     FDecl->getLocation(),
5099                                                     FDecl->getLocation(),
5100                                                     FDecl->getIdentifier(),
5101                                                     OverloadTy,
5102                                                     /*TInfo=*/nullptr,
5103                                                     SC_Extern, false,
5104                                                     /*hasPrototype=*/true);
5105   SmallVector<ParmVarDecl*, 16> Params;
5106   FT = cast<FunctionProtoType>(OverloadTy);
5107   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5108     QualType ParamType = FT->getParamType(i);
5109     ParmVarDecl *Parm =
5110         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5111                                 SourceLocation(), nullptr, ParamType,
5112                                 /*TInfo=*/nullptr, SC_None, nullptr);
5113     Parm->setScopeInfo(0, i);
5114     Params.push_back(Parm);
5115   }
5116   OverloadDecl->setParams(Params);
5117   return OverloadDecl;
5118 }
5119 
5120 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5121                                     FunctionDecl *Callee,
5122                                     MultiExprArg ArgExprs) {
5123   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5124   // similar attributes) really don't like it when functions are called with an
5125   // invalid number of args.
5126   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5127                          /*PartialOverloading=*/false) &&
5128       !Callee->isVariadic())
5129     return;
5130   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5131     return;
5132 
5133   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5134     S.Diag(Fn->getLocStart(),
5135            isa<CXXMethodDecl>(Callee)
5136                ? diag::err_ovl_no_viable_member_function_in_call
5137                : diag::err_ovl_no_viable_function_in_call)
5138         << Callee << Callee->getSourceRange();
5139     S.Diag(Callee->getLocation(),
5140            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5141         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5142     return;
5143   }
5144 }
5145 
5146 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5147     const UnresolvedMemberExpr *const UME, Sema &S) {
5148 
5149   const auto GetFunctionLevelDCIfCXXClass =
5150       [](Sema &S) -> const CXXRecordDecl * {
5151     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5152     if (!DC || !DC->getParent())
5153       return nullptr;
5154 
5155     // If the call to some member function was made from within a member
5156     // function body 'M' return return 'M's parent.
5157     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5158       return MD->getParent()->getCanonicalDecl();
5159     // else the call was made from within a default member initializer of a
5160     // class, so return the class.
5161     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5162       return RD->getCanonicalDecl();
5163     return nullptr;
5164   };
5165   // If our DeclContext is neither a member function nor a class (in the
5166   // case of a lambda in a default member initializer), we can't have an
5167   // enclosing 'this'.
5168 
5169   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5170   if (!CurParentClass)
5171     return false;
5172 
5173   // The naming class for implicit member functions call is the class in which
5174   // name lookup starts.
5175   const CXXRecordDecl *const NamingClass =
5176       UME->getNamingClass()->getCanonicalDecl();
5177   assert(NamingClass && "Must have naming class even for implicit access");
5178 
5179   // If the unresolved member functions were found in a 'naming class' that is
5180   // related (either the same or derived from) to the class that contains the
5181   // member function that itself contained the implicit member access.
5182 
5183   return CurParentClass == NamingClass ||
5184          CurParentClass->isDerivedFrom(NamingClass);
5185 }
5186 
5187 static void
5188 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5189     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5190 
5191   if (!UME)
5192     return;
5193 
5194   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5195   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5196   // already been captured, or if this is an implicit member function call (if
5197   // it isn't, an attempt to capture 'this' should already have been made).
5198   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5199       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5200     return;
5201 
5202   // Check if the naming class in which the unresolved members were found is
5203   // related (same as or is a base of) to the enclosing class.
5204 
5205   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5206     return;
5207 
5208 
5209   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5210   // If the enclosing function is not dependent, then this lambda is
5211   // capture ready, so if we can capture this, do so.
5212   if (!EnclosingFunctionCtx->isDependentContext()) {
5213     // If the current lambda and all enclosing lambdas can capture 'this' -
5214     // then go ahead and capture 'this' (since our unresolved overload set
5215     // contains at least one non-static member function).
5216     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5217       S.CheckCXXThisCapture(CallLoc);
5218   } else if (S.CurContext->isDependentContext()) {
5219     // ... since this is an implicit member reference, that might potentially
5220     // involve a 'this' capture, mark 'this' for potential capture in
5221     // enclosing lambdas.
5222     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5223       CurLSI->addPotentialThisCapture(CallLoc);
5224   }
5225 }
5226 
5227 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5228 /// This provides the location of the left/right parens and a list of comma
5229 /// locations.
5230 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5231                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5232                                Expr *ExecConfig, bool IsExecConfig) {
5233   // Since this might be a postfix expression, get rid of ParenListExprs.
5234   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5235   if (Result.isInvalid()) return ExprError();
5236   Fn = Result.get();
5237 
5238   if (checkArgsForPlaceholders(*this, ArgExprs))
5239     return ExprError();
5240 
5241   if (getLangOpts().CPlusPlus) {
5242     // If this is a pseudo-destructor expression, build the call immediately.
5243     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5244       if (!ArgExprs.empty()) {
5245         // Pseudo-destructor calls should not have any arguments.
5246         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5247             << FixItHint::CreateRemoval(
5248                    SourceRange(ArgExprs.front()->getLocStart(),
5249                                ArgExprs.back()->getLocEnd()));
5250       }
5251 
5252       return new (Context)
5253           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5254     }
5255     if (Fn->getType() == Context.PseudoObjectTy) {
5256       ExprResult result = CheckPlaceholderExpr(Fn);
5257       if (result.isInvalid()) return ExprError();
5258       Fn = result.get();
5259     }
5260 
5261     // Determine whether this is a dependent call inside a C++ template,
5262     // in which case we won't do any semantic analysis now.
5263     bool Dependent = false;
5264     if (Fn->isTypeDependent())
5265       Dependent = true;
5266     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5267       Dependent = true;
5268 
5269     if (Dependent) {
5270       if (ExecConfig) {
5271         return new (Context) CUDAKernelCallExpr(
5272             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5273             Context.DependentTy, VK_RValue, RParenLoc);
5274       } else {
5275 
5276        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5277             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5278             Fn->getLocStart());
5279 
5280         return new (Context) CallExpr(
5281             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5282       }
5283     }
5284 
5285     // Determine whether this is a call to an object (C++ [over.call.object]).
5286     if (Fn->getType()->isRecordType())
5287       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5288                                           RParenLoc);
5289 
5290     if (Fn->getType() == Context.UnknownAnyTy) {
5291       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5292       if (result.isInvalid()) return ExprError();
5293       Fn = result.get();
5294     }
5295 
5296     if (Fn->getType() == Context.BoundMemberTy) {
5297       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5298                                        RParenLoc);
5299     }
5300   }
5301 
5302   // Check for overloaded calls.  This can happen even in C due to extensions.
5303   if (Fn->getType() == Context.OverloadTy) {
5304     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5305 
5306     // We aren't supposed to apply this logic if there's an '&' involved.
5307     if (!find.HasFormOfMemberPointer) {
5308       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5309         return new (Context) CallExpr(
5310             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5311       OverloadExpr *ovl = find.Expression;
5312       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5313         return BuildOverloadedCallExpr(
5314             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5315             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5316       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5317                                        RParenLoc);
5318     }
5319   }
5320 
5321   // If we're directly calling a function, get the appropriate declaration.
5322   if (Fn->getType() == Context.UnknownAnyTy) {
5323     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5324     if (result.isInvalid()) return ExprError();
5325     Fn = result.get();
5326   }
5327 
5328   Expr *NakedFn = Fn->IgnoreParens();
5329 
5330   bool CallingNDeclIndirectly = false;
5331   NamedDecl *NDecl = nullptr;
5332   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5333     if (UnOp->getOpcode() == UO_AddrOf) {
5334       CallingNDeclIndirectly = true;
5335       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5336     }
5337   }
5338 
5339   if (isa<DeclRefExpr>(NakedFn)) {
5340     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5341 
5342     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5343     if (FDecl && FDecl->getBuiltinID()) {
5344       // Rewrite the function decl for this builtin by replacing parameters
5345       // with no explicit address space with the address space of the arguments
5346       // in ArgExprs.
5347       if ((FDecl =
5348                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5349         NDecl = FDecl;
5350         Fn = DeclRefExpr::Create(
5351             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5352             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5353       }
5354     }
5355   } else if (isa<MemberExpr>(NakedFn))
5356     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5357 
5358   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5359     if (CallingNDeclIndirectly &&
5360         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5361                                            Fn->getLocStart()))
5362       return ExprError();
5363 
5364     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5365       return ExprError();
5366 
5367     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5368   }
5369 
5370   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5371                                ExecConfig, IsExecConfig);
5372 }
5373 
5374 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5375 ///
5376 /// __builtin_astype( value, dst type )
5377 ///
5378 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5379                                  SourceLocation BuiltinLoc,
5380                                  SourceLocation RParenLoc) {
5381   ExprValueKind VK = VK_RValue;
5382   ExprObjectKind OK = OK_Ordinary;
5383   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5384   QualType SrcTy = E->getType();
5385   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5386     return ExprError(Diag(BuiltinLoc,
5387                           diag::err_invalid_astype_of_different_size)
5388                      << DstTy
5389                      << SrcTy
5390                      << E->getSourceRange());
5391   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5392 }
5393 
5394 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5395 /// provided arguments.
5396 ///
5397 /// __builtin_convertvector( value, dst type )
5398 ///
5399 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5400                                         SourceLocation BuiltinLoc,
5401                                         SourceLocation RParenLoc) {
5402   TypeSourceInfo *TInfo;
5403   GetTypeFromParser(ParsedDestTy, &TInfo);
5404   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5405 }
5406 
5407 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5408 /// i.e. an expression not of \p OverloadTy.  The expression should
5409 /// unary-convert to an expression of function-pointer or
5410 /// block-pointer type.
5411 ///
5412 /// \param NDecl the declaration being called, if available
5413 ExprResult
5414 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5415                             SourceLocation LParenLoc,
5416                             ArrayRef<Expr *> Args,
5417                             SourceLocation RParenLoc,
5418                             Expr *Config, bool IsExecConfig) {
5419   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5420   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5421 
5422   // Functions with 'interrupt' attribute cannot be called directly.
5423   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5424     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5425     return ExprError();
5426   }
5427 
5428   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5429   // so there's some risk when calling out to non-interrupt handler functions
5430   // that the callee might not preserve them. This is easy to diagnose here,
5431   // but can be very challenging to debug.
5432   if (auto *Caller = getCurFunctionDecl())
5433     if (Caller->hasAttr<ARMInterruptAttr>()) {
5434       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5435       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5436         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5437     }
5438 
5439   // Promote the function operand.
5440   // We special-case function promotion here because we only allow promoting
5441   // builtin functions to function pointers in the callee of a call.
5442   ExprResult Result;
5443   if (BuiltinID &&
5444       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5445     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5446                                CK_BuiltinFnToFnPtr).get();
5447   } else {
5448     Result = CallExprUnaryConversions(Fn);
5449   }
5450   if (Result.isInvalid())
5451     return ExprError();
5452   Fn = Result.get();
5453 
5454   // Make the call expr early, before semantic checks.  This guarantees cleanup
5455   // of arguments and function on error.
5456   CallExpr *TheCall;
5457   if (Config)
5458     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5459                                                cast<CallExpr>(Config), Args,
5460                                                Context.BoolTy, VK_RValue,
5461                                                RParenLoc);
5462   else
5463     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5464                                      VK_RValue, RParenLoc);
5465 
5466   if (!getLangOpts().CPlusPlus) {
5467     // C cannot always handle TypoExpr nodes in builtin calls and direct
5468     // function calls as their argument checking don't necessarily handle
5469     // dependent types properly, so make sure any TypoExprs have been
5470     // dealt with.
5471     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5472     if (!Result.isUsable()) return ExprError();
5473     TheCall = dyn_cast<CallExpr>(Result.get());
5474     if (!TheCall) return Result;
5475     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5476   }
5477 
5478   // Bail out early if calling a builtin with custom typechecking.
5479   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5480     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5481 
5482  retry:
5483   const FunctionType *FuncT;
5484   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5485     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5486     // have type pointer to function".
5487     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5488     if (!FuncT)
5489       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5490                          << Fn->getType() << Fn->getSourceRange());
5491   } else if (const BlockPointerType *BPT =
5492                Fn->getType()->getAs<BlockPointerType>()) {
5493     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5494   } else {
5495     // Handle calls to expressions of unknown-any type.
5496     if (Fn->getType() == Context.UnknownAnyTy) {
5497       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5498       if (rewrite.isInvalid()) return ExprError();
5499       Fn = rewrite.get();
5500       TheCall->setCallee(Fn);
5501       goto retry;
5502     }
5503 
5504     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5505       << Fn->getType() << Fn->getSourceRange());
5506   }
5507 
5508   if (getLangOpts().CUDA) {
5509     if (Config) {
5510       // CUDA: Kernel calls must be to global functions
5511       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5512         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5513             << FDecl->getName() << Fn->getSourceRange());
5514 
5515       // CUDA: Kernel function must have 'void' return type
5516       if (!FuncT->getReturnType()->isVoidType())
5517         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5518             << Fn->getType() << Fn->getSourceRange());
5519     } else {
5520       // CUDA: Calls to global functions must be configured
5521       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5522         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5523             << FDecl->getName() << Fn->getSourceRange());
5524     }
5525   }
5526 
5527   // Check for a valid return type
5528   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5529                           FDecl))
5530     return ExprError();
5531 
5532   // We know the result type of the call, set it.
5533   TheCall->setType(FuncT->getCallResultType(Context));
5534   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5535 
5536   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5537   if (Proto) {
5538     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5539                                 IsExecConfig))
5540       return ExprError();
5541   } else {
5542     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5543 
5544     if (FDecl) {
5545       // Check if we have too few/too many template arguments, based
5546       // on our knowledge of the function definition.
5547       const FunctionDecl *Def = nullptr;
5548       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5549         Proto = Def->getType()->getAs<FunctionProtoType>();
5550        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5551           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5552           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5553       }
5554 
5555       // If the function we're calling isn't a function prototype, but we have
5556       // a function prototype from a prior declaratiom, use that prototype.
5557       if (!FDecl->hasPrototype())
5558         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5559     }
5560 
5561     // Promote the arguments (C99 6.5.2.2p6).
5562     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5563       Expr *Arg = Args[i];
5564 
5565       if (Proto && i < Proto->getNumParams()) {
5566         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5567             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5568         ExprResult ArgE =
5569             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5570         if (ArgE.isInvalid())
5571           return true;
5572 
5573         Arg = ArgE.getAs<Expr>();
5574 
5575       } else {
5576         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5577 
5578         if (ArgE.isInvalid())
5579           return true;
5580 
5581         Arg = ArgE.getAs<Expr>();
5582       }
5583 
5584       if (RequireCompleteType(Arg->getLocStart(),
5585                               Arg->getType(),
5586                               diag::err_call_incomplete_argument, Arg))
5587         return ExprError();
5588 
5589       TheCall->setArg(i, Arg);
5590     }
5591   }
5592 
5593   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5594     if (!Method->isStatic())
5595       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5596         << Fn->getSourceRange());
5597 
5598   // Check for sentinels
5599   if (NDecl)
5600     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5601 
5602   // Do special checking on direct calls to functions.
5603   if (FDecl) {
5604     if (CheckFunctionCall(FDecl, TheCall, Proto))
5605       return ExprError();
5606 
5607     if (BuiltinID)
5608       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5609   } else if (NDecl) {
5610     if (CheckPointerCall(NDecl, TheCall, Proto))
5611       return ExprError();
5612   } else {
5613     if (CheckOtherCall(TheCall, Proto))
5614       return ExprError();
5615   }
5616 
5617   return MaybeBindToTemporary(TheCall);
5618 }
5619 
5620 ExprResult
5621 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5622                            SourceLocation RParenLoc, Expr *InitExpr) {
5623   assert(Ty && "ActOnCompoundLiteral(): missing type");
5624   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5625 
5626   TypeSourceInfo *TInfo;
5627   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5628   if (!TInfo)
5629     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5630 
5631   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5632 }
5633 
5634 ExprResult
5635 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5636                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5637   QualType literalType = TInfo->getType();
5638 
5639   if (literalType->isArrayType()) {
5640     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5641           diag::err_illegal_decl_array_incomplete_type,
5642           SourceRange(LParenLoc,
5643                       LiteralExpr->getSourceRange().getEnd())))
5644       return ExprError();
5645     if (literalType->isVariableArrayType())
5646       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5647         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5648   } else if (!literalType->isDependentType() &&
5649              RequireCompleteType(LParenLoc, literalType,
5650                diag::err_typecheck_decl_incomplete_type,
5651                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5652     return ExprError();
5653 
5654   InitializedEntity Entity
5655     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5656   InitializationKind Kind
5657     = InitializationKind::CreateCStyleCast(LParenLoc,
5658                                            SourceRange(LParenLoc, RParenLoc),
5659                                            /*InitList=*/true);
5660   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5661   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5662                                       &literalType);
5663   if (Result.isInvalid())
5664     return ExprError();
5665   LiteralExpr = Result.get();
5666 
5667   bool isFileScope = !CurContext->isFunctionOrMethod();
5668   if (isFileScope &&
5669       !LiteralExpr->isTypeDependent() &&
5670       !LiteralExpr->isValueDependent() &&
5671       !literalType->isDependentType()) { // 6.5.2.5p3
5672     if (CheckForConstantInitializer(LiteralExpr, literalType))
5673       return ExprError();
5674   }
5675 
5676   // In C, compound literals are l-values for some reason.
5677   // For GCC compatibility, in C++, file-scope array compound literals with
5678   // constant initializers are also l-values, and compound literals are
5679   // otherwise prvalues.
5680   //
5681   // (GCC also treats C++ list-initialized file-scope array prvalues with
5682   // constant initializers as l-values, but that's non-conforming, so we don't
5683   // follow it there.)
5684   //
5685   // FIXME: It would be better to handle the lvalue cases as materializing and
5686   // lifetime-extending a temporary object, but our materialized temporaries
5687   // representation only supports lifetime extension from a variable, not "out
5688   // of thin air".
5689   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5690   // is bound to the result of applying array-to-pointer decay to the compound
5691   // literal.
5692   // FIXME: GCC supports compound literals of reference type, which should
5693   // obviously have a value kind derived from the kind of reference involved.
5694   ExprValueKind VK =
5695       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5696           ? VK_RValue
5697           : VK_LValue;
5698 
5699   return MaybeBindToTemporary(
5700       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5701                                         VK, LiteralExpr, isFileScope));
5702 }
5703 
5704 ExprResult
5705 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5706                     SourceLocation RBraceLoc) {
5707   // Immediately handle non-overload placeholders.  Overloads can be
5708   // resolved contextually, but everything else here can't.
5709   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5710     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5711       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5712 
5713       // Ignore failures; dropping the entire initializer list because
5714       // of one failure would be terrible for indexing/etc.
5715       if (result.isInvalid()) continue;
5716 
5717       InitArgList[I] = result.get();
5718     }
5719   }
5720 
5721   // Semantic analysis for initializers is done by ActOnDeclarator() and
5722   // CheckInitializer() - it requires knowledge of the object being intialized.
5723 
5724   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5725                                                RBraceLoc);
5726   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5727   return E;
5728 }
5729 
5730 /// Do an explicit extend of the given block pointer if we're in ARC.
5731 void Sema::maybeExtendBlockObject(ExprResult &E) {
5732   assert(E.get()->getType()->isBlockPointerType());
5733   assert(E.get()->isRValue());
5734 
5735   // Only do this in an r-value context.
5736   if (!getLangOpts().ObjCAutoRefCount) return;
5737 
5738   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5739                                CK_ARCExtendBlockObject, E.get(),
5740                                /*base path*/ nullptr, VK_RValue);
5741   Cleanup.setExprNeedsCleanups(true);
5742 }
5743 
5744 /// Prepare a conversion of the given expression to an ObjC object
5745 /// pointer type.
5746 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5747   QualType type = E.get()->getType();
5748   if (type->isObjCObjectPointerType()) {
5749     return CK_BitCast;
5750   } else if (type->isBlockPointerType()) {
5751     maybeExtendBlockObject(E);
5752     return CK_BlockPointerToObjCPointerCast;
5753   } else {
5754     assert(type->isPointerType());
5755     return CK_CPointerToObjCPointerCast;
5756   }
5757 }
5758 
5759 /// Prepares for a scalar cast, performing all the necessary stages
5760 /// except the final cast and returning the kind required.
5761 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5762   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5763   // Also, callers should have filtered out the invalid cases with
5764   // pointers.  Everything else should be possible.
5765 
5766   QualType SrcTy = Src.get()->getType();
5767   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5768     return CK_NoOp;
5769 
5770   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5771   case Type::STK_MemberPointer:
5772     llvm_unreachable("member pointer type in C");
5773 
5774   case Type::STK_CPointer:
5775   case Type::STK_BlockPointer:
5776   case Type::STK_ObjCObjectPointer:
5777     switch (DestTy->getScalarTypeKind()) {
5778     case Type::STK_CPointer: {
5779       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5780       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5781       if (SrcAS != DestAS)
5782         return CK_AddressSpaceConversion;
5783       return CK_BitCast;
5784     }
5785     case Type::STK_BlockPointer:
5786       return (SrcKind == Type::STK_BlockPointer
5787                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5788     case Type::STK_ObjCObjectPointer:
5789       if (SrcKind == Type::STK_ObjCObjectPointer)
5790         return CK_BitCast;
5791       if (SrcKind == Type::STK_CPointer)
5792         return CK_CPointerToObjCPointerCast;
5793       maybeExtendBlockObject(Src);
5794       return CK_BlockPointerToObjCPointerCast;
5795     case Type::STK_Bool:
5796       return CK_PointerToBoolean;
5797     case Type::STK_Integral:
5798       return CK_PointerToIntegral;
5799     case Type::STK_Floating:
5800     case Type::STK_FloatingComplex:
5801     case Type::STK_IntegralComplex:
5802     case Type::STK_MemberPointer:
5803       llvm_unreachable("illegal cast from pointer");
5804     }
5805     llvm_unreachable("Should have returned before this");
5806 
5807   case Type::STK_Bool: // casting from bool is like casting from an integer
5808   case Type::STK_Integral:
5809     switch (DestTy->getScalarTypeKind()) {
5810     case Type::STK_CPointer:
5811     case Type::STK_ObjCObjectPointer:
5812     case Type::STK_BlockPointer:
5813       if (Src.get()->isNullPointerConstant(Context,
5814                                            Expr::NPC_ValueDependentIsNull))
5815         return CK_NullToPointer;
5816       return CK_IntegralToPointer;
5817     case Type::STK_Bool:
5818       return CK_IntegralToBoolean;
5819     case Type::STK_Integral:
5820       return CK_IntegralCast;
5821     case Type::STK_Floating:
5822       return CK_IntegralToFloating;
5823     case Type::STK_IntegralComplex:
5824       Src = ImpCastExprToType(Src.get(),
5825                       DestTy->castAs<ComplexType>()->getElementType(),
5826                       CK_IntegralCast);
5827       return CK_IntegralRealToComplex;
5828     case Type::STK_FloatingComplex:
5829       Src = ImpCastExprToType(Src.get(),
5830                       DestTy->castAs<ComplexType>()->getElementType(),
5831                       CK_IntegralToFloating);
5832       return CK_FloatingRealToComplex;
5833     case Type::STK_MemberPointer:
5834       llvm_unreachable("member pointer type in C");
5835     }
5836     llvm_unreachable("Should have returned before this");
5837 
5838   case Type::STK_Floating:
5839     switch (DestTy->getScalarTypeKind()) {
5840     case Type::STK_Floating:
5841       return CK_FloatingCast;
5842     case Type::STK_Bool:
5843       return CK_FloatingToBoolean;
5844     case Type::STK_Integral:
5845       return CK_FloatingToIntegral;
5846     case Type::STK_FloatingComplex:
5847       Src = ImpCastExprToType(Src.get(),
5848                               DestTy->castAs<ComplexType>()->getElementType(),
5849                               CK_FloatingCast);
5850       return CK_FloatingRealToComplex;
5851     case Type::STK_IntegralComplex:
5852       Src = ImpCastExprToType(Src.get(),
5853                               DestTy->castAs<ComplexType>()->getElementType(),
5854                               CK_FloatingToIntegral);
5855       return CK_IntegralRealToComplex;
5856     case Type::STK_CPointer:
5857     case Type::STK_ObjCObjectPointer:
5858     case Type::STK_BlockPointer:
5859       llvm_unreachable("valid float->pointer cast?");
5860     case Type::STK_MemberPointer:
5861       llvm_unreachable("member pointer type in C");
5862     }
5863     llvm_unreachable("Should have returned before this");
5864 
5865   case Type::STK_FloatingComplex:
5866     switch (DestTy->getScalarTypeKind()) {
5867     case Type::STK_FloatingComplex:
5868       return CK_FloatingComplexCast;
5869     case Type::STK_IntegralComplex:
5870       return CK_FloatingComplexToIntegralComplex;
5871     case Type::STK_Floating: {
5872       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5873       if (Context.hasSameType(ET, DestTy))
5874         return CK_FloatingComplexToReal;
5875       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5876       return CK_FloatingCast;
5877     }
5878     case Type::STK_Bool:
5879       return CK_FloatingComplexToBoolean;
5880     case Type::STK_Integral:
5881       Src = ImpCastExprToType(Src.get(),
5882                               SrcTy->castAs<ComplexType>()->getElementType(),
5883                               CK_FloatingComplexToReal);
5884       return CK_FloatingToIntegral;
5885     case Type::STK_CPointer:
5886     case Type::STK_ObjCObjectPointer:
5887     case Type::STK_BlockPointer:
5888       llvm_unreachable("valid complex float->pointer cast?");
5889     case Type::STK_MemberPointer:
5890       llvm_unreachable("member pointer type in C");
5891     }
5892     llvm_unreachable("Should have returned before this");
5893 
5894   case Type::STK_IntegralComplex:
5895     switch (DestTy->getScalarTypeKind()) {
5896     case Type::STK_FloatingComplex:
5897       return CK_IntegralComplexToFloatingComplex;
5898     case Type::STK_IntegralComplex:
5899       return CK_IntegralComplexCast;
5900     case Type::STK_Integral: {
5901       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5902       if (Context.hasSameType(ET, DestTy))
5903         return CK_IntegralComplexToReal;
5904       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5905       return CK_IntegralCast;
5906     }
5907     case Type::STK_Bool:
5908       return CK_IntegralComplexToBoolean;
5909     case Type::STK_Floating:
5910       Src = ImpCastExprToType(Src.get(),
5911                               SrcTy->castAs<ComplexType>()->getElementType(),
5912                               CK_IntegralComplexToReal);
5913       return CK_IntegralToFloating;
5914     case Type::STK_CPointer:
5915     case Type::STK_ObjCObjectPointer:
5916     case Type::STK_BlockPointer:
5917       llvm_unreachable("valid complex int->pointer cast?");
5918     case Type::STK_MemberPointer:
5919       llvm_unreachable("member pointer type in C");
5920     }
5921     llvm_unreachable("Should have returned before this");
5922   }
5923 
5924   llvm_unreachable("Unhandled scalar cast");
5925 }
5926 
5927 static bool breakDownVectorType(QualType type, uint64_t &len,
5928                                 QualType &eltType) {
5929   // Vectors are simple.
5930   if (const VectorType *vecType = type->getAs<VectorType>()) {
5931     len = vecType->getNumElements();
5932     eltType = vecType->getElementType();
5933     assert(eltType->isScalarType());
5934     return true;
5935   }
5936 
5937   // We allow lax conversion to and from non-vector types, but only if
5938   // they're real types (i.e. non-complex, non-pointer scalar types).
5939   if (!type->isRealType()) return false;
5940 
5941   len = 1;
5942   eltType = type;
5943   return true;
5944 }
5945 
5946 /// Are the two types lax-compatible vector types?  That is, given
5947 /// that one of them is a vector, do they have equal storage sizes,
5948 /// where the storage size is the number of elements times the element
5949 /// size?
5950 ///
5951 /// This will also return false if either of the types is neither a
5952 /// vector nor a real type.
5953 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5954   assert(destTy->isVectorType() || srcTy->isVectorType());
5955 
5956   // Disallow lax conversions between scalars and ExtVectors (these
5957   // conversions are allowed for other vector types because common headers
5958   // depend on them).  Most scalar OP ExtVector cases are handled by the
5959   // splat path anyway, which does what we want (convert, not bitcast).
5960   // What this rules out for ExtVectors is crazy things like char4*float.
5961   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5962   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5963 
5964   uint64_t srcLen, destLen;
5965   QualType srcEltTy, destEltTy;
5966   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5967   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5968 
5969   // ASTContext::getTypeSize will return the size rounded up to a
5970   // power of 2, so instead of using that, we need to use the raw
5971   // element size multiplied by the element count.
5972   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5973   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5974 
5975   return (srcLen * srcEltSize == destLen * destEltSize);
5976 }
5977 
5978 /// Is this a legal conversion between two types, one of which is
5979 /// known to be a vector type?
5980 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5981   assert(destTy->isVectorType() || srcTy->isVectorType());
5982 
5983   if (!Context.getLangOpts().LaxVectorConversions)
5984     return false;
5985   return areLaxCompatibleVectorTypes(srcTy, destTy);
5986 }
5987 
5988 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5989                            CastKind &Kind) {
5990   assert(VectorTy->isVectorType() && "Not a vector type!");
5991 
5992   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5993     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5994       return Diag(R.getBegin(),
5995                   Ty->isVectorType() ?
5996                   diag::err_invalid_conversion_between_vectors :
5997                   diag::err_invalid_conversion_between_vector_and_integer)
5998         << VectorTy << Ty << R;
5999   } else
6000     return Diag(R.getBegin(),
6001                 diag::err_invalid_conversion_between_vector_and_scalar)
6002       << VectorTy << Ty << R;
6003 
6004   Kind = CK_BitCast;
6005   return false;
6006 }
6007 
6008 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6009   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6010 
6011   if (DestElemTy == SplattedExpr->getType())
6012     return SplattedExpr;
6013 
6014   assert(DestElemTy->isFloatingType() ||
6015          DestElemTy->isIntegralOrEnumerationType());
6016 
6017   CastKind CK;
6018   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6019     // OpenCL requires that we convert `true` boolean expressions to -1, but
6020     // only when splatting vectors.
6021     if (DestElemTy->isFloatingType()) {
6022       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6023       // in two steps: boolean to signed integral, then to floating.
6024       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6025                                                  CK_BooleanToSignedIntegral);
6026       SplattedExpr = CastExprRes.get();
6027       CK = CK_IntegralToFloating;
6028     } else {
6029       CK = CK_BooleanToSignedIntegral;
6030     }
6031   } else {
6032     ExprResult CastExprRes = SplattedExpr;
6033     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6034     if (CastExprRes.isInvalid())
6035       return ExprError();
6036     SplattedExpr = CastExprRes.get();
6037   }
6038   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6039 }
6040 
6041 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6042                                     Expr *CastExpr, CastKind &Kind) {
6043   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6044 
6045   QualType SrcTy = CastExpr->getType();
6046 
6047   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6048   // an ExtVectorType.
6049   // In OpenCL, casts between vectors of different types are not allowed.
6050   // (See OpenCL 6.2).
6051   if (SrcTy->isVectorType()) {
6052     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6053         (getLangOpts().OpenCL &&
6054          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6055       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6056         << DestTy << SrcTy << R;
6057       return ExprError();
6058     }
6059     Kind = CK_BitCast;
6060     return CastExpr;
6061   }
6062 
6063   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6064   // conversion will take place first from scalar to elt type, and then
6065   // splat from elt type to vector.
6066   if (SrcTy->isPointerType())
6067     return Diag(R.getBegin(),
6068                 diag::err_invalid_conversion_between_vector_and_scalar)
6069       << DestTy << SrcTy << R;
6070 
6071   Kind = CK_VectorSplat;
6072   return prepareVectorSplat(DestTy, CastExpr);
6073 }
6074 
6075 ExprResult
6076 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6077                     Declarator &D, ParsedType &Ty,
6078                     SourceLocation RParenLoc, Expr *CastExpr) {
6079   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6080          "ActOnCastExpr(): missing type or expr");
6081 
6082   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6083   if (D.isInvalidType())
6084     return ExprError();
6085 
6086   if (getLangOpts().CPlusPlus) {
6087     // Check that there are no default arguments (C++ only).
6088     CheckExtraCXXDefaultArguments(D);
6089   } else {
6090     // Make sure any TypoExprs have been dealt with.
6091     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6092     if (!Res.isUsable())
6093       return ExprError();
6094     CastExpr = Res.get();
6095   }
6096 
6097   checkUnusedDeclAttributes(D);
6098 
6099   QualType castType = castTInfo->getType();
6100   Ty = CreateParsedType(castType, castTInfo);
6101 
6102   bool isVectorLiteral = false;
6103 
6104   // Check for an altivec or OpenCL literal,
6105   // i.e. all the elements are integer constants.
6106   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6107   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6108   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6109        && castType->isVectorType() && (PE || PLE)) {
6110     if (PLE && PLE->getNumExprs() == 0) {
6111       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6112       return ExprError();
6113     }
6114     if (PE || PLE->getNumExprs() == 1) {
6115       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6116       if (!E->getType()->isVectorType())
6117         isVectorLiteral = true;
6118     }
6119     else
6120       isVectorLiteral = true;
6121   }
6122 
6123   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6124   // then handle it as such.
6125   if (isVectorLiteral)
6126     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6127 
6128   // If the Expr being casted is a ParenListExpr, handle it specially.
6129   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6130   // sequence of BinOp comma operators.
6131   if (isa<ParenListExpr>(CastExpr)) {
6132     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6133     if (Result.isInvalid()) return ExprError();
6134     CastExpr = Result.get();
6135   }
6136 
6137   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6138       !getSourceManager().isInSystemMacro(LParenLoc))
6139     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6140 
6141   CheckTollFreeBridgeCast(castType, CastExpr);
6142 
6143   CheckObjCBridgeRelatedCast(castType, CastExpr);
6144 
6145   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6146 
6147   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6148 }
6149 
6150 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6151                                     SourceLocation RParenLoc, Expr *E,
6152                                     TypeSourceInfo *TInfo) {
6153   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6154          "Expected paren or paren list expression");
6155 
6156   Expr **exprs;
6157   unsigned numExprs;
6158   Expr *subExpr;
6159   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6160   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6161     LiteralLParenLoc = PE->getLParenLoc();
6162     LiteralRParenLoc = PE->getRParenLoc();
6163     exprs = PE->getExprs();
6164     numExprs = PE->getNumExprs();
6165   } else { // isa<ParenExpr> by assertion at function entrance
6166     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6167     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6168     subExpr = cast<ParenExpr>(E)->getSubExpr();
6169     exprs = &subExpr;
6170     numExprs = 1;
6171   }
6172 
6173   QualType Ty = TInfo->getType();
6174   assert(Ty->isVectorType() && "Expected vector type");
6175 
6176   SmallVector<Expr *, 8> initExprs;
6177   const VectorType *VTy = Ty->getAs<VectorType>();
6178   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6179 
6180   // '(...)' form of vector initialization in AltiVec: the number of
6181   // initializers must be one or must match the size of the vector.
6182   // If a single value is specified in the initializer then it will be
6183   // replicated to all the components of the vector
6184   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6185     // The number of initializers must be one or must match the size of the
6186     // vector. If a single value is specified in the initializer then it will
6187     // be replicated to all the components of the vector
6188     if (numExprs == 1) {
6189       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6190       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6191       if (Literal.isInvalid())
6192         return ExprError();
6193       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6194                                   PrepareScalarCast(Literal, ElemTy));
6195       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6196     }
6197     else if (numExprs < numElems) {
6198       Diag(E->getExprLoc(),
6199            diag::err_incorrect_number_of_vector_initializers);
6200       return ExprError();
6201     }
6202     else
6203       initExprs.append(exprs, exprs + numExprs);
6204   }
6205   else {
6206     // For OpenCL, when the number of initializers is a single value,
6207     // it will be replicated to all components of the vector.
6208     if (getLangOpts().OpenCL &&
6209         VTy->getVectorKind() == VectorType::GenericVector &&
6210         numExprs == 1) {
6211         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6212         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6213         if (Literal.isInvalid())
6214           return ExprError();
6215         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6216                                     PrepareScalarCast(Literal, ElemTy));
6217         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6218     }
6219 
6220     initExprs.append(exprs, exprs + numExprs);
6221   }
6222   // FIXME: This means that pretty-printing the final AST will produce curly
6223   // braces instead of the original commas.
6224   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6225                                                    initExprs, LiteralRParenLoc);
6226   initE->setType(Ty);
6227   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6228 }
6229 
6230 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6231 /// the ParenListExpr into a sequence of comma binary operators.
6232 ExprResult
6233 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6234   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6235   if (!E)
6236     return OrigExpr;
6237 
6238   ExprResult Result(E->getExpr(0));
6239 
6240   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6241     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6242                         E->getExpr(i));
6243 
6244   if (Result.isInvalid()) return ExprError();
6245 
6246   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6247 }
6248 
6249 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6250                                     SourceLocation R,
6251                                     MultiExprArg Val) {
6252   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6253   return expr;
6254 }
6255 
6256 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6257 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6258 /// emitted.
6259 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6260                                       SourceLocation QuestionLoc) {
6261   Expr *NullExpr = LHSExpr;
6262   Expr *NonPointerExpr = RHSExpr;
6263   Expr::NullPointerConstantKind NullKind =
6264       NullExpr->isNullPointerConstant(Context,
6265                                       Expr::NPC_ValueDependentIsNotNull);
6266 
6267   if (NullKind == Expr::NPCK_NotNull) {
6268     NullExpr = RHSExpr;
6269     NonPointerExpr = LHSExpr;
6270     NullKind =
6271         NullExpr->isNullPointerConstant(Context,
6272                                         Expr::NPC_ValueDependentIsNotNull);
6273   }
6274 
6275   if (NullKind == Expr::NPCK_NotNull)
6276     return false;
6277 
6278   if (NullKind == Expr::NPCK_ZeroExpression)
6279     return false;
6280 
6281   if (NullKind == Expr::NPCK_ZeroLiteral) {
6282     // In this case, check to make sure that we got here from a "NULL"
6283     // string in the source code.
6284     NullExpr = NullExpr->IgnoreParenImpCasts();
6285     SourceLocation loc = NullExpr->getExprLoc();
6286     if (!findMacroSpelling(loc, "NULL"))
6287       return false;
6288   }
6289 
6290   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6291   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6292       << NonPointerExpr->getType() << DiagType
6293       << NonPointerExpr->getSourceRange();
6294   return true;
6295 }
6296 
6297 /// \brief Return false if the condition expression is valid, true otherwise.
6298 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6299   QualType CondTy = Cond->getType();
6300 
6301   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6302   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6303     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6304       << CondTy << Cond->getSourceRange();
6305     return true;
6306   }
6307 
6308   // C99 6.5.15p2
6309   if (CondTy->isScalarType()) return false;
6310 
6311   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6312     << CondTy << Cond->getSourceRange();
6313   return true;
6314 }
6315 
6316 /// \brief Handle when one or both operands are void type.
6317 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6318                                          ExprResult &RHS) {
6319     Expr *LHSExpr = LHS.get();
6320     Expr *RHSExpr = RHS.get();
6321 
6322     if (!LHSExpr->getType()->isVoidType())
6323       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6324         << RHSExpr->getSourceRange();
6325     if (!RHSExpr->getType()->isVoidType())
6326       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6327         << LHSExpr->getSourceRange();
6328     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6329     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6330     return S.Context.VoidTy;
6331 }
6332 
6333 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6334 /// true otherwise.
6335 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6336                                         QualType PointerTy) {
6337   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6338       !NullExpr.get()->isNullPointerConstant(S.Context,
6339                                             Expr::NPC_ValueDependentIsNull))
6340     return true;
6341 
6342   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6343   return false;
6344 }
6345 
6346 /// \brief Checks compatibility between two pointers and return the resulting
6347 /// type.
6348 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6349                                                      ExprResult &RHS,
6350                                                      SourceLocation Loc) {
6351   QualType LHSTy = LHS.get()->getType();
6352   QualType RHSTy = RHS.get()->getType();
6353 
6354   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6355     // Two identical pointers types are always compatible.
6356     return LHSTy;
6357   }
6358 
6359   QualType lhptee, rhptee;
6360 
6361   // Get the pointee types.
6362   bool IsBlockPointer = false;
6363   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6364     lhptee = LHSBTy->getPointeeType();
6365     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6366     IsBlockPointer = true;
6367   } else {
6368     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6369     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6370   }
6371 
6372   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6373   // differently qualified versions of compatible types, the result type is
6374   // a pointer to an appropriately qualified version of the composite
6375   // type.
6376 
6377   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6378   // clause doesn't make sense for our extensions. E.g. address space 2 should
6379   // be incompatible with address space 3: they may live on different devices or
6380   // anything.
6381   Qualifiers lhQual = lhptee.getQualifiers();
6382   Qualifiers rhQual = rhptee.getQualifiers();
6383 
6384   LangAS ResultAddrSpace = LangAS::Default;
6385   LangAS LAddrSpace = lhQual.getAddressSpace();
6386   LangAS RAddrSpace = rhQual.getAddressSpace();
6387   if (S.getLangOpts().OpenCL) {
6388     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6389     // spaces is disallowed.
6390     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6391       ResultAddrSpace = LAddrSpace;
6392     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6393       ResultAddrSpace = RAddrSpace;
6394     else {
6395       S.Diag(Loc,
6396              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6397           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6398           << RHS.get()->getSourceRange();
6399       return QualType();
6400     }
6401   }
6402 
6403   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6404   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6405   lhQual.removeCVRQualifiers();
6406   rhQual.removeCVRQualifiers();
6407 
6408   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6409   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6410   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6411   // qual types are compatible iff
6412   //  * corresponded types are compatible
6413   //  * CVR qualifiers are equal
6414   //  * address spaces are equal
6415   // Thus for conditional operator we merge CVR and address space unqualified
6416   // pointees and if there is a composite type we return a pointer to it with
6417   // merged qualifiers.
6418   if (S.getLangOpts().OpenCL) {
6419     LHSCastKind = LAddrSpace == ResultAddrSpace
6420                       ? CK_BitCast
6421                       : CK_AddressSpaceConversion;
6422     RHSCastKind = RAddrSpace == ResultAddrSpace
6423                       ? CK_BitCast
6424                       : CK_AddressSpaceConversion;
6425     lhQual.removeAddressSpace();
6426     rhQual.removeAddressSpace();
6427   }
6428 
6429   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6430   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6431 
6432   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6433 
6434   if (CompositeTy.isNull()) {
6435     // In this situation, we assume void* type. No especially good
6436     // reason, but this is what gcc does, and we do have to pick
6437     // to get a consistent AST.
6438     QualType incompatTy;
6439     incompatTy = S.Context.getPointerType(
6440         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6441     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6442     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6443     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6444     // for casts between types with incompatible address space qualifiers.
6445     // For the following code the compiler produces casts between global and
6446     // local address spaces of the corresponded innermost pointees:
6447     // local int *global *a;
6448     // global int *global *b;
6449     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6450     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6451         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6452         << RHS.get()->getSourceRange();
6453     return incompatTy;
6454   }
6455 
6456   // The pointer types are compatible.
6457   // In case of OpenCL ResultTy should have the address space qualifier
6458   // which is a superset of address spaces of both the 2nd and the 3rd
6459   // operands of the conditional operator.
6460   QualType ResultTy = [&, ResultAddrSpace]() {
6461     if (S.getLangOpts().OpenCL) {
6462       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6463       CompositeQuals.setAddressSpace(ResultAddrSpace);
6464       return S.Context
6465           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6466           .withCVRQualifiers(MergedCVRQual);
6467     }
6468     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6469   }();
6470   if (IsBlockPointer)
6471     ResultTy = S.Context.getBlockPointerType(ResultTy);
6472   else
6473     ResultTy = S.Context.getPointerType(ResultTy);
6474 
6475   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6476   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6477   return ResultTy;
6478 }
6479 
6480 /// \brief Return the resulting type when the operands are both block pointers.
6481 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6482                                                           ExprResult &LHS,
6483                                                           ExprResult &RHS,
6484                                                           SourceLocation Loc) {
6485   QualType LHSTy = LHS.get()->getType();
6486   QualType RHSTy = RHS.get()->getType();
6487 
6488   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6489     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6490       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6491       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6492       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6493       return destType;
6494     }
6495     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6496       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6497       << RHS.get()->getSourceRange();
6498     return QualType();
6499   }
6500 
6501   // We have 2 block pointer types.
6502   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6503 }
6504 
6505 /// \brief Return the resulting type when the operands are both pointers.
6506 static QualType
6507 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6508                                             ExprResult &RHS,
6509                                             SourceLocation Loc) {
6510   // get the pointer types
6511   QualType LHSTy = LHS.get()->getType();
6512   QualType RHSTy = RHS.get()->getType();
6513 
6514   // get the "pointed to" types
6515   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6516   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6517 
6518   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6519   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6520     // Figure out necessary qualifiers (C99 6.5.15p6)
6521     QualType destPointee
6522       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6523     QualType destType = S.Context.getPointerType(destPointee);
6524     // Add qualifiers if necessary.
6525     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6526     // Promote to void*.
6527     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6528     return destType;
6529   }
6530   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6531     QualType destPointee
6532       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6533     QualType destType = S.Context.getPointerType(destPointee);
6534     // Add qualifiers if necessary.
6535     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6536     // Promote to void*.
6537     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6538     return destType;
6539   }
6540 
6541   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6542 }
6543 
6544 /// \brief Return false if the first expression is not an integer and the second
6545 /// expression is not a pointer, true otherwise.
6546 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6547                                         Expr* PointerExpr, SourceLocation Loc,
6548                                         bool IsIntFirstExpr) {
6549   if (!PointerExpr->getType()->isPointerType() ||
6550       !Int.get()->getType()->isIntegerType())
6551     return false;
6552 
6553   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6554   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6555 
6556   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6557     << Expr1->getType() << Expr2->getType()
6558     << Expr1->getSourceRange() << Expr2->getSourceRange();
6559   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6560                             CK_IntegralToPointer);
6561   return true;
6562 }
6563 
6564 /// \brief Simple conversion between integer and floating point types.
6565 ///
6566 /// Used when handling the OpenCL conditional operator where the
6567 /// condition is a vector while the other operands are scalar.
6568 ///
6569 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6570 /// types are either integer or floating type. Between the two
6571 /// operands, the type with the higher rank is defined as the "result
6572 /// type". The other operand needs to be promoted to the same type. No
6573 /// other type promotion is allowed. We cannot use
6574 /// UsualArithmeticConversions() for this purpose, since it always
6575 /// promotes promotable types.
6576 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6577                                             ExprResult &RHS,
6578                                             SourceLocation QuestionLoc) {
6579   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6580   if (LHS.isInvalid())
6581     return QualType();
6582   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6583   if (RHS.isInvalid())
6584     return QualType();
6585 
6586   // For conversion purposes, we ignore any qualifiers.
6587   // For example, "const float" and "float" are equivalent.
6588   QualType LHSType =
6589     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6590   QualType RHSType =
6591     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6592 
6593   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6594     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6595       << LHSType << LHS.get()->getSourceRange();
6596     return QualType();
6597   }
6598 
6599   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6600     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6601       << RHSType << RHS.get()->getSourceRange();
6602     return QualType();
6603   }
6604 
6605   // If both types are identical, no conversion is needed.
6606   if (LHSType == RHSType)
6607     return LHSType;
6608 
6609   // Now handle "real" floating types (i.e. float, double, long double).
6610   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6611     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6612                                  /*IsCompAssign = */ false);
6613 
6614   // Finally, we have two differing integer types.
6615   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6616   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6617 }
6618 
6619 /// \brief Convert scalar operands to a vector that matches the
6620 ///        condition in length.
6621 ///
6622 /// Used when handling the OpenCL conditional operator where the
6623 /// condition is a vector while the other operands are scalar.
6624 ///
6625 /// We first compute the "result type" for the scalar operands
6626 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6627 /// into a vector of that type where the length matches the condition
6628 /// vector type. s6.11.6 requires that the element types of the result
6629 /// and the condition must have the same number of bits.
6630 static QualType
6631 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6632                               QualType CondTy, SourceLocation QuestionLoc) {
6633   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6634   if (ResTy.isNull()) return QualType();
6635 
6636   const VectorType *CV = CondTy->getAs<VectorType>();
6637   assert(CV);
6638 
6639   // Determine the vector result type
6640   unsigned NumElements = CV->getNumElements();
6641   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6642 
6643   // Ensure that all types have the same number of bits
6644   if (S.Context.getTypeSize(CV->getElementType())
6645       != S.Context.getTypeSize(ResTy)) {
6646     // Since VectorTy is created internally, it does not pretty print
6647     // with an OpenCL name. Instead, we just print a description.
6648     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6649     SmallString<64> Str;
6650     llvm::raw_svector_ostream OS(Str);
6651     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6652     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6653       << CondTy << OS.str();
6654     return QualType();
6655   }
6656 
6657   // Convert operands to the vector result type
6658   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6659   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6660 
6661   return VectorTy;
6662 }
6663 
6664 /// \brief Return false if this is a valid OpenCL condition vector
6665 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6666                                        SourceLocation QuestionLoc) {
6667   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6668   // integral type.
6669   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6670   assert(CondTy);
6671   QualType EleTy = CondTy->getElementType();
6672   if (EleTy->isIntegerType()) return false;
6673 
6674   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6675     << Cond->getType() << Cond->getSourceRange();
6676   return true;
6677 }
6678 
6679 /// \brief Return false if the vector condition type and the vector
6680 ///        result type are compatible.
6681 ///
6682 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6683 /// number of elements, and their element types have the same number
6684 /// of bits.
6685 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6686                               SourceLocation QuestionLoc) {
6687   const VectorType *CV = CondTy->getAs<VectorType>();
6688   const VectorType *RV = VecResTy->getAs<VectorType>();
6689   assert(CV && RV);
6690 
6691   if (CV->getNumElements() != RV->getNumElements()) {
6692     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6693       << CondTy << VecResTy;
6694     return true;
6695   }
6696 
6697   QualType CVE = CV->getElementType();
6698   QualType RVE = RV->getElementType();
6699 
6700   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6701     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6702       << CondTy << VecResTy;
6703     return true;
6704   }
6705 
6706   return false;
6707 }
6708 
6709 /// \brief Return the resulting type for the conditional operator in
6710 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6711 ///        s6.3.i) when the condition is a vector type.
6712 static QualType
6713 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6714                              ExprResult &LHS, ExprResult &RHS,
6715                              SourceLocation QuestionLoc) {
6716   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6717   if (Cond.isInvalid())
6718     return QualType();
6719   QualType CondTy = Cond.get()->getType();
6720 
6721   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6722     return QualType();
6723 
6724   // If either operand is a vector then find the vector type of the
6725   // result as specified in OpenCL v1.1 s6.3.i.
6726   if (LHS.get()->getType()->isVectorType() ||
6727       RHS.get()->getType()->isVectorType()) {
6728     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6729                                               /*isCompAssign*/false,
6730                                               /*AllowBothBool*/true,
6731                                               /*AllowBoolConversions*/false);
6732     if (VecResTy.isNull()) return QualType();
6733     // The result type must match the condition type as specified in
6734     // OpenCL v1.1 s6.11.6.
6735     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6736       return QualType();
6737     return VecResTy;
6738   }
6739 
6740   // Both operands are scalar.
6741   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6742 }
6743 
6744 /// \brief Return true if the Expr is block type
6745 static bool checkBlockType(Sema &S, const Expr *E) {
6746   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6747     QualType Ty = CE->getCallee()->getType();
6748     if (Ty->isBlockPointerType()) {
6749       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6750       return true;
6751     }
6752   }
6753   return false;
6754 }
6755 
6756 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6757 /// In that case, LHS = cond.
6758 /// C99 6.5.15
6759 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6760                                         ExprResult &RHS, ExprValueKind &VK,
6761                                         ExprObjectKind &OK,
6762                                         SourceLocation QuestionLoc) {
6763 
6764   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6765   if (!LHSResult.isUsable()) return QualType();
6766   LHS = LHSResult;
6767 
6768   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6769   if (!RHSResult.isUsable()) return QualType();
6770   RHS = RHSResult;
6771 
6772   // C++ is sufficiently different to merit its own checker.
6773   if (getLangOpts().CPlusPlus)
6774     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6775 
6776   VK = VK_RValue;
6777   OK = OK_Ordinary;
6778 
6779   // The OpenCL operator with a vector condition is sufficiently
6780   // different to merit its own checker.
6781   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6782     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6783 
6784   // First, check the condition.
6785   Cond = UsualUnaryConversions(Cond.get());
6786   if (Cond.isInvalid())
6787     return QualType();
6788   if (checkCondition(*this, Cond.get(), QuestionLoc))
6789     return QualType();
6790 
6791   // Now check the two expressions.
6792   if (LHS.get()->getType()->isVectorType() ||
6793       RHS.get()->getType()->isVectorType())
6794     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6795                                /*AllowBothBool*/true,
6796                                /*AllowBoolConversions*/false);
6797 
6798   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6799   if (LHS.isInvalid() || RHS.isInvalid())
6800     return QualType();
6801 
6802   QualType LHSTy = LHS.get()->getType();
6803   QualType RHSTy = RHS.get()->getType();
6804 
6805   // Diagnose attempts to convert between __float128 and long double where
6806   // such conversions currently can't be handled.
6807   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6808     Diag(QuestionLoc,
6809          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6810       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6811     return QualType();
6812   }
6813 
6814   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6815   // selection operator (?:).
6816   if (getLangOpts().OpenCL &&
6817       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6818     return QualType();
6819   }
6820 
6821   // If both operands have arithmetic type, do the usual arithmetic conversions
6822   // to find a common type: C99 6.5.15p3,5.
6823   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6824     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6825     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6826 
6827     return ResTy;
6828   }
6829 
6830   // If both operands are the same structure or union type, the result is that
6831   // type.
6832   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6833     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6834       if (LHSRT->getDecl() == RHSRT->getDecl())
6835         // "If both the operands have structure or union type, the result has
6836         // that type."  This implies that CV qualifiers are dropped.
6837         return LHSTy.getUnqualifiedType();
6838     // FIXME: Type of conditional expression must be complete in C mode.
6839   }
6840 
6841   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6842   // The following || allows only one side to be void (a GCC-ism).
6843   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6844     return checkConditionalVoidType(*this, LHS, RHS);
6845   }
6846 
6847   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6848   // the type of the other operand."
6849   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6850   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6851 
6852   // All objective-c pointer type analysis is done here.
6853   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6854                                                         QuestionLoc);
6855   if (LHS.isInvalid() || RHS.isInvalid())
6856     return QualType();
6857   if (!compositeType.isNull())
6858     return compositeType;
6859 
6860 
6861   // Handle block pointer types.
6862   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6863     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6864                                                      QuestionLoc);
6865 
6866   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6867   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6868     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6869                                                        QuestionLoc);
6870 
6871   // GCC compatibility: soften pointer/integer mismatch.  Note that
6872   // null pointers have been filtered out by this point.
6873   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6874       /*isIntFirstExpr=*/true))
6875     return RHSTy;
6876   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6877       /*isIntFirstExpr=*/false))
6878     return LHSTy;
6879 
6880   // Emit a better diagnostic if one of the expressions is a null pointer
6881   // constant and the other is not a pointer type. In this case, the user most
6882   // likely forgot to take the address of the other expression.
6883   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6884     return QualType();
6885 
6886   // Otherwise, the operands are not compatible.
6887   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6888     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6889     << RHS.get()->getSourceRange();
6890   return QualType();
6891 }
6892 
6893 /// FindCompositeObjCPointerType - Helper method to find composite type of
6894 /// two objective-c pointer types of the two input expressions.
6895 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6896                                             SourceLocation QuestionLoc) {
6897   QualType LHSTy = LHS.get()->getType();
6898   QualType RHSTy = RHS.get()->getType();
6899 
6900   // Handle things like Class and struct objc_class*.  Here we case the result
6901   // to the pseudo-builtin, because that will be implicitly cast back to the
6902   // redefinition type if an attempt is made to access its fields.
6903   if (LHSTy->isObjCClassType() &&
6904       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6905     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6906     return LHSTy;
6907   }
6908   if (RHSTy->isObjCClassType() &&
6909       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6910     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6911     return RHSTy;
6912   }
6913   // And the same for struct objc_object* / id
6914   if (LHSTy->isObjCIdType() &&
6915       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6916     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6917     return LHSTy;
6918   }
6919   if (RHSTy->isObjCIdType() &&
6920       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6921     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6922     return RHSTy;
6923   }
6924   // And the same for struct objc_selector* / SEL
6925   if (Context.isObjCSelType(LHSTy) &&
6926       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6927     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6928     return LHSTy;
6929   }
6930   if (Context.isObjCSelType(RHSTy) &&
6931       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6932     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6933     return RHSTy;
6934   }
6935   // Check constraints for Objective-C object pointers types.
6936   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6937 
6938     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6939       // Two identical object pointer types are always compatible.
6940       return LHSTy;
6941     }
6942     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6943     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6944     QualType compositeType = LHSTy;
6945 
6946     // If both operands are interfaces and either operand can be
6947     // assigned to the other, use that type as the composite
6948     // type. This allows
6949     //   xxx ? (A*) a : (B*) b
6950     // where B is a subclass of A.
6951     //
6952     // Additionally, as for assignment, if either type is 'id'
6953     // allow silent coercion. Finally, if the types are
6954     // incompatible then make sure to use 'id' as the composite
6955     // type so the result is acceptable for sending messages to.
6956 
6957     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6958     // It could return the composite type.
6959     if (!(compositeType =
6960           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6961       // Nothing more to do.
6962     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6963       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6964     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6965       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6966     } else if ((LHSTy->isObjCQualifiedIdType() ||
6967                 RHSTy->isObjCQualifiedIdType()) &&
6968                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6969       // Need to handle "id<xx>" explicitly.
6970       // GCC allows qualified id and any Objective-C type to devolve to
6971       // id. Currently localizing to here until clear this should be
6972       // part of ObjCQualifiedIdTypesAreCompatible.
6973       compositeType = Context.getObjCIdType();
6974     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6975       compositeType = Context.getObjCIdType();
6976     } else {
6977       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6978       << LHSTy << RHSTy
6979       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6980       QualType incompatTy = Context.getObjCIdType();
6981       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6982       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6983       return incompatTy;
6984     }
6985     // The object pointer types are compatible.
6986     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6987     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6988     return compositeType;
6989   }
6990   // Check Objective-C object pointer types and 'void *'
6991   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6992     if (getLangOpts().ObjCAutoRefCount) {
6993       // ARC forbids the implicit conversion of object pointers to 'void *',
6994       // so these types are not compatible.
6995       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6996           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6997       LHS = RHS = true;
6998       return QualType();
6999     }
7000     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7001     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7002     QualType destPointee
7003     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7004     QualType destType = Context.getPointerType(destPointee);
7005     // Add qualifiers if necessary.
7006     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7007     // Promote to void*.
7008     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7009     return destType;
7010   }
7011   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7012     if (getLangOpts().ObjCAutoRefCount) {
7013       // ARC forbids the implicit conversion of object pointers to 'void *',
7014       // so these types are not compatible.
7015       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7016           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7017       LHS = RHS = true;
7018       return QualType();
7019     }
7020     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7021     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7022     QualType destPointee
7023     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7024     QualType destType = Context.getPointerType(destPointee);
7025     // Add qualifiers if necessary.
7026     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7027     // Promote to void*.
7028     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7029     return destType;
7030   }
7031   return QualType();
7032 }
7033 
7034 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7035 /// ParenRange in parentheses.
7036 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7037                                const PartialDiagnostic &Note,
7038                                SourceRange ParenRange) {
7039   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7040   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7041       EndLoc.isValid()) {
7042     Self.Diag(Loc, Note)
7043       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7044       << FixItHint::CreateInsertion(EndLoc, ")");
7045   } else {
7046     // We can't display the parentheses, so just show the bare note.
7047     Self.Diag(Loc, Note) << ParenRange;
7048   }
7049 }
7050 
7051 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7052   return BinaryOperator::isAdditiveOp(Opc) ||
7053          BinaryOperator::isMultiplicativeOp(Opc) ||
7054          BinaryOperator::isShiftOp(Opc);
7055 }
7056 
7057 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7058 /// expression, either using a built-in or overloaded operator,
7059 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7060 /// expression.
7061 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7062                                    Expr **RHSExprs) {
7063   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7064   E = E->IgnoreImpCasts();
7065   E = E->IgnoreConversionOperator();
7066   E = E->IgnoreImpCasts();
7067 
7068   // Built-in binary operator.
7069   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7070     if (IsArithmeticOp(OP->getOpcode())) {
7071       *Opcode = OP->getOpcode();
7072       *RHSExprs = OP->getRHS();
7073       return true;
7074     }
7075   }
7076 
7077   // Overloaded operator.
7078   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7079     if (Call->getNumArgs() != 2)
7080       return false;
7081 
7082     // Make sure this is really a binary operator that is safe to pass into
7083     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7084     OverloadedOperatorKind OO = Call->getOperator();
7085     if (OO < OO_Plus || OO > OO_Arrow ||
7086         OO == OO_PlusPlus || OO == OO_MinusMinus)
7087       return false;
7088 
7089     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7090     if (IsArithmeticOp(OpKind)) {
7091       *Opcode = OpKind;
7092       *RHSExprs = Call->getArg(1);
7093       return true;
7094     }
7095   }
7096 
7097   return false;
7098 }
7099 
7100 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7101 /// or is a logical expression such as (x==y) which has int type, but is
7102 /// commonly interpreted as boolean.
7103 static bool ExprLooksBoolean(Expr *E) {
7104   E = E->IgnoreParenImpCasts();
7105 
7106   if (E->getType()->isBooleanType())
7107     return true;
7108   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7109     return OP->isComparisonOp() || OP->isLogicalOp();
7110   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7111     return OP->getOpcode() == UO_LNot;
7112   if (E->getType()->isPointerType())
7113     return true;
7114 
7115   return false;
7116 }
7117 
7118 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7119 /// and binary operator are mixed in a way that suggests the programmer assumed
7120 /// the conditional operator has higher precedence, for example:
7121 /// "int x = a + someBinaryCondition ? 1 : 2".
7122 static void DiagnoseConditionalPrecedence(Sema &Self,
7123                                           SourceLocation OpLoc,
7124                                           Expr *Condition,
7125                                           Expr *LHSExpr,
7126                                           Expr *RHSExpr) {
7127   BinaryOperatorKind CondOpcode;
7128   Expr *CondRHS;
7129 
7130   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7131     return;
7132   if (!ExprLooksBoolean(CondRHS))
7133     return;
7134 
7135   // The condition is an arithmetic binary expression, with a right-
7136   // hand side that looks boolean, so warn.
7137 
7138   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7139       << Condition->getSourceRange()
7140       << BinaryOperator::getOpcodeStr(CondOpcode);
7141 
7142   SuggestParentheses(Self, OpLoc,
7143     Self.PDiag(diag::note_precedence_silence)
7144       << BinaryOperator::getOpcodeStr(CondOpcode),
7145     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7146 
7147   SuggestParentheses(Self, OpLoc,
7148     Self.PDiag(diag::note_precedence_conditional_first),
7149     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7150 }
7151 
7152 /// Compute the nullability of a conditional expression.
7153 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7154                                               QualType LHSTy, QualType RHSTy,
7155                                               ASTContext &Ctx) {
7156   if (!ResTy->isAnyPointerType())
7157     return ResTy;
7158 
7159   auto GetNullability = [&Ctx](QualType Ty) {
7160     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7161     if (Kind)
7162       return *Kind;
7163     return NullabilityKind::Unspecified;
7164   };
7165 
7166   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7167   NullabilityKind MergedKind;
7168 
7169   // Compute nullability of a binary conditional expression.
7170   if (IsBin) {
7171     if (LHSKind == NullabilityKind::NonNull)
7172       MergedKind = NullabilityKind::NonNull;
7173     else
7174       MergedKind = RHSKind;
7175   // Compute nullability of a normal conditional expression.
7176   } else {
7177     if (LHSKind == NullabilityKind::Nullable ||
7178         RHSKind == NullabilityKind::Nullable)
7179       MergedKind = NullabilityKind::Nullable;
7180     else if (LHSKind == NullabilityKind::NonNull)
7181       MergedKind = RHSKind;
7182     else if (RHSKind == NullabilityKind::NonNull)
7183       MergedKind = LHSKind;
7184     else
7185       MergedKind = NullabilityKind::Unspecified;
7186   }
7187 
7188   // Return if ResTy already has the correct nullability.
7189   if (GetNullability(ResTy) == MergedKind)
7190     return ResTy;
7191 
7192   // Strip all nullability from ResTy.
7193   while (ResTy->getNullability(Ctx))
7194     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7195 
7196   // Create a new AttributedType with the new nullability kind.
7197   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7198   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7199 }
7200 
7201 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7202 /// in the case of a the GNU conditional expr extension.
7203 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7204                                     SourceLocation ColonLoc,
7205                                     Expr *CondExpr, Expr *LHSExpr,
7206                                     Expr *RHSExpr) {
7207   if (!getLangOpts().CPlusPlus) {
7208     // C cannot handle TypoExpr nodes in the condition because it
7209     // doesn't handle dependent types properly, so make sure any TypoExprs have
7210     // been dealt with before checking the operands.
7211     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7212     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7213     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7214 
7215     if (!CondResult.isUsable())
7216       return ExprError();
7217 
7218     if (LHSExpr) {
7219       if (!LHSResult.isUsable())
7220         return ExprError();
7221     }
7222 
7223     if (!RHSResult.isUsable())
7224       return ExprError();
7225 
7226     CondExpr = CondResult.get();
7227     LHSExpr = LHSResult.get();
7228     RHSExpr = RHSResult.get();
7229   }
7230 
7231   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7232   // was the condition.
7233   OpaqueValueExpr *opaqueValue = nullptr;
7234   Expr *commonExpr = nullptr;
7235   if (!LHSExpr) {
7236     commonExpr = CondExpr;
7237     // Lower out placeholder types first.  This is important so that we don't
7238     // try to capture a placeholder. This happens in few cases in C++; such
7239     // as Objective-C++'s dictionary subscripting syntax.
7240     if (commonExpr->hasPlaceholderType()) {
7241       ExprResult result = CheckPlaceholderExpr(commonExpr);
7242       if (!result.isUsable()) return ExprError();
7243       commonExpr = result.get();
7244     }
7245     // We usually want to apply unary conversions *before* saving, except
7246     // in the special case of a C++ l-value conditional.
7247     if (!(getLangOpts().CPlusPlus
7248           && !commonExpr->isTypeDependent()
7249           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7250           && commonExpr->isGLValue()
7251           && commonExpr->isOrdinaryOrBitFieldObject()
7252           && RHSExpr->isOrdinaryOrBitFieldObject()
7253           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7254       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7255       if (commonRes.isInvalid())
7256         return ExprError();
7257       commonExpr = commonRes.get();
7258     }
7259 
7260     // If the common expression is a class or array prvalue, materialize it
7261     // so that we can safely refer to it multiple times.
7262     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7263                                    commonExpr->getType()->isArrayType())) {
7264       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7265       if (MatExpr.isInvalid())
7266         return ExprError();
7267       commonExpr = MatExpr.get();
7268     }
7269 
7270     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7271                                                 commonExpr->getType(),
7272                                                 commonExpr->getValueKind(),
7273                                                 commonExpr->getObjectKind(),
7274                                                 commonExpr);
7275     LHSExpr = CondExpr = opaqueValue;
7276   }
7277 
7278   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7279   ExprValueKind VK = VK_RValue;
7280   ExprObjectKind OK = OK_Ordinary;
7281   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7282   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7283                                              VK, OK, QuestionLoc);
7284   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7285       RHS.isInvalid())
7286     return ExprError();
7287 
7288   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7289                                 RHS.get());
7290 
7291   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7292 
7293   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7294                                          Context);
7295 
7296   if (!commonExpr)
7297     return new (Context)
7298         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7299                             RHS.get(), result, VK, OK);
7300 
7301   return new (Context) BinaryConditionalOperator(
7302       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7303       ColonLoc, result, VK, OK);
7304 }
7305 
7306 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7307 // being closely modeled after the C99 spec:-). The odd characteristic of this
7308 // routine is it effectively iqnores the qualifiers on the top level pointee.
7309 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7310 // FIXME: add a couple examples in this comment.
7311 static Sema::AssignConvertType
7312 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7313   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7314   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7315 
7316   // get the "pointed to" type (ignoring qualifiers at the top level)
7317   const Type *lhptee, *rhptee;
7318   Qualifiers lhq, rhq;
7319   std::tie(lhptee, lhq) =
7320       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7321   std::tie(rhptee, rhq) =
7322       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7323 
7324   Sema::AssignConvertType ConvTy = Sema::Compatible;
7325 
7326   // C99 6.5.16.1p1: This following citation is common to constraints
7327   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7328   // qualifiers of the type *pointed to* by the right;
7329 
7330   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7331   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7332       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7333     // Ignore lifetime for further calculation.
7334     lhq.removeObjCLifetime();
7335     rhq.removeObjCLifetime();
7336   }
7337 
7338   if (!lhq.compatiblyIncludes(rhq)) {
7339     // Treat address-space mismatches as fatal.  TODO: address subspaces
7340     if (!lhq.isAddressSpaceSupersetOf(rhq))
7341       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7342 
7343     // It's okay to add or remove GC or lifetime qualifiers when converting to
7344     // and from void*.
7345     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7346                         .compatiblyIncludes(
7347                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7348              && (lhptee->isVoidType() || rhptee->isVoidType()))
7349       ; // keep old
7350 
7351     // Treat lifetime mismatches as fatal.
7352     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7353       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7354 
7355     // For GCC/MS compatibility, other qualifier mismatches are treated
7356     // as still compatible in C.
7357     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7358   }
7359 
7360   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7361   // incomplete type and the other is a pointer to a qualified or unqualified
7362   // version of void...
7363   if (lhptee->isVoidType()) {
7364     if (rhptee->isIncompleteOrObjectType())
7365       return ConvTy;
7366 
7367     // As an extension, we allow cast to/from void* to function pointer.
7368     assert(rhptee->isFunctionType());
7369     return Sema::FunctionVoidPointer;
7370   }
7371 
7372   if (rhptee->isVoidType()) {
7373     if (lhptee->isIncompleteOrObjectType())
7374       return ConvTy;
7375 
7376     // As an extension, we allow cast to/from void* to function pointer.
7377     assert(lhptee->isFunctionType());
7378     return Sema::FunctionVoidPointer;
7379   }
7380 
7381   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7382   // unqualified versions of compatible types, ...
7383   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7384   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7385     // Check if the pointee types are compatible ignoring the sign.
7386     // We explicitly check for char so that we catch "char" vs
7387     // "unsigned char" on systems where "char" is unsigned.
7388     if (lhptee->isCharType())
7389       ltrans = S.Context.UnsignedCharTy;
7390     else if (lhptee->hasSignedIntegerRepresentation())
7391       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7392 
7393     if (rhptee->isCharType())
7394       rtrans = S.Context.UnsignedCharTy;
7395     else if (rhptee->hasSignedIntegerRepresentation())
7396       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7397 
7398     if (ltrans == rtrans) {
7399       // Types are compatible ignoring the sign. Qualifier incompatibility
7400       // takes priority over sign incompatibility because the sign
7401       // warning can be disabled.
7402       if (ConvTy != Sema::Compatible)
7403         return ConvTy;
7404 
7405       return Sema::IncompatiblePointerSign;
7406     }
7407 
7408     // If we are a multi-level pointer, it's possible that our issue is simply
7409     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7410     // the eventual target type is the same and the pointers have the same
7411     // level of indirection, this must be the issue.
7412     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7413       do {
7414         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7415         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7416       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7417 
7418       if (lhptee == rhptee)
7419         return Sema::IncompatibleNestedPointerQualifiers;
7420     }
7421 
7422     // General pointer incompatibility takes priority over qualifiers.
7423     return Sema::IncompatiblePointer;
7424   }
7425   if (!S.getLangOpts().CPlusPlus &&
7426       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7427     return Sema::IncompatiblePointer;
7428   return ConvTy;
7429 }
7430 
7431 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7432 /// block pointer types are compatible or whether a block and normal pointer
7433 /// are compatible. It is more restrict than comparing two function pointer
7434 // types.
7435 static Sema::AssignConvertType
7436 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7437                                     QualType RHSType) {
7438   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7439   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7440 
7441   QualType lhptee, rhptee;
7442 
7443   // get the "pointed to" type (ignoring qualifiers at the top level)
7444   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7445   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7446 
7447   // In C++, the types have to match exactly.
7448   if (S.getLangOpts().CPlusPlus)
7449     return Sema::IncompatibleBlockPointer;
7450 
7451   Sema::AssignConvertType ConvTy = Sema::Compatible;
7452 
7453   // For blocks we enforce that qualifiers are identical.
7454   Qualifiers LQuals = lhptee.getLocalQualifiers();
7455   Qualifiers RQuals = rhptee.getLocalQualifiers();
7456   if (S.getLangOpts().OpenCL) {
7457     LQuals.removeAddressSpace();
7458     RQuals.removeAddressSpace();
7459   }
7460   if (LQuals != RQuals)
7461     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7462 
7463   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7464   // assignment.
7465   // The current behavior is similar to C++ lambdas. A block might be
7466   // assigned to a variable iff its return type and parameters are compatible
7467   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7468   // an assignment. Presumably it should behave in way that a function pointer
7469   // assignment does in C, so for each parameter and return type:
7470   //  * CVR and address space of LHS should be a superset of CVR and address
7471   //  space of RHS.
7472   //  * unqualified types should be compatible.
7473   if (S.getLangOpts().OpenCL) {
7474     if (!S.Context.typesAreBlockPointerCompatible(
7475             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7476             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7477       return Sema::IncompatibleBlockPointer;
7478   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7479     return Sema::IncompatibleBlockPointer;
7480 
7481   return ConvTy;
7482 }
7483 
7484 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7485 /// for assignment compatibility.
7486 static Sema::AssignConvertType
7487 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7488                                    QualType RHSType) {
7489   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7490   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7491 
7492   if (LHSType->isObjCBuiltinType()) {
7493     // Class is not compatible with ObjC object pointers.
7494     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7495         !RHSType->isObjCQualifiedClassType())
7496       return Sema::IncompatiblePointer;
7497     return Sema::Compatible;
7498   }
7499   if (RHSType->isObjCBuiltinType()) {
7500     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7501         !LHSType->isObjCQualifiedClassType())
7502       return Sema::IncompatiblePointer;
7503     return Sema::Compatible;
7504   }
7505   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7506   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7507 
7508   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7509       // make an exception for id<P>
7510       !LHSType->isObjCQualifiedIdType())
7511     return Sema::CompatiblePointerDiscardsQualifiers;
7512 
7513   if (S.Context.typesAreCompatible(LHSType, RHSType))
7514     return Sema::Compatible;
7515   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7516     return Sema::IncompatibleObjCQualifiedId;
7517   return Sema::IncompatiblePointer;
7518 }
7519 
7520 Sema::AssignConvertType
7521 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7522                                  QualType LHSType, QualType RHSType) {
7523   // Fake up an opaque expression.  We don't actually care about what
7524   // cast operations are required, so if CheckAssignmentConstraints
7525   // adds casts to this they'll be wasted, but fortunately that doesn't
7526   // usually happen on valid code.
7527   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7528   ExprResult RHSPtr = &RHSExpr;
7529   CastKind K;
7530 
7531   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7532 }
7533 
7534 /// This helper function returns true if QT is a vector type that has element
7535 /// type ElementType.
7536 static bool isVector(QualType QT, QualType ElementType) {
7537   if (const VectorType *VT = QT->getAs<VectorType>())
7538     return VT->getElementType() == ElementType;
7539   return false;
7540 }
7541 
7542 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7543 /// has code to accommodate several GCC extensions when type checking
7544 /// pointers. Here are some objectionable examples that GCC considers warnings:
7545 ///
7546 ///  int a, *pint;
7547 ///  short *pshort;
7548 ///  struct foo *pfoo;
7549 ///
7550 ///  pint = pshort; // warning: assignment from incompatible pointer type
7551 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7552 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7553 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7554 ///
7555 /// As a result, the code for dealing with pointers is more complex than the
7556 /// C99 spec dictates.
7557 ///
7558 /// Sets 'Kind' for any result kind except Incompatible.
7559 Sema::AssignConvertType
7560 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7561                                  CastKind &Kind, bool ConvertRHS) {
7562   QualType RHSType = RHS.get()->getType();
7563   QualType OrigLHSType = LHSType;
7564 
7565   // Get canonical types.  We're not formatting these types, just comparing
7566   // them.
7567   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7568   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7569 
7570   // Common case: no conversion required.
7571   if (LHSType == RHSType) {
7572     Kind = CK_NoOp;
7573     return Compatible;
7574   }
7575 
7576   // If we have an atomic type, try a non-atomic assignment, then just add an
7577   // atomic qualification step.
7578   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7579     Sema::AssignConvertType result =
7580       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7581     if (result != Compatible)
7582       return result;
7583     if (Kind != CK_NoOp && ConvertRHS)
7584       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7585     Kind = CK_NonAtomicToAtomic;
7586     return Compatible;
7587   }
7588 
7589   // If the left-hand side is a reference type, then we are in a
7590   // (rare!) case where we've allowed the use of references in C,
7591   // e.g., as a parameter type in a built-in function. In this case,
7592   // just make sure that the type referenced is compatible with the
7593   // right-hand side type. The caller is responsible for adjusting
7594   // LHSType so that the resulting expression does not have reference
7595   // type.
7596   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7597     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7598       Kind = CK_LValueBitCast;
7599       return Compatible;
7600     }
7601     return Incompatible;
7602   }
7603 
7604   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7605   // to the same ExtVector type.
7606   if (LHSType->isExtVectorType()) {
7607     if (RHSType->isExtVectorType())
7608       return Incompatible;
7609     if (RHSType->isArithmeticType()) {
7610       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7611       if (ConvertRHS)
7612         RHS = prepareVectorSplat(LHSType, RHS.get());
7613       Kind = CK_VectorSplat;
7614       return Compatible;
7615     }
7616   }
7617 
7618   // Conversions to or from vector type.
7619   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7620     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7621       // Allow assignments of an AltiVec vector type to an equivalent GCC
7622       // vector type and vice versa
7623       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7624         Kind = CK_BitCast;
7625         return Compatible;
7626       }
7627 
7628       // If we are allowing lax vector conversions, and LHS and RHS are both
7629       // vectors, the total size only needs to be the same. This is a bitcast;
7630       // no bits are changed but the result type is different.
7631       if (isLaxVectorConversion(RHSType, LHSType)) {
7632         Kind = CK_BitCast;
7633         return IncompatibleVectors;
7634       }
7635     }
7636 
7637     // When the RHS comes from another lax conversion (e.g. binops between
7638     // scalars and vectors) the result is canonicalized as a vector. When the
7639     // LHS is also a vector, the lax is allowed by the condition above. Handle
7640     // the case where LHS is a scalar.
7641     if (LHSType->isScalarType()) {
7642       const VectorType *VecType = RHSType->getAs<VectorType>();
7643       if (VecType && VecType->getNumElements() == 1 &&
7644           isLaxVectorConversion(RHSType, LHSType)) {
7645         ExprResult *VecExpr = &RHS;
7646         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7647         Kind = CK_BitCast;
7648         return Compatible;
7649       }
7650     }
7651 
7652     return Incompatible;
7653   }
7654 
7655   // Diagnose attempts to convert between __float128 and long double where
7656   // such conversions currently can't be handled.
7657   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7658     return Incompatible;
7659 
7660   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7661   // discards the imaginary part.
7662   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7663       !LHSType->getAs<ComplexType>())
7664     return Incompatible;
7665 
7666   // Arithmetic conversions.
7667   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7668       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7669     if (ConvertRHS)
7670       Kind = PrepareScalarCast(RHS, LHSType);
7671     return Compatible;
7672   }
7673 
7674   // Conversions to normal pointers.
7675   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7676     // U* -> T*
7677     if (isa<PointerType>(RHSType)) {
7678       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7679       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7680       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7681       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7682     }
7683 
7684     // int -> T*
7685     if (RHSType->isIntegerType()) {
7686       Kind = CK_IntegralToPointer; // FIXME: null?
7687       return IntToPointer;
7688     }
7689 
7690     // C pointers are not compatible with ObjC object pointers,
7691     // with two exceptions:
7692     if (isa<ObjCObjectPointerType>(RHSType)) {
7693       //  - conversions to void*
7694       if (LHSPointer->getPointeeType()->isVoidType()) {
7695         Kind = CK_BitCast;
7696         return Compatible;
7697       }
7698 
7699       //  - conversions from 'Class' to the redefinition type
7700       if (RHSType->isObjCClassType() &&
7701           Context.hasSameType(LHSType,
7702                               Context.getObjCClassRedefinitionType())) {
7703         Kind = CK_BitCast;
7704         return Compatible;
7705       }
7706 
7707       Kind = CK_BitCast;
7708       return IncompatiblePointer;
7709     }
7710 
7711     // U^ -> void*
7712     if (RHSType->getAs<BlockPointerType>()) {
7713       if (LHSPointer->getPointeeType()->isVoidType()) {
7714         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7715         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7716                                 ->getPointeeType()
7717                                 .getAddressSpace();
7718         Kind =
7719             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7720         return Compatible;
7721       }
7722     }
7723 
7724     return Incompatible;
7725   }
7726 
7727   // Conversions to block pointers.
7728   if (isa<BlockPointerType>(LHSType)) {
7729     // U^ -> T^
7730     if (RHSType->isBlockPointerType()) {
7731       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7732                               ->getPointeeType()
7733                               .getAddressSpace();
7734       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7735                               ->getPointeeType()
7736                               .getAddressSpace();
7737       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7738       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7739     }
7740 
7741     // int or null -> T^
7742     if (RHSType->isIntegerType()) {
7743       Kind = CK_IntegralToPointer; // FIXME: null
7744       return IntToBlockPointer;
7745     }
7746 
7747     // id -> T^
7748     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7749       Kind = CK_AnyPointerToBlockPointerCast;
7750       return Compatible;
7751     }
7752 
7753     // void* -> T^
7754     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7755       if (RHSPT->getPointeeType()->isVoidType()) {
7756         Kind = CK_AnyPointerToBlockPointerCast;
7757         return Compatible;
7758       }
7759 
7760     return Incompatible;
7761   }
7762 
7763   // Conversions to Objective-C pointers.
7764   if (isa<ObjCObjectPointerType>(LHSType)) {
7765     // A* -> B*
7766     if (RHSType->isObjCObjectPointerType()) {
7767       Kind = CK_BitCast;
7768       Sema::AssignConvertType result =
7769         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7770       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7771           result == Compatible &&
7772           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7773         result = IncompatibleObjCWeakRef;
7774       return result;
7775     }
7776 
7777     // int or null -> A*
7778     if (RHSType->isIntegerType()) {
7779       Kind = CK_IntegralToPointer; // FIXME: null
7780       return IntToPointer;
7781     }
7782 
7783     // In general, C pointers are not compatible with ObjC object pointers,
7784     // with two exceptions:
7785     if (isa<PointerType>(RHSType)) {
7786       Kind = CK_CPointerToObjCPointerCast;
7787 
7788       //  - conversions from 'void*'
7789       if (RHSType->isVoidPointerType()) {
7790         return Compatible;
7791       }
7792 
7793       //  - conversions to 'Class' from its redefinition type
7794       if (LHSType->isObjCClassType() &&
7795           Context.hasSameType(RHSType,
7796                               Context.getObjCClassRedefinitionType())) {
7797         return Compatible;
7798       }
7799 
7800       return IncompatiblePointer;
7801     }
7802 
7803     // Only under strict condition T^ is compatible with an Objective-C pointer.
7804     if (RHSType->isBlockPointerType() &&
7805         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7806       if (ConvertRHS)
7807         maybeExtendBlockObject(RHS);
7808       Kind = CK_BlockPointerToObjCPointerCast;
7809       return Compatible;
7810     }
7811 
7812     return Incompatible;
7813   }
7814 
7815   // Conversions from pointers that are not covered by the above.
7816   if (isa<PointerType>(RHSType)) {
7817     // T* -> _Bool
7818     if (LHSType == Context.BoolTy) {
7819       Kind = CK_PointerToBoolean;
7820       return Compatible;
7821     }
7822 
7823     // T* -> int
7824     if (LHSType->isIntegerType()) {
7825       Kind = CK_PointerToIntegral;
7826       return PointerToInt;
7827     }
7828 
7829     return Incompatible;
7830   }
7831 
7832   // Conversions from Objective-C pointers that are not covered by the above.
7833   if (isa<ObjCObjectPointerType>(RHSType)) {
7834     // T* -> _Bool
7835     if (LHSType == Context.BoolTy) {
7836       Kind = CK_PointerToBoolean;
7837       return Compatible;
7838     }
7839 
7840     // T* -> int
7841     if (LHSType->isIntegerType()) {
7842       Kind = CK_PointerToIntegral;
7843       return PointerToInt;
7844     }
7845 
7846     return Incompatible;
7847   }
7848 
7849   // struct A -> struct B
7850   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7851     if (Context.typesAreCompatible(LHSType, RHSType)) {
7852       Kind = CK_NoOp;
7853       return Compatible;
7854     }
7855   }
7856 
7857   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7858     Kind = CK_IntToOCLSampler;
7859     return Compatible;
7860   }
7861 
7862   return Incompatible;
7863 }
7864 
7865 /// \brief Constructs a transparent union from an expression that is
7866 /// used to initialize the transparent union.
7867 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7868                                       ExprResult &EResult, QualType UnionType,
7869                                       FieldDecl *Field) {
7870   // Build an initializer list that designates the appropriate member
7871   // of the transparent union.
7872   Expr *E = EResult.get();
7873   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7874                                                    E, SourceLocation());
7875   Initializer->setType(UnionType);
7876   Initializer->setInitializedFieldInUnion(Field);
7877 
7878   // Build a compound literal constructing a value of the transparent
7879   // union type from this initializer list.
7880   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7881   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7882                                         VK_RValue, Initializer, false);
7883 }
7884 
7885 Sema::AssignConvertType
7886 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7887                                                ExprResult &RHS) {
7888   QualType RHSType = RHS.get()->getType();
7889 
7890   // If the ArgType is a Union type, we want to handle a potential
7891   // transparent_union GCC extension.
7892   const RecordType *UT = ArgType->getAsUnionType();
7893   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7894     return Incompatible;
7895 
7896   // The field to initialize within the transparent union.
7897   RecordDecl *UD = UT->getDecl();
7898   FieldDecl *InitField = nullptr;
7899   // It's compatible if the expression matches any of the fields.
7900   for (auto *it : UD->fields()) {
7901     if (it->getType()->isPointerType()) {
7902       // If the transparent union contains a pointer type, we allow:
7903       // 1) void pointer
7904       // 2) null pointer constant
7905       if (RHSType->isPointerType())
7906         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7907           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7908           InitField = it;
7909           break;
7910         }
7911 
7912       if (RHS.get()->isNullPointerConstant(Context,
7913                                            Expr::NPC_ValueDependentIsNull)) {
7914         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7915                                 CK_NullToPointer);
7916         InitField = it;
7917         break;
7918       }
7919     }
7920 
7921     CastKind Kind;
7922     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7923           == Compatible) {
7924       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7925       InitField = it;
7926       break;
7927     }
7928   }
7929 
7930   if (!InitField)
7931     return Incompatible;
7932 
7933   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7934   return Compatible;
7935 }
7936 
7937 Sema::AssignConvertType
7938 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7939                                        bool Diagnose,
7940                                        bool DiagnoseCFAudited,
7941                                        bool ConvertRHS) {
7942   // We need to be able to tell the caller whether we diagnosed a problem, if
7943   // they ask us to issue diagnostics.
7944   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7945 
7946   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7947   // we can't avoid *all* modifications at the moment, so we need some somewhere
7948   // to put the updated value.
7949   ExprResult LocalRHS = CallerRHS;
7950   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7951 
7952   if (getLangOpts().CPlusPlus) {
7953     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7954       // C++ 5.17p3: If the left operand is not of class type, the
7955       // expression is implicitly converted (C++ 4) to the
7956       // cv-unqualified type of the left operand.
7957       QualType RHSType = RHS.get()->getType();
7958       if (Diagnose) {
7959         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7960                                         AA_Assigning);
7961       } else {
7962         ImplicitConversionSequence ICS =
7963             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7964                                   /*SuppressUserConversions=*/false,
7965                                   /*AllowExplicit=*/false,
7966                                   /*InOverloadResolution=*/false,
7967                                   /*CStyle=*/false,
7968                                   /*AllowObjCWritebackConversion=*/false);
7969         if (ICS.isFailure())
7970           return Incompatible;
7971         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7972                                         ICS, AA_Assigning);
7973       }
7974       if (RHS.isInvalid())
7975         return Incompatible;
7976       Sema::AssignConvertType result = Compatible;
7977       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7978           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7979         result = IncompatibleObjCWeakRef;
7980       return result;
7981     }
7982 
7983     // FIXME: Currently, we fall through and treat C++ classes like C
7984     // structures.
7985     // FIXME: We also fall through for atomics; not sure what should
7986     // happen there, though.
7987   } else if (RHS.get()->getType() == Context.OverloadTy) {
7988     // As a set of extensions to C, we support overloading on functions. These
7989     // functions need to be resolved here.
7990     DeclAccessPair DAP;
7991     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7992             RHS.get(), LHSType, /*Complain=*/false, DAP))
7993       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7994     else
7995       return Incompatible;
7996   }
7997 
7998   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7999   // a null pointer constant.
8000   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8001        LHSType->isBlockPointerType()) &&
8002       RHS.get()->isNullPointerConstant(Context,
8003                                        Expr::NPC_ValueDependentIsNull)) {
8004     if (Diagnose || ConvertRHS) {
8005       CastKind Kind;
8006       CXXCastPath Path;
8007       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8008                              /*IgnoreBaseAccess=*/false, Diagnose);
8009       if (ConvertRHS)
8010         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8011     }
8012     return Compatible;
8013   }
8014 
8015   // This check seems unnatural, however it is necessary to ensure the proper
8016   // conversion of functions/arrays. If the conversion were done for all
8017   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8018   // expressions that suppress this implicit conversion (&, sizeof).
8019   //
8020   // Suppress this for references: C++ 8.5.3p5.
8021   if (!LHSType->isReferenceType()) {
8022     // FIXME: We potentially allocate here even if ConvertRHS is false.
8023     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8024     if (RHS.isInvalid())
8025       return Incompatible;
8026   }
8027 
8028   Expr *PRE = RHS.get()->IgnoreParenCasts();
8029   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8030     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8031     if (PDecl && !PDecl->hasDefinition()) {
8032       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
8033       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8034     }
8035   }
8036 
8037   CastKind Kind;
8038   Sema::AssignConvertType result =
8039     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8040 
8041   // C99 6.5.16.1p2: The value of the right operand is converted to the
8042   // type of the assignment expression.
8043   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8044   // so that we can use references in built-in functions even in C.
8045   // The getNonReferenceType() call makes sure that the resulting expression
8046   // does not have reference type.
8047   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8048     QualType Ty = LHSType.getNonLValueExprType(Context);
8049     Expr *E = RHS.get();
8050 
8051     // Check for various Objective-C errors. If we are not reporting
8052     // diagnostics and just checking for errors, e.g., during overload
8053     // resolution, return Incompatible to indicate the failure.
8054     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8055         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8056                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8057       if (!Diagnose)
8058         return Incompatible;
8059     }
8060     if (getLangOpts().ObjC1 &&
8061         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8062                                            E->getType(), E, Diagnose) ||
8063          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8064       if (!Diagnose)
8065         return Incompatible;
8066       // Replace the expression with a corrected version and continue so we
8067       // can find further errors.
8068       RHS = E;
8069       return Compatible;
8070     }
8071 
8072     if (ConvertRHS)
8073       RHS = ImpCastExprToType(E, Ty, Kind);
8074   }
8075   return result;
8076 }
8077 
8078 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8079                                ExprResult &RHS) {
8080   Diag(Loc, diag::err_typecheck_invalid_operands)
8081     << LHS.get()->getType() << RHS.get()->getType()
8082     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8083   return QualType();
8084 }
8085 
8086 // Diagnose cases where a scalar was implicitly converted to a vector and
8087 // diagnose the underlying types. Otherwise, diagnose the error
8088 // as invalid vector logical operands for non-C++ cases.
8089 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8090                                             ExprResult &RHS) {
8091   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8092   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8093 
8094   bool LHSNatVec = LHSType->isVectorType();
8095   bool RHSNatVec = RHSType->isVectorType();
8096 
8097   if (!(LHSNatVec && RHSNatVec)) {
8098     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8099     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8100     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8101         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8102         << Vector->getSourceRange();
8103     return QualType();
8104   }
8105 
8106   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8107       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8108       << RHS.get()->getSourceRange();
8109 
8110   return QualType();
8111 }
8112 
8113 /// Try to convert a value of non-vector type to a vector type by converting
8114 /// the type to the element type of the vector and then performing a splat.
8115 /// If the language is OpenCL, we only use conversions that promote scalar
8116 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8117 /// for float->int.
8118 ///
8119 /// OpenCL V2.0 6.2.6.p2:
8120 /// An error shall occur if any scalar operand type has greater rank
8121 /// than the type of the vector element.
8122 ///
8123 /// \param scalar - if non-null, actually perform the conversions
8124 /// \return true if the operation fails (but without diagnosing the failure)
8125 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8126                                      QualType scalarTy,
8127                                      QualType vectorEltTy,
8128                                      QualType vectorTy,
8129                                      unsigned &DiagID) {
8130   // The conversion to apply to the scalar before splatting it,
8131   // if necessary.
8132   CastKind scalarCast = CK_NoOp;
8133 
8134   if (vectorEltTy->isIntegralType(S.Context)) {
8135     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8136         (scalarTy->isIntegerType() &&
8137          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8138       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8139       return true;
8140     }
8141     if (!scalarTy->isIntegralType(S.Context))
8142       return true;
8143     scalarCast = CK_IntegralCast;
8144   } else if (vectorEltTy->isRealFloatingType()) {
8145     if (scalarTy->isRealFloatingType()) {
8146       if (S.getLangOpts().OpenCL &&
8147           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8148         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8149         return true;
8150       }
8151       scalarCast = CK_FloatingCast;
8152     }
8153     else if (scalarTy->isIntegralType(S.Context))
8154       scalarCast = CK_IntegralToFloating;
8155     else
8156       return true;
8157   } else {
8158     return true;
8159   }
8160 
8161   // Adjust scalar if desired.
8162   if (scalar) {
8163     if (scalarCast != CK_NoOp)
8164       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8165     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8166   }
8167   return false;
8168 }
8169 
8170 /// Convert vector E to a vector with the same number of elements but different
8171 /// element type.
8172 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8173   const auto *VecTy = E->getType()->getAs<VectorType>();
8174   assert(VecTy && "Expression E must be a vector");
8175   QualType NewVecTy = S.Context.getVectorType(ElementType,
8176                                               VecTy->getNumElements(),
8177                                               VecTy->getVectorKind());
8178 
8179   // Look through the implicit cast. Return the subexpression if its type is
8180   // NewVecTy.
8181   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8182     if (ICE->getSubExpr()->getType() == NewVecTy)
8183       return ICE->getSubExpr();
8184 
8185   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8186   return S.ImpCastExprToType(E, NewVecTy, Cast);
8187 }
8188 
8189 /// Test if a (constant) integer Int can be casted to another integer type
8190 /// IntTy without losing precision.
8191 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8192                                       QualType OtherIntTy) {
8193   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8194 
8195   // Reject cases where the value of the Int is unknown as that would
8196   // possibly cause truncation, but accept cases where the scalar can be
8197   // demoted without loss of precision.
8198   llvm::APSInt Result;
8199   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8200   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8201   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8202   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8203 
8204   if (CstInt) {
8205     // If the scalar is constant and is of a higher order and has more active
8206     // bits that the vector element type, reject it.
8207     unsigned NumBits = IntSigned
8208                            ? (Result.isNegative() ? Result.getMinSignedBits()
8209                                                   : Result.getActiveBits())
8210                            : Result.getActiveBits();
8211     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8212       return true;
8213 
8214     // If the signedness of the scalar type and the vector element type
8215     // differs and the number of bits is greater than that of the vector
8216     // element reject it.
8217     return (IntSigned != OtherIntSigned &&
8218             NumBits > S.Context.getIntWidth(OtherIntTy));
8219   }
8220 
8221   // Reject cases where the value of the scalar is not constant and it's
8222   // order is greater than that of the vector element type.
8223   return (Order < 0);
8224 }
8225 
8226 /// Test if a (constant) integer Int can be casted to floating point type
8227 /// FloatTy without losing precision.
8228 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8229                                      QualType FloatTy) {
8230   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8231 
8232   // Determine if the integer constant can be expressed as a floating point
8233   // number of the appropiate type.
8234   llvm::APSInt Result;
8235   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8236   uint64_t Bits = 0;
8237   if (CstInt) {
8238     // Reject constants that would be truncated if they were converted to
8239     // the floating point type. Test by simple to/from conversion.
8240     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8241     //        could be avoided if there was a convertFromAPInt method
8242     //        which could signal back if implicit truncation occurred.
8243     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8244     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8245                            llvm::APFloat::rmTowardZero);
8246     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8247                              !IntTy->hasSignedIntegerRepresentation());
8248     bool Ignored = false;
8249     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8250                            &Ignored);
8251     if (Result != ConvertBack)
8252       return true;
8253   } else {
8254     // Reject types that cannot be fully encoded into the mantissa of
8255     // the float.
8256     Bits = S.Context.getTypeSize(IntTy);
8257     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8258         S.Context.getFloatTypeSemantics(FloatTy));
8259     if (Bits > FloatPrec)
8260       return true;
8261   }
8262 
8263   return false;
8264 }
8265 
8266 /// Attempt to convert and splat Scalar into a vector whose types matches
8267 /// Vector following GCC conversion rules. The rule is that implicit
8268 /// conversion can occur when Scalar can be casted to match Vector's element
8269 /// type without causing truncation of Scalar.
8270 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8271                                         ExprResult *Vector) {
8272   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8273   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8274   const VectorType *VT = VectorTy->getAs<VectorType>();
8275 
8276   assert(!isa<ExtVectorType>(VT) &&
8277          "ExtVectorTypes should not be handled here!");
8278 
8279   QualType VectorEltTy = VT->getElementType();
8280 
8281   // Reject cases where the vector element type or the scalar element type are
8282   // not integral or floating point types.
8283   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8284     return true;
8285 
8286   // The conversion to apply to the scalar before splatting it,
8287   // if necessary.
8288   CastKind ScalarCast = CK_NoOp;
8289 
8290   // Accept cases where the vector elements are integers and the scalar is
8291   // an integer.
8292   // FIXME: Notionally if the scalar was a floating point value with a precise
8293   //        integral representation, we could cast it to an appropriate integer
8294   //        type and then perform the rest of the checks here. GCC will perform
8295   //        this conversion in some cases as determined by the input language.
8296   //        We should accept it on a language independent basis.
8297   if (VectorEltTy->isIntegralType(S.Context) &&
8298       ScalarTy->isIntegralType(S.Context) &&
8299       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8300 
8301     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8302       return true;
8303 
8304     ScalarCast = CK_IntegralCast;
8305   } else if (VectorEltTy->isRealFloatingType()) {
8306     if (ScalarTy->isRealFloatingType()) {
8307 
8308       // Reject cases where the scalar type is not a constant and has a higher
8309       // Order than the vector element type.
8310       llvm::APFloat Result(0.0);
8311       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8312       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8313       if (!CstScalar && Order < 0)
8314         return true;
8315 
8316       // If the scalar cannot be safely casted to the vector element type,
8317       // reject it.
8318       if (CstScalar) {
8319         bool Truncated = false;
8320         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8321                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8322         if (Truncated)
8323           return true;
8324       }
8325 
8326       ScalarCast = CK_FloatingCast;
8327     } else if (ScalarTy->isIntegralType(S.Context)) {
8328       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8329         return true;
8330 
8331       ScalarCast = CK_IntegralToFloating;
8332     } else
8333       return true;
8334   }
8335 
8336   // Adjust scalar if desired.
8337   if (Scalar) {
8338     if (ScalarCast != CK_NoOp)
8339       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8340     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8341   }
8342   return false;
8343 }
8344 
8345 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8346                                    SourceLocation Loc, bool IsCompAssign,
8347                                    bool AllowBothBool,
8348                                    bool AllowBoolConversions) {
8349   if (!IsCompAssign) {
8350     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8351     if (LHS.isInvalid())
8352       return QualType();
8353   }
8354   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8355   if (RHS.isInvalid())
8356     return QualType();
8357 
8358   // For conversion purposes, we ignore any qualifiers.
8359   // For example, "const float" and "float" are equivalent.
8360   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8361   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8362 
8363   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8364   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8365   assert(LHSVecType || RHSVecType);
8366 
8367   // AltiVec-style "vector bool op vector bool" combinations are allowed
8368   // for some operators but not others.
8369   if (!AllowBothBool &&
8370       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8371       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8372     return InvalidOperands(Loc, LHS, RHS);
8373 
8374   // If the vector types are identical, return.
8375   if (Context.hasSameType(LHSType, RHSType))
8376     return LHSType;
8377 
8378   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8379   if (LHSVecType && RHSVecType &&
8380       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8381     if (isa<ExtVectorType>(LHSVecType)) {
8382       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8383       return LHSType;
8384     }
8385 
8386     if (!IsCompAssign)
8387       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8388     return RHSType;
8389   }
8390 
8391   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8392   // can be mixed, with the result being the non-bool type.  The non-bool
8393   // operand must have integer element type.
8394   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8395       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8396       (Context.getTypeSize(LHSVecType->getElementType()) ==
8397        Context.getTypeSize(RHSVecType->getElementType()))) {
8398     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8399         LHSVecType->getElementType()->isIntegerType() &&
8400         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8401       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8402       return LHSType;
8403     }
8404     if (!IsCompAssign &&
8405         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8406         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8407         RHSVecType->getElementType()->isIntegerType()) {
8408       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8409       return RHSType;
8410     }
8411   }
8412 
8413   // If there's a vector type and a scalar, try to convert the scalar to
8414   // the vector element type and splat.
8415   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8416   if (!RHSVecType) {
8417     if (isa<ExtVectorType>(LHSVecType)) {
8418       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8419                                     LHSVecType->getElementType(), LHSType,
8420                                     DiagID))
8421         return LHSType;
8422     } else {
8423       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8424         return LHSType;
8425     }
8426   }
8427   if (!LHSVecType) {
8428     if (isa<ExtVectorType>(RHSVecType)) {
8429       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8430                                     LHSType, RHSVecType->getElementType(),
8431                                     RHSType, DiagID))
8432         return RHSType;
8433     } else {
8434       if (LHS.get()->getValueKind() == VK_LValue ||
8435           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8436         return RHSType;
8437     }
8438   }
8439 
8440   // FIXME: The code below also handles conversion between vectors and
8441   // non-scalars, we should break this down into fine grained specific checks
8442   // and emit proper diagnostics.
8443   QualType VecType = LHSVecType ? LHSType : RHSType;
8444   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8445   QualType OtherType = LHSVecType ? RHSType : LHSType;
8446   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8447   if (isLaxVectorConversion(OtherType, VecType)) {
8448     // If we're allowing lax vector conversions, only the total (data) size
8449     // needs to be the same. For non compound assignment, if one of the types is
8450     // scalar, the result is always the vector type.
8451     if (!IsCompAssign) {
8452       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8453       return VecType;
8454     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8455     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8456     // type. Note that this is already done by non-compound assignments in
8457     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8458     // <1 x T> -> T. The result is also a vector type.
8459     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8460                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8461       ExprResult *RHSExpr = &RHS;
8462       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8463       return VecType;
8464     }
8465   }
8466 
8467   // Okay, the expression is invalid.
8468 
8469   // If there's a non-vector, non-real operand, diagnose that.
8470   if ((!RHSVecType && !RHSType->isRealType()) ||
8471       (!LHSVecType && !LHSType->isRealType())) {
8472     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8473       << LHSType << RHSType
8474       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8475     return QualType();
8476   }
8477 
8478   // OpenCL V1.1 6.2.6.p1:
8479   // If the operands are of more than one vector type, then an error shall
8480   // occur. Implicit conversions between vector types are not permitted, per
8481   // section 6.2.1.
8482   if (getLangOpts().OpenCL &&
8483       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8484       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8485     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8486                                                            << RHSType;
8487     return QualType();
8488   }
8489 
8490 
8491   // If there is a vector type that is not a ExtVector and a scalar, we reach
8492   // this point if scalar could not be converted to the vector's element type
8493   // without truncation.
8494   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8495       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8496     QualType Scalar = LHSVecType ? RHSType : LHSType;
8497     QualType Vector = LHSVecType ? LHSType : RHSType;
8498     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8499     Diag(Loc,
8500          diag::err_typecheck_vector_not_convertable_implict_truncation)
8501         << ScalarOrVector << Scalar << Vector;
8502 
8503     return QualType();
8504   }
8505 
8506   // Otherwise, use the generic diagnostic.
8507   Diag(Loc, DiagID)
8508     << LHSType << RHSType
8509     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8510   return QualType();
8511 }
8512 
8513 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8514 // expression.  These are mainly cases where the null pointer is used as an
8515 // integer instead of a pointer.
8516 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8517                                 SourceLocation Loc, bool IsCompare) {
8518   // The canonical way to check for a GNU null is with isNullPointerConstant,
8519   // but we use a bit of a hack here for speed; this is a relatively
8520   // hot path, and isNullPointerConstant is slow.
8521   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8522   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8523 
8524   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8525 
8526   // Avoid analyzing cases where the result will either be invalid (and
8527   // diagnosed as such) or entirely valid and not something to warn about.
8528   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8529       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8530     return;
8531 
8532   // Comparison operations would not make sense with a null pointer no matter
8533   // what the other expression is.
8534   if (!IsCompare) {
8535     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8536         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8537         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8538     return;
8539   }
8540 
8541   // The rest of the operations only make sense with a null pointer
8542   // if the other expression is a pointer.
8543   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8544       NonNullType->canDecayToPointerType())
8545     return;
8546 
8547   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8548       << LHSNull /* LHS is NULL */ << NonNullType
8549       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8550 }
8551 
8552 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8553                                                ExprResult &RHS,
8554                                                SourceLocation Loc, bool IsDiv) {
8555   // Check for division/remainder by zero.
8556   llvm::APSInt RHSValue;
8557   if (!RHS.get()->isValueDependent() &&
8558       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8559     S.DiagRuntimeBehavior(Loc, RHS.get(),
8560                           S.PDiag(diag::warn_remainder_division_by_zero)
8561                             << IsDiv << RHS.get()->getSourceRange());
8562 }
8563 
8564 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8565                                            SourceLocation Loc,
8566                                            bool IsCompAssign, bool IsDiv) {
8567   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8568 
8569   if (LHS.get()->getType()->isVectorType() ||
8570       RHS.get()->getType()->isVectorType())
8571     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8572                                /*AllowBothBool*/getLangOpts().AltiVec,
8573                                /*AllowBoolConversions*/false);
8574 
8575   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8576   if (LHS.isInvalid() || RHS.isInvalid())
8577     return QualType();
8578 
8579 
8580   if (compType.isNull() || !compType->isArithmeticType())
8581     return InvalidOperands(Loc, LHS, RHS);
8582   if (IsDiv)
8583     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8584   return compType;
8585 }
8586 
8587 QualType Sema::CheckRemainderOperands(
8588   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8589   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8590 
8591   if (LHS.get()->getType()->isVectorType() ||
8592       RHS.get()->getType()->isVectorType()) {
8593     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8594         RHS.get()->getType()->hasIntegerRepresentation())
8595       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8596                                  /*AllowBothBool*/getLangOpts().AltiVec,
8597                                  /*AllowBoolConversions*/false);
8598     return InvalidOperands(Loc, LHS, RHS);
8599   }
8600 
8601   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8602   if (LHS.isInvalid() || RHS.isInvalid())
8603     return QualType();
8604 
8605   if (compType.isNull() || !compType->isIntegerType())
8606     return InvalidOperands(Loc, LHS, RHS);
8607   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8608   return compType;
8609 }
8610 
8611 /// \brief Diagnose invalid arithmetic on two void pointers.
8612 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8613                                                 Expr *LHSExpr, Expr *RHSExpr) {
8614   S.Diag(Loc, S.getLangOpts().CPlusPlus
8615                 ? diag::err_typecheck_pointer_arith_void_type
8616                 : diag::ext_gnu_void_ptr)
8617     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8618                             << RHSExpr->getSourceRange();
8619 }
8620 
8621 /// \brief Diagnose invalid arithmetic on a void pointer.
8622 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8623                                             Expr *Pointer) {
8624   S.Diag(Loc, S.getLangOpts().CPlusPlus
8625                 ? diag::err_typecheck_pointer_arith_void_type
8626                 : diag::ext_gnu_void_ptr)
8627     << 0 /* one pointer */ << Pointer->getSourceRange();
8628 }
8629 
8630 /// \brief Diagnose invalid arithmetic on a null pointer.
8631 ///
8632 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8633 /// idiom, which we recognize as a GNU extension.
8634 ///
8635 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8636                                             Expr *Pointer, bool IsGNUIdiom) {
8637   if (IsGNUIdiom)
8638     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8639       << Pointer->getSourceRange();
8640   else
8641     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8642       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8643 }
8644 
8645 /// \brief Diagnose invalid arithmetic on two function pointers.
8646 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8647                                                     Expr *LHS, Expr *RHS) {
8648   assert(LHS->getType()->isAnyPointerType());
8649   assert(RHS->getType()->isAnyPointerType());
8650   S.Diag(Loc, S.getLangOpts().CPlusPlus
8651                 ? diag::err_typecheck_pointer_arith_function_type
8652                 : diag::ext_gnu_ptr_func_arith)
8653     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8654     // We only show the second type if it differs from the first.
8655     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8656                                                    RHS->getType())
8657     << RHS->getType()->getPointeeType()
8658     << LHS->getSourceRange() << RHS->getSourceRange();
8659 }
8660 
8661 /// \brief Diagnose invalid arithmetic on a function pointer.
8662 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8663                                                 Expr *Pointer) {
8664   assert(Pointer->getType()->isAnyPointerType());
8665   S.Diag(Loc, S.getLangOpts().CPlusPlus
8666                 ? diag::err_typecheck_pointer_arith_function_type
8667                 : diag::ext_gnu_ptr_func_arith)
8668     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8669     << 0 /* one pointer, so only one type */
8670     << Pointer->getSourceRange();
8671 }
8672 
8673 /// \brief Emit error if Operand is incomplete pointer type
8674 ///
8675 /// \returns True if pointer has incomplete type
8676 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8677                                                  Expr *Operand) {
8678   QualType ResType = Operand->getType();
8679   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8680     ResType = ResAtomicType->getValueType();
8681 
8682   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8683   QualType PointeeTy = ResType->getPointeeType();
8684   return S.RequireCompleteType(Loc, PointeeTy,
8685                                diag::err_typecheck_arithmetic_incomplete_type,
8686                                PointeeTy, Operand->getSourceRange());
8687 }
8688 
8689 /// \brief Check the validity of an arithmetic pointer operand.
8690 ///
8691 /// If the operand has pointer type, this code will check for pointer types
8692 /// which are invalid in arithmetic operations. These will be diagnosed
8693 /// appropriately, including whether or not the use is supported as an
8694 /// extension.
8695 ///
8696 /// \returns True when the operand is valid to use (even if as an extension).
8697 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8698                                             Expr *Operand) {
8699   QualType ResType = Operand->getType();
8700   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8701     ResType = ResAtomicType->getValueType();
8702 
8703   if (!ResType->isAnyPointerType()) return true;
8704 
8705   QualType PointeeTy = ResType->getPointeeType();
8706   if (PointeeTy->isVoidType()) {
8707     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8708     return !S.getLangOpts().CPlusPlus;
8709   }
8710   if (PointeeTy->isFunctionType()) {
8711     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8712     return !S.getLangOpts().CPlusPlus;
8713   }
8714 
8715   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8716 
8717   return true;
8718 }
8719 
8720 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8721 /// operands.
8722 ///
8723 /// This routine will diagnose any invalid arithmetic on pointer operands much
8724 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8725 /// for emitting a single diagnostic even for operations where both LHS and RHS
8726 /// are (potentially problematic) pointers.
8727 ///
8728 /// \returns True when the operand is valid to use (even if as an extension).
8729 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8730                                                 Expr *LHSExpr, Expr *RHSExpr) {
8731   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8732   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8733   if (!isLHSPointer && !isRHSPointer) return true;
8734 
8735   QualType LHSPointeeTy, RHSPointeeTy;
8736   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8737   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8738 
8739   // if both are pointers check if operation is valid wrt address spaces
8740   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8741     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8742     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8743     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8744       S.Diag(Loc,
8745              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8746           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8747           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8748       return false;
8749     }
8750   }
8751 
8752   // Check for arithmetic on pointers to incomplete types.
8753   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8754   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8755   if (isLHSVoidPtr || isRHSVoidPtr) {
8756     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8757     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8758     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8759 
8760     return !S.getLangOpts().CPlusPlus;
8761   }
8762 
8763   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8764   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8765   if (isLHSFuncPtr || isRHSFuncPtr) {
8766     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8767     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8768                                                                 RHSExpr);
8769     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8770 
8771     return !S.getLangOpts().CPlusPlus;
8772   }
8773 
8774   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8775     return false;
8776   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8777     return false;
8778 
8779   return true;
8780 }
8781 
8782 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8783 /// literal.
8784 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8785                                   Expr *LHSExpr, Expr *RHSExpr) {
8786   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8787   Expr* IndexExpr = RHSExpr;
8788   if (!StrExpr) {
8789     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8790     IndexExpr = LHSExpr;
8791   }
8792 
8793   bool IsStringPlusInt = StrExpr &&
8794       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8795   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8796     return;
8797 
8798   llvm::APSInt index;
8799   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8800     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8801     if (index.isNonNegative() &&
8802         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8803                               index.isUnsigned()))
8804       return;
8805   }
8806 
8807   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8808   Self.Diag(OpLoc, diag::warn_string_plus_int)
8809       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8810 
8811   // Only print a fixit for "str" + int, not for int + "str".
8812   if (IndexExpr == RHSExpr) {
8813     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8814     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8815         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8816         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8817         << FixItHint::CreateInsertion(EndLoc, "]");
8818   } else
8819     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8820 }
8821 
8822 /// \brief Emit a warning when adding a char literal to a string.
8823 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8824                                    Expr *LHSExpr, Expr *RHSExpr) {
8825   const Expr *StringRefExpr = LHSExpr;
8826   const CharacterLiteral *CharExpr =
8827       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8828 
8829   if (!CharExpr) {
8830     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8831     StringRefExpr = RHSExpr;
8832   }
8833 
8834   if (!CharExpr || !StringRefExpr)
8835     return;
8836 
8837   const QualType StringType = StringRefExpr->getType();
8838 
8839   // Return if not a PointerType.
8840   if (!StringType->isAnyPointerType())
8841     return;
8842 
8843   // Return if not a CharacterType.
8844   if (!StringType->getPointeeType()->isAnyCharacterType())
8845     return;
8846 
8847   ASTContext &Ctx = Self.getASTContext();
8848   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8849 
8850   const QualType CharType = CharExpr->getType();
8851   if (!CharType->isAnyCharacterType() &&
8852       CharType->isIntegerType() &&
8853       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8854     Self.Diag(OpLoc, diag::warn_string_plus_char)
8855         << DiagRange << Ctx.CharTy;
8856   } else {
8857     Self.Diag(OpLoc, diag::warn_string_plus_char)
8858         << DiagRange << CharExpr->getType();
8859   }
8860 
8861   // Only print a fixit for str + char, not for char + str.
8862   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8863     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8864     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8865         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8866         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8867         << FixItHint::CreateInsertion(EndLoc, "]");
8868   } else {
8869     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8870   }
8871 }
8872 
8873 /// \brief Emit error when two pointers are incompatible.
8874 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8875                                            Expr *LHSExpr, Expr *RHSExpr) {
8876   assert(LHSExpr->getType()->isAnyPointerType());
8877   assert(RHSExpr->getType()->isAnyPointerType());
8878   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8879     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8880     << RHSExpr->getSourceRange();
8881 }
8882 
8883 // C99 6.5.6
8884 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8885                                      SourceLocation Loc, BinaryOperatorKind Opc,
8886                                      QualType* CompLHSTy) {
8887   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8888 
8889   if (LHS.get()->getType()->isVectorType() ||
8890       RHS.get()->getType()->isVectorType()) {
8891     QualType compType = CheckVectorOperands(
8892         LHS, RHS, Loc, CompLHSTy,
8893         /*AllowBothBool*/getLangOpts().AltiVec,
8894         /*AllowBoolConversions*/getLangOpts().ZVector);
8895     if (CompLHSTy) *CompLHSTy = compType;
8896     return compType;
8897   }
8898 
8899   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8900   if (LHS.isInvalid() || RHS.isInvalid())
8901     return QualType();
8902 
8903   // Diagnose "string literal" '+' int and string '+' "char literal".
8904   if (Opc == BO_Add) {
8905     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8906     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8907   }
8908 
8909   // handle the common case first (both operands are arithmetic).
8910   if (!compType.isNull() && compType->isArithmeticType()) {
8911     if (CompLHSTy) *CompLHSTy = compType;
8912     return compType;
8913   }
8914 
8915   // Type-checking.  Ultimately the pointer's going to be in PExp;
8916   // note that we bias towards the LHS being the pointer.
8917   Expr *PExp = LHS.get(), *IExp = RHS.get();
8918 
8919   bool isObjCPointer;
8920   if (PExp->getType()->isPointerType()) {
8921     isObjCPointer = false;
8922   } else if (PExp->getType()->isObjCObjectPointerType()) {
8923     isObjCPointer = true;
8924   } else {
8925     std::swap(PExp, IExp);
8926     if (PExp->getType()->isPointerType()) {
8927       isObjCPointer = false;
8928     } else if (PExp->getType()->isObjCObjectPointerType()) {
8929       isObjCPointer = true;
8930     } else {
8931       return InvalidOperands(Loc, LHS, RHS);
8932     }
8933   }
8934   assert(PExp->getType()->isAnyPointerType());
8935 
8936   if (!IExp->getType()->isIntegerType())
8937     return InvalidOperands(Loc, LHS, RHS);
8938 
8939   // Adding to a null pointer results in undefined behavior.
8940   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
8941           Context, Expr::NPC_ValueDependentIsNotNull)) {
8942     // In C++ adding zero to a null pointer is defined.
8943     llvm::APSInt KnownVal;
8944     if (!getLangOpts().CPlusPlus ||
8945         (!IExp->isValueDependent() &&
8946          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
8947       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
8948       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
8949           Context, BO_Add, PExp, IExp);
8950       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
8951     }
8952   }
8953 
8954   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8955     return QualType();
8956 
8957   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8958     return QualType();
8959 
8960   // Check array bounds for pointer arithemtic
8961   CheckArrayAccess(PExp, IExp);
8962 
8963   if (CompLHSTy) {
8964     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8965     if (LHSTy.isNull()) {
8966       LHSTy = LHS.get()->getType();
8967       if (LHSTy->isPromotableIntegerType())
8968         LHSTy = Context.getPromotedIntegerType(LHSTy);
8969     }
8970     *CompLHSTy = LHSTy;
8971   }
8972 
8973   return PExp->getType();
8974 }
8975 
8976 // C99 6.5.6
8977 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8978                                         SourceLocation Loc,
8979                                         QualType* CompLHSTy) {
8980   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8981 
8982   if (LHS.get()->getType()->isVectorType() ||
8983       RHS.get()->getType()->isVectorType()) {
8984     QualType compType = CheckVectorOperands(
8985         LHS, RHS, Loc, CompLHSTy,
8986         /*AllowBothBool*/getLangOpts().AltiVec,
8987         /*AllowBoolConversions*/getLangOpts().ZVector);
8988     if (CompLHSTy) *CompLHSTy = compType;
8989     return compType;
8990   }
8991 
8992   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8993   if (LHS.isInvalid() || RHS.isInvalid())
8994     return QualType();
8995 
8996   // Enforce type constraints: C99 6.5.6p3.
8997 
8998   // Handle the common case first (both operands are arithmetic).
8999   if (!compType.isNull() && compType->isArithmeticType()) {
9000     if (CompLHSTy) *CompLHSTy = compType;
9001     return compType;
9002   }
9003 
9004   // Either ptr - int   or   ptr - ptr.
9005   if (LHS.get()->getType()->isAnyPointerType()) {
9006     QualType lpointee = LHS.get()->getType()->getPointeeType();
9007 
9008     // Diagnose bad cases where we step over interface counts.
9009     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9010         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9011       return QualType();
9012 
9013     // The result type of a pointer-int computation is the pointer type.
9014     if (RHS.get()->getType()->isIntegerType()) {
9015       // Subtracting from a null pointer should produce a warning.
9016       // The last argument to the diagnose call says this doesn't match the
9017       // GNU int-to-pointer idiom.
9018       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9019                                            Expr::NPC_ValueDependentIsNotNull)) {
9020         // In C++ adding zero to a null pointer is defined.
9021         llvm::APSInt KnownVal;
9022         if (!getLangOpts().CPlusPlus ||
9023             (!RHS.get()->isValueDependent() &&
9024              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9025           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9026         }
9027       }
9028 
9029       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9030         return QualType();
9031 
9032       // Check array bounds for pointer arithemtic
9033       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9034                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9035 
9036       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9037       return LHS.get()->getType();
9038     }
9039 
9040     // Handle pointer-pointer subtractions.
9041     if (const PointerType *RHSPTy
9042           = RHS.get()->getType()->getAs<PointerType>()) {
9043       QualType rpointee = RHSPTy->getPointeeType();
9044 
9045       if (getLangOpts().CPlusPlus) {
9046         // Pointee types must be the same: C++ [expr.add]
9047         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9048           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9049         }
9050       } else {
9051         // Pointee types must be compatible C99 6.5.6p3
9052         if (!Context.typesAreCompatible(
9053                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9054                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9055           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9056           return QualType();
9057         }
9058       }
9059 
9060       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9061                                                LHS.get(), RHS.get()))
9062         return QualType();
9063 
9064       // FIXME: Add warnings for nullptr - ptr.
9065 
9066       // The pointee type may have zero size.  As an extension, a structure or
9067       // union may have zero size or an array may have zero length.  In this
9068       // case subtraction does not make sense.
9069       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9070         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9071         if (ElementSize.isZero()) {
9072           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9073             << rpointee.getUnqualifiedType()
9074             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9075         }
9076       }
9077 
9078       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9079       return Context.getPointerDiffType();
9080     }
9081   }
9082 
9083   return InvalidOperands(Loc, LHS, RHS);
9084 }
9085 
9086 static bool isScopedEnumerationType(QualType T) {
9087   if (const EnumType *ET = T->getAs<EnumType>())
9088     return ET->getDecl()->isScoped();
9089   return false;
9090 }
9091 
9092 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9093                                    SourceLocation Loc, BinaryOperatorKind Opc,
9094                                    QualType LHSType) {
9095   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9096   // so skip remaining warnings as we don't want to modify values within Sema.
9097   if (S.getLangOpts().OpenCL)
9098     return;
9099 
9100   llvm::APSInt Right;
9101   // Check right/shifter operand
9102   if (RHS.get()->isValueDependent() ||
9103       !RHS.get()->EvaluateAsInt(Right, S.Context))
9104     return;
9105 
9106   if (Right.isNegative()) {
9107     S.DiagRuntimeBehavior(Loc, RHS.get(),
9108                           S.PDiag(diag::warn_shift_negative)
9109                             << RHS.get()->getSourceRange());
9110     return;
9111   }
9112   llvm::APInt LeftBits(Right.getBitWidth(),
9113                        S.Context.getTypeSize(LHS.get()->getType()));
9114   if (Right.uge(LeftBits)) {
9115     S.DiagRuntimeBehavior(Loc, RHS.get(),
9116                           S.PDiag(diag::warn_shift_gt_typewidth)
9117                             << RHS.get()->getSourceRange());
9118     return;
9119   }
9120   if (Opc != BO_Shl)
9121     return;
9122 
9123   // When left shifting an ICE which is signed, we can check for overflow which
9124   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9125   // integers have defined behavior modulo one more than the maximum value
9126   // representable in the result type, so never warn for those.
9127   llvm::APSInt Left;
9128   if (LHS.get()->isValueDependent() ||
9129       LHSType->hasUnsignedIntegerRepresentation() ||
9130       !LHS.get()->EvaluateAsInt(Left, S.Context))
9131     return;
9132 
9133   // If LHS does not have a signed type and non-negative value
9134   // then, the behavior is undefined. Warn about it.
9135   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9136     S.DiagRuntimeBehavior(Loc, LHS.get(),
9137                           S.PDiag(diag::warn_shift_lhs_negative)
9138                             << LHS.get()->getSourceRange());
9139     return;
9140   }
9141 
9142   llvm::APInt ResultBits =
9143       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9144   if (LeftBits.uge(ResultBits))
9145     return;
9146   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9147   Result = Result.shl(Right);
9148 
9149   // Print the bit representation of the signed integer as an unsigned
9150   // hexadecimal number.
9151   SmallString<40> HexResult;
9152   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9153 
9154   // If we are only missing a sign bit, this is less likely to result in actual
9155   // bugs -- if the result is cast back to an unsigned type, it will have the
9156   // expected value. Thus we place this behind a different warning that can be
9157   // turned off separately if needed.
9158   if (LeftBits == ResultBits - 1) {
9159     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9160         << HexResult << LHSType
9161         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9162     return;
9163   }
9164 
9165   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9166     << HexResult.str() << Result.getMinSignedBits() << LHSType
9167     << Left.getBitWidth() << LHS.get()->getSourceRange()
9168     << RHS.get()->getSourceRange();
9169 }
9170 
9171 /// \brief Return the resulting type when a vector is shifted
9172 ///        by a scalar or vector shift amount.
9173 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9174                                  SourceLocation Loc, bool IsCompAssign) {
9175   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9176   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9177       !LHS.get()->getType()->isVectorType()) {
9178     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9179       << RHS.get()->getType() << LHS.get()->getType()
9180       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9181     return QualType();
9182   }
9183 
9184   if (!IsCompAssign) {
9185     LHS = S.UsualUnaryConversions(LHS.get());
9186     if (LHS.isInvalid()) return QualType();
9187   }
9188 
9189   RHS = S.UsualUnaryConversions(RHS.get());
9190   if (RHS.isInvalid()) return QualType();
9191 
9192   QualType LHSType = LHS.get()->getType();
9193   // Note that LHS might be a scalar because the routine calls not only in
9194   // OpenCL case.
9195   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9196   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9197 
9198   // Note that RHS might not be a vector.
9199   QualType RHSType = RHS.get()->getType();
9200   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9201   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9202 
9203   // The operands need to be integers.
9204   if (!LHSEleType->isIntegerType()) {
9205     S.Diag(Loc, diag::err_typecheck_expect_int)
9206       << LHS.get()->getType() << LHS.get()->getSourceRange();
9207     return QualType();
9208   }
9209 
9210   if (!RHSEleType->isIntegerType()) {
9211     S.Diag(Loc, diag::err_typecheck_expect_int)
9212       << RHS.get()->getType() << RHS.get()->getSourceRange();
9213     return QualType();
9214   }
9215 
9216   if (!LHSVecTy) {
9217     assert(RHSVecTy);
9218     if (IsCompAssign)
9219       return RHSType;
9220     if (LHSEleType != RHSEleType) {
9221       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9222       LHSEleType = RHSEleType;
9223     }
9224     QualType VecTy =
9225         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9226     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9227     LHSType = VecTy;
9228   } else if (RHSVecTy) {
9229     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9230     // are applied component-wise. So if RHS is a vector, then ensure
9231     // that the number of elements is the same as LHS...
9232     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9233       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9234         << LHS.get()->getType() << RHS.get()->getType()
9235         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9236       return QualType();
9237     }
9238     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9239       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9240       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9241       if (LHSBT != RHSBT &&
9242           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9243         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9244             << LHS.get()->getType() << RHS.get()->getType()
9245             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9246       }
9247     }
9248   } else {
9249     // ...else expand RHS to match the number of elements in LHS.
9250     QualType VecTy =
9251       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9252     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9253   }
9254 
9255   return LHSType;
9256 }
9257 
9258 // C99 6.5.7
9259 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9260                                   SourceLocation Loc, BinaryOperatorKind Opc,
9261                                   bool IsCompAssign) {
9262   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9263 
9264   // Vector shifts promote their scalar inputs to vector type.
9265   if (LHS.get()->getType()->isVectorType() ||
9266       RHS.get()->getType()->isVectorType()) {
9267     if (LangOpts.ZVector) {
9268       // The shift operators for the z vector extensions work basically
9269       // like general shifts, except that neither the LHS nor the RHS is
9270       // allowed to be a "vector bool".
9271       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9272         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9273           return InvalidOperands(Loc, LHS, RHS);
9274       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9275         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9276           return InvalidOperands(Loc, LHS, RHS);
9277     }
9278     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9279   }
9280 
9281   // Shifts don't perform usual arithmetic conversions, they just do integer
9282   // promotions on each operand. C99 6.5.7p3
9283 
9284   // For the LHS, do usual unary conversions, but then reset them away
9285   // if this is a compound assignment.
9286   ExprResult OldLHS = LHS;
9287   LHS = UsualUnaryConversions(LHS.get());
9288   if (LHS.isInvalid())
9289     return QualType();
9290   QualType LHSType = LHS.get()->getType();
9291   if (IsCompAssign) LHS = OldLHS;
9292 
9293   // The RHS is simpler.
9294   RHS = UsualUnaryConversions(RHS.get());
9295   if (RHS.isInvalid())
9296     return QualType();
9297   QualType RHSType = RHS.get()->getType();
9298 
9299   // C99 6.5.7p2: Each of the operands shall have integer type.
9300   if (!LHSType->hasIntegerRepresentation() ||
9301       !RHSType->hasIntegerRepresentation())
9302     return InvalidOperands(Loc, LHS, RHS);
9303 
9304   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9305   // hasIntegerRepresentation() above instead of this.
9306   if (isScopedEnumerationType(LHSType) ||
9307       isScopedEnumerationType(RHSType)) {
9308     return InvalidOperands(Loc, LHS, RHS);
9309   }
9310   // Sanity-check shift operands
9311   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9312 
9313   // "The type of the result is that of the promoted left operand."
9314   return LHSType;
9315 }
9316 
9317 /// If two different enums are compared, raise a warning.
9318 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9319                                 Expr *RHS) {
9320   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9321   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9322 
9323   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9324   if (!LHSEnumType)
9325     return;
9326   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9327   if (!RHSEnumType)
9328     return;
9329 
9330   // Ignore anonymous enums.
9331   if (!LHSEnumType->getDecl()->getIdentifier() &&
9332       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9333     return;
9334   if (!RHSEnumType->getDecl()->getIdentifier() &&
9335       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9336     return;
9337 
9338   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9339     return;
9340 
9341   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9342       << LHSStrippedType << RHSStrippedType
9343       << LHS->getSourceRange() << RHS->getSourceRange();
9344 }
9345 
9346 /// \brief Diagnose bad pointer comparisons.
9347 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9348                                               ExprResult &LHS, ExprResult &RHS,
9349                                               bool IsError) {
9350   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9351                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9352     << LHS.get()->getType() << RHS.get()->getType()
9353     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9354 }
9355 
9356 /// \brief Returns false if the pointers are converted to a composite type,
9357 /// true otherwise.
9358 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9359                                            ExprResult &LHS, ExprResult &RHS) {
9360   // C++ [expr.rel]p2:
9361   //   [...] Pointer conversions (4.10) and qualification
9362   //   conversions (4.4) are performed on pointer operands (or on
9363   //   a pointer operand and a null pointer constant) to bring
9364   //   them to their composite pointer type. [...]
9365   //
9366   // C++ [expr.eq]p1 uses the same notion for (in)equality
9367   // comparisons of pointers.
9368 
9369   QualType LHSType = LHS.get()->getType();
9370   QualType RHSType = RHS.get()->getType();
9371   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9372          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9373 
9374   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9375   if (T.isNull()) {
9376     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9377         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9378       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9379     else
9380       S.InvalidOperands(Loc, LHS, RHS);
9381     return true;
9382   }
9383 
9384   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9385   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9386   return false;
9387 }
9388 
9389 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9390                                                     ExprResult &LHS,
9391                                                     ExprResult &RHS,
9392                                                     bool IsError) {
9393   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9394                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9395     << LHS.get()->getType() << RHS.get()->getType()
9396     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9397 }
9398 
9399 static bool isObjCObjectLiteral(ExprResult &E) {
9400   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9401   case Stmt::ObjCArrayLiteralClass:
9402   case Stmt::ObjCDictionaryLiteralClass:
9403   case Stmt::ObjCStringLiteralClass:
9404   case Stmt::ObjCBoxedExprClass:
9405     return true;
9406   default:
9407     // Note that ObjCBoolLiteral is NOT an object literal!
9408     return false;
9409   }
9410 }
9411 
9412 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9413   const ObjCObjectPointerType *Type =
9414     LHS->getType()->getAs<ObjCObjectPointerType>();
9415 
9416   // If this is not actually an Objective-C object, bail out.
9417   if (!Type)
9418     return false;
9419 
9420   // Get the LHS object's interface type.
9421   QualType InterfaceType = Type->getPointeeType();
9422 
9423   // If the RHS isn't an Objective-C object, bail out.
9424   if (!RHS->getType()->isObjCObjectPointerType())
9425     return false;
9426 
9427   // Try to find the -isEqual: method.
9428   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9429   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9430                                                       InterfaceType,
9431                                                       /*instance=*/true);
9432   if (!Method) {
9433     if (Type->isObjCIdType()) {
9434       // For 'id', just check the global pool.
9435       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9436                                                   /*receiverId=*/true);
9437     } else {
9438       // Check protocols.
9439       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9440                                              /*instance=*/true);
9441     }
9442   }
9443 
9444   if (!Method)
9445     return false;
9446 
9447   QualType T = Method->parameters()[0]->getType();
9448   if (!T->isObjCObjectPointerType())
9449     return false;
9450 
9451   QualType R = Method->getReturnType();
9452   if (!R->isScalarType())
9453     return false;
9454 
9455   return true;
9456 }
9457 
9458 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9459   FromE = FromE->IgnoreParenImpCasts();
9460   switch (FromE->getStmtClass()) {
9461     default:
9462       break;
9463     case Stmt::ObjCStringLiteralClass:
9464       // "string literal"
9465       return LK_String;
9466     case Stmt::ObjCArrayLiteralClass:
9467       // "array literal"
9468       return LK_Array;
9469     case Stmt::ObjCDictionaryLiteralClass:
9470       // "dictionary literal"
9471       return LK_Dictionary;
9472     case Stmt::BlockExprClass:
9473       return LK_Block;
9474     case Stmt::ObjCBoxedExprClass: {
9475       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9476       switch (Inner->getStmtClass()) {
9477         case Stmt::IntegerLiteralClass:
9478         case Stmt::FloatingLiteralClass:
9479         case Stmt::CharacterLiteralClass:
9480         case Stmt::ObjCBoolLiteralExprClass:
9481         case Stmt::CXXBoolLiteralExprClass:
9482           // "numeric literal"
9483           return LK_Numeric;
9484         case Stmt::ImplicitCastExprClass: {
9485           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9486           // Boolean literals can be represented by implicit casts.
9487           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9488             return LK_Numeric;
9489           break;
9490         }
9491         default:
9492           break;
9493       }
9494       return LK_Boxed;
9495     }
9496   }
9497   return LK_None;
9498 }
9499 
9500 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9501                                           ExprResult &LHS, ExprResult &RHS,
9502                                           BinaryOperator::Opcode Opc){
9503   Expr *Literal;
9504   Expr *Other;
9505   if (isObjCObjectLiteral(LHS)) {
9506     Literal = LHS.get();
9507     Other = RHS.get();
9508   } else {
9509     Literal = RHS.get();
9510     Other = LHS.get();
9511   }
9512 
9513   // Don't warn on comparisons against nil.
9514   Other = Other->IgnoreParenCasts();
9515   if (Other->isNullPointerConstant(S.getASTContext(),
9516                                    Expr::NPC_ValueDependentIsNotNull))
9517     return;
9518 
9519   // This should be kept in sync with warn_objc_literal_comparison.
9520   // LK_String should always be after the other literals, since it has its own
9521   // warning flag.
9522   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9523   assert(LiteralKind != Sema::LK_Block);
9524   if (LiteralKind == Sema::LK_None) {
9525     llvm_unreachable("Unknown Objective-C object literal kind");
9526   }
9527 
9528   if (LiteralKind == Sema::LK_String)
9529     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9530       << Literal->getSourceRange();
9531   else
9532     S.Diag(Loc, diag::warn_objc_literal_comparison)
9533       << LiteralKind << Literal->getSourceRange();
9534 
9535   if (BinaryOperator::isEqualityOp(Opc) &&
9536       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9537     SourceLocation Start = LHS.get()->getLocStart();
9538     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9539     CharSourceRange OpRange =
9540       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9541 
9542     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9543       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9544       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9545       << FixItHint::CreateInsertion(End, "]");
9546   }
9547 }
9548 
9549 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9550 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9551                                            ExprResult &RHS, SourceLocation Loc,
9552                                            BinaryOperatorKind Opc) {
9553   // Check that left hand side is !something.
9554   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9555   if (!UO || UO->getOpcode() != UO_LNot) return;
9556 
9557   // Only check if the right hand side is non-bool arithmetic type.
9558   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9559 
9560   // Make sure that the something in !something is not bool.
9561   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9562   if (SubExpr->isKnownToHaveBooleanValue()) return;
9563 
9564   // Emit warning.
9565   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9566   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9567       << Loc << IsBitwiseOp;
9568 
9569   // First note suggest !(x < y)
9570   SourceLocation FirstOpen = SubExpr->getLocStart();
9571   SourceLocation FirstClose = RHS.get()->getLocEnd();
9572   FirstClose = S.getLocForEndOfToken(FirstClose);
9573   if (FirstClose.isInvalid())
9574     FirstOpen = SourceLocation();
9575   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9576       << IsBitwiseOp
9577       << FixItHint::CreateInsertion(FirstOpen, "(")
9578       << FixItHint::CreateInsertion(FirstClose, ")");
9579 
9580   // Second note suggests (!x) < y
9581   SourceLocation SecondOpen = LHS.get()->getLocStart();
9582   SourceLocation SecondClose = LHS.get()->getLocEnd();
9583   SecondClose = S.getLocForEndOfToken(SecondClose);
9584   if (SecondClose.isInvalid())
9585     SecondOpen = SourceLocation();
9586   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9587       << FixItHint::CreateInsertion(SecondOpen, "(")
9588       << FixItHint::CreateInsertion(SecondClose, ")");
9589 }
9590 
9591 // Get the decl for a simple expression: a reference to a variable,
9592 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9593 static ValueDecl *getCompareDecl(Expr *E) {
9594   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9595     return DR->getDecl();
9596   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9597     if (Ivar->isFreeIvar())
9598       return Ivar->getDecl();
9599   }
9600   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9601     if (Mem->isImplicitAccess())
9602       return Mem->getMemberDecl();
9603   }
9604   return nullptr;
9605 }
9606 
9607 /// Diagnose some forms of syntactically-obvious tautological comparison.
9608 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9609                                            Expr *LHS, Expr *RHS,
9610                                            BinaryOperatorKind Opc) {
9611   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9612   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9613 
9614   QualType LHSType = LHS->getType();
9615   if (LHSType->hasFloatingRepresentation() ||
9616       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9617       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9618       S.inTemplateInstantiation())
9619     return;
9620 
9621   // For non-floating point types, check for self-comparisons of the form
9622   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9623   // often indicate logic errors in the program.
9624   //
9625   // NOTE: Don't warn about comparison expressions resulting from macro
9626   // expansion. Also don't warn about comparisons which are only self
9627   // comparisons within a template instantiation. The warnings should catch
9628   // obvious cases in the definition of the template anyways. The idea is to
9629   // warn when the typed comparison operator will always evaluate to the same
9630   // result.
9631   ValueDecl *DL = getCompareDecl(LHSStripped);
9632   ValueDecl *DR = getCompareDecl(RHSStripped);
9633   if (DL && DR && declaresSameEntity(DL, DR)) {
9634     StringRef Result;
9635     switch (Opc) {
9636     case BO_EQ: case BO_LE: case BO_GE:
9637       Result = "true";
9638       break;
9639     case BO_NE: case BO_LT: case BO_GT:
9640       Result = "false";
9641       break;
9642     case BO_Cmp:
9643       Result = "'std::strong_ordering::equal'";
9644       break;
9645     default:
9646       break;
9647     }
9648     S.DiagRuntimeBehavior(Loc, nullptr,
9649                           S.PDiag(diag::warn_comparison_always)
9650                               << 0 /*self-comparison*/ << !Result.empty()
9651                               << Result);
9652   } else if (DL && DR &&
9653              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9654              !DL->isWeak() && !DR->isWeak()) {
9655     // What is it always going to evaluate to?
9656     StringRef Result;
9657     switch(Opc) {
9658     case BO_EQ: // e.g. array1 == array2
9659       Result = "false";
9660       break;
9661     case BO_NE: // e.g. array1 != array2
9662       Result = "true";
9663       break;
9664     default: // e.g. array1 <= array2
9665       // The best we can say is 'a constant'
9666       break;
9667     }
9668     S.DiagRuntimeBehavior(Loc, nullptr,
9669                           S.PDiag(diag::warn_comparison_always)
9670                               << 1 /*array comparison*/
9671                               << !Result.empty() << Result);
9672   }
9673 
9674   if (isa<CastExpr>(LHSStripped))
9675     LHSStripped = LHSStripped->IgnoreParenCasts();
9676   if (isa<CastExpr>(RHSStripped))
9677     RHSStripped = RHSStripped->IgnoreParenCasts();
9678 
9679   // Warn about comparisons against a string constant (unless the other
9680   // operand is null); the user probably wants strcmp.
9681   Expr *LiteralString = nullptr;
9682   Expr *LiteralStringStripped = nullptr;
9683   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9684       !RHSStripped->isNullPointerConstant(S.Context,
9685                                           Expr::NPC_ValueDependentIsNull)) {
9686     LiteralString = LHS;
9687     LiteralStringStripped = LHSStripped;
9688   } else if ((isa<StringLiteral>(RHSStripped) ||
9689               isa<ObjCEncodeExpr>(RHSStripped)) &&
9690              !LHSStripped->isNullPointerConstant(S.Context,
9691                                           Expr::NPC_ValueDependentIsNull)) {
9692     LiteralString = RHS;
9693     LiteralStringStripped = RHSStripped;
9694   }
9695 
9696   if (LiteralString) {
9697     S.DiagRuntimeBehavior(Loc, nullptr,
9698                           S.PDiag(diag::warn_stringcompare)
9699                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9700                               << LiteralString->getSourceRange());
9701   }
9702 }
9703 
9704 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9705                                                  ExprResult &RHS,
9706                                                  SourceLocation Loc,
9707                                                  BinaryOperatorKind Opc) {
9708   // C99 6.5.8p3 / C99 6.5.9p4
9709   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9710   if (LHS.isInvalid() || RHS.isInvalid())
9711     return QualType();
9712   if (Type.isNull())
9713     return S.InvalidOperands(Loc, LHS, RHS);
9714   assert(Type->isArithmeticType() || Type->isEnumeralType());
9715 
9716   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
9717 
9718   enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering;
9719   if (Type->isAnyComplexType())
9720     Ordering = StrongEquality;
9721   else if (Type->isFloatingType())
9722     Ordering = PartialOrdering;
9723   else
9724     Ordering = StrongOrdering;
9725 
9726   if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc))
9727     return S.InvalidOperands(Loc, LHS, RHS);
9728 
9729   // Check for comparisons of floating point operands using != and ==.
9730   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
9731     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
9732 
9733   // The result of comparisons is 'bool' in C++, 'int' in C.
9734   // FIXME: For BO_Cmp, return the relevant comparison category type.
9735   return S.Context.getLogicalOperationType();
9736 }
9737 
9738 // C99 6.5.8, C++ [expr.rel]
9739 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9740                                     SourceLocation Loc, BinaryOperatorKind Opc,
9741                                     bool IsRelational) {
9742   // Comparisons expect an rvalue, so convert to rvalue before any
9743   // type-related checks.
9744   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9745   if (LHS.isInvalid())
9746     return QualType();
9747   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9748   if (RHS.isInvalid())
9749     return QualType();
9750 
9751   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9752 
9753   // Handle vector comparisons separately.
9754   if (LHS.get()->getType()->isVectorType() ||
9755       RHS.get()->getType()->isVectorType())
9756     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
9757 
9758   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9759   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
9760 
9761   QualType LHSType = LHS.get()->getType();
9762   QualType RHSType = RHS.get()->getType();
9763   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
9764       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
9765     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
9766 
9767   QualType ResultTy = Context.getLogicalOperationType();
9768 
9769   const Expr::NullPointerConstantKind LHSNullKind =
9770       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9771   const Expr::NullPointerConstantKind RHSNullKind =
9772       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9773   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9774   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9775 
9776   if (!IsRelational && LHSIsNull != RHSIsNull) {
9777     bool IsEquality = Opc == BO_EQ;
9778     if (RHSIsNull)
9779       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9780                                    RHS.get()->getSourceRange());
9781     else
9782       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9783                                    LHS.get()->getSourceRange());
9784   }
9785 
9786   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9787       (RHSType->isIntegerType() && !RHSIsNull)) {
9788     // Skip normal pointer conversion checks in this case; we have better
9789     // diagnostics for this below.
9790   } else if (getLangOpts().CPlusPlus) {
9791     // Equality comparison of a function pointer to a void pointer is invalid,
9792     // but we allow it as an extension.
9793     // FIXME: If we really want to allow this, should it be part of composite
9794     // pointer type computation so it works in conditionals too?
9795     if (!IsRelational &&
9796         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9797          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9798       // This is a gcc extension compatibility comparison.
9799       // In a SFINAE context, we treat this as a hard error to maintain
9800       // conformance with the C++ standard.
9801       diagnoseFunctionPointerToVoidComparison(
9802           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9803 
9804       if (isSFINAEContext())
9805         return QualType();
9806 
9807       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9808       return ResultTy;
9809     }
9810 
9811     // C++ [expr.eq]p2:
9812     //   If at least one operand is a pointer [...] bring them to their
9813     //   composite pointer type.
9814     // C++ [expr.rel]p2:
9815     //   If both operands are pointers, [...] bring them to their composite
9816     //   pointer type.
9817     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9818             (IsRelational ? 2 : 1) &&
9819         (!LangOpts.ObjCAutoRefCount ||
9820          !(LHSType->isObjCObjectPointerType() ||
9821            RHSType->isObjCObjectPointerType()))) {
9822       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9823         return QualType();
9824       else
9825         return ResultTy;
9826     }
9827   } else if (LHSType->isPointerType() &&
9828              RHSType->isPointerType()) { // C99 6.5.8p2
9829     // All of the following pointer-related warnings are GCC extensions, except
9830     // when handling null pointer constants.
9831     QualType LCanPointeeTy =
9832       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9833     QualType RCanPointeeTy =
9834       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9835 
9836     // C99 6.5.9p2 and C99 6.5.8p2
9837     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9838                                    RCanPointeeTy.getUnqualifiedType())) {
9839       // Valid unless a relational comparison of function pointers
9840       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9841         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9842           << LHSType << RHSType << LHS.get()->getSourceRange()
9843           << RHS.get()->getSourceRange();
9844       }
9845     } else if (!IsRelational &&
9846                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9847       // Valid unless comparison between non-null pointer and function pointer
9848       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9849           && !LHSIsNull && !RHSIsNull)
9850         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9851                                                 /*isError*/false);
9852     } else {
9853       // Invalid
9854       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9855     }
9856     if (LCanPointeeTy != RCanPointeeTy) {
9857       // Treat NULL constant as a special case in OpenCL.
9858       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9859         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9860         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9861           Diag(Loc,
9862                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9863               << LHSType << RHSType << 0 /* comparison */
9864               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9865         }
9866       }
9867       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
9868       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
9869       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9870                                                : CK_BitCast;
9871       if (LHSIsNull && !RHSIsNull)
9872         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9873       else
9874         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9875     }
9876     return ResultTy;
9877   }
9878 
9879   if (getLangOpts().CPlusPlus) {
9880     // C++ [expr.eq]p4:
9881     //   Two operands of type std::nullptr_t or one operand of type
9882     //   std::nullptr_t and the other a null pointer constant compare equal.
9883     if (!IsRelational && LHSIsNull && RHSIsNull) {
9884       if (LHSType->isNullPtrType()) {
9885         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9886         return ResultTy;
9887       }
9888       if (RHSType->isNullPtrType()) {
9889         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9890         return ResultTy;
9891       }
9892     }
9893 
9894     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9895     // These aren't covered by the composite pointer type rules.
9896     if (!IsRelational && RHSType->isNullPtrType() &&
9897         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9898       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9899       return ResultTy;
9900     }
9901     if (!IsRelational && LHSType->isNullPtrType() &&
9902         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9903       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9904       return ResultTy;
9905     }
9906 
9907     if (IsRelational &&
9908         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9909          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9910       // HACK: Relational comparison of nullptr_t against a pointer type is
9911       // invalid per DR583, but we allow it within std::less<> and friends,
9912       // since otherwise common uses of it break.
9913       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9914       // friends to have std::nullptr_t overload candidates.
9915       DeclContext *DC = CurContext;
9916       if (isa<FunctionDecl>(DC))
9917         DC = DC->getParent();
9918       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9919         if (CTSD->isInStdNamespace() &&
9920             llvm::StringSwitch<bool>(CTSD->getName())
9921                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9922                 .Default(false)) {
9923           if (RHSType->isNullPtrType())
9924             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9925           else
9926             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9927           return ResultTy;
9928         }
9929       }
9930     }
9931 
9932     // C++ [expr.eq]p2:
9933     //   If at least one operand is a pointer to member, [...] bring them to
9934     //   their composite pointer type.
9935     if (!IsRelational &&
9936         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9937       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9938         return QualType();
9939       else
9940         return ResultTy;
9941     }
9942   }
9943 
9944   // Handle block pointer types.
9945   if (!IsRelational && LHSType->isBlockPointerType() &&
9946       RHSType->isBlockPointerType()) {
9947     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9948     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9949 
9950     if (!LHSIsNull && !RHSIsNull &&
9951         !Context.typesAreCompatible(lpointee, rpointee)) {
9952       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9953         << LHSType << RHSType << LHS.get()->getSourceRange()
9954         << RHS.get()->getSourceRange();
9955     }
9956     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9957     return ResultTy;
9958   }
9959 
9960   // Allow block pointers to be compared with null pointer constants.
9961   if (!IsRelational
9962       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9963           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9964     if (!LHSIsNull && !RHSIsNull) {
9965       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9966              ->getPointeeType()->isVoidType())
9967             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9968                 ->getPointeeType()->isVoidType())))
9969         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9970           << LHSType << RHSType << LHS.get()->getSourceRange()
9971           << RHS.get()->getSourceRange();
9972     }
9973     if (LHSIsNull && !RHSIsNull)
9974       LHS = ImpCastExprToType(LHS.get(), RHSType,
9975                               RHSType->isPointerType() ? CK_BitCast
9976                                 : CK_AnyPointerToBlockPointerCast);
9977     else
9978       RHS = ImpCastExprToType(RHS.get(), LHSType,
9979                               LHSType->isPointerType() ? CK_BitCast
9980                                 : CK_AnyPointerToBlockPointerCast);
9981     return ResultTy;
9982   }
9983 
9984   if (LHSType->isObjCObjectPointerType() ||
9985       RHSType->isObjCObjectPointerType()) {
9986     const PointerType *LPT = LHSType->getAs<PointerType>();
9987     const PointerType *RPT = RHSType->getAs<PointerType>();
9988     if (LPT || RPT) {
9989       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9990       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9991 
9992       if (!LPtrToVoid && !RPtrToVoid &&
9993           !Context.typesAreCompatible(LHSType, RHSType)) {
9994         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9995                                           /*isError*/false);
9996       }
9997       if (LHSIsNull && !RHSIsNull) {
9998         Expr *E = LHS.get();
9999         if (getLangOpts().ObjCAutoRefCount)
10000           CheckObjCConversion(SourceRange(), RHSType, E,
10001                               CCK_ImplicitConversion);
10002         LHS = ImpCastExprToType(E, RHSType,
10003                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10004       }
10005       else {
10006         Expr *E = RHS.get();
10007         if (getLangOpts().ObjCAutoRefCount)
10008           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10009                               /*Diagnose=*/true,
10010                               /*DiagnoseCFAudited=*/false, Opc);
10011         RHS = ImpCastExprToType(E, LHSType,
10012                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10013       }
10014       return ResultTy;
10015     }
10016     if (LHSType->isObjCObjectPointerType() &&
10017         RHSType->isObjCObjectPointerType()) {
10018       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10019         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10020                                           /*isError*/false);
10021       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10022         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10023 
10024       if (LHSIsNull && !RHSIsNull)
10025         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10026       else
10027         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10028       return ResultTy;
10029     }
10030   }
10031   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10032       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10033     unsigned DiagID = 0;
10034     bool isError = false;
10035     if (LangOpts.DebuggerSupport) {
10036       // Under a debugger, allow the comparison of pointers to integers,
10037       // since users tend to want to compare addresses.
10038     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10039                (RHSIsNull && RHSType->isIntegerType())) {
10040       if (IsRelational) {
10041         isError = getLangOpts().CPlusPlus;
10042         DiagID =
10043           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10044                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10045       }
10046     } else if (getLangOpts().CPlusPlus) {
10047       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10048       isError = true;
10049     } else if (IsRelational)
10050       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10051     else
10052       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10053 
10054     if (DiagID) {
10055       Diag(Loc, DiagID)
10056         << LHSType << RHSType << LHS.get()->getSourceRange()
10057         << RHS.get()->getSourceRange();
10058       if (isError)
10059         return QualType();
10060     }
10061 
10062     if (LHSType->isIntegerType())
10063       LHS = ImpCastExprToType(LHS.get(), RHSType,
10064                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10065     else
10066       RHS = ImpCastExprToType(RHS.get(), LHSType,
10067                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10068     return ResultTy;
10069   }
10070 
10071   // Handle block pointers.
10072   if (!IsRelational && RHSIsNull
10073       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10074     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10075     return ResultTy;
10076   }
10077   if (!IsRelational && LHSIsNull
10078       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10079     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10080     return ResultTy;
10081   }
10082 
10083   if (getLangOpts().OpenCLVersion >= 200) {
10084     if (LHSIsNull && RHSType->isQueueT()) {
10085       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10086       return ResultTy;
10087     }
10088 
10089     if (LHSType->isQueueT() && RHSIsNull) {
10090       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10091       return ResultTy;
10092     }
10093   }
10094 
10095   return InvalidOperands(Loc, LHS, RHS);
10096 }
10097 
10098 // Return a signed ext_vector_type that is of identical size and number of
10099 // elements. For floating point vectors, return an integer type of identical
10100 // size and number of elements. In the non ext_vector_type case, search from
10101 // the largest type to the smallest type to avoid cases where long long == long,
10102 // where long gets picked over long long.
10103 QualType Sema::GetSignedVectorType(QualType V) {
10104   const VectorType *VTy = V->getAs<VectorType>();
10105   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10106 
10107   if (isa<ExtVectorType>(VTy)) {
10108     if (TypeSize == Context.getTypeSize(Context.CharTy))
10109       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10110     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10111       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10112     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10113       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10114     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10115       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10116     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10117            "Unhandled vector element size in vector compare");
10118     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10119   }
10120 
10121   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10122     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10123                                  VectorType::GenericVector);
10124   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10125     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10126                                  VectorType::GenericVector);
10127   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10128     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10129                                  VectorType::GenericVector);
10130   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10131     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10132                                  VectorType::GenericVector);
10133   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10134          "Unhandled vector element size in vector compare");
10135   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10136                                VectorType::GenericVector);
10137 }
10138 
10139 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10140 /// operates on extended vector types.  Instead of producing an IntTy result,
10141 /// like a scalar comparison, a vector comparison produces a vector of integer
10142 /// types.
10143 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10144                                           SourceLocation Loc,
10145                                           BinaryOperatorKind Opc) {
10146   // Check to make sure we're operating on vectors of the same type and width,
10147   // Allowing one side to be a scalar of element type.
10148   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10149                               /*AllowBothBool*/true,
10150                               /*AllowBoolConversions*/getLangOpts().ZVector);
10151   if (vType.isNull())
10152     return vType;
10153 
10154   QualType LHSType = LHS.get()->getType();
10155 
10156   // If AltiVec, the comparison results in a numeric type, i.e.
10157   // bool for C++, int for C
10158   if (getLangOpts().AltiVec &&
10159       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10160     return Context.getLogicalOperationType();
10161 
10162   // For non-floating point types, check for self-comparisons of the form
10163   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10164   // often indicate logic errors in the program.
10165   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10166 
10167   // Check for comparisons of floating point operands using != and ==.
10168   if (BinaryOperator::isEqualityOp(Opc) &&
10169       LHSType->hasFloatingRepresentation()) {
10170     assert(RHS.get()->getType()->hasFloatingRepresentation());
10171     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10172   }
10173 
10174   // Return a signed type for the vector.
10175   return GetSignedVectorType(vType);
10176 }
10177 
10178 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10179                                           SourceLocation Loc) {
10180   // Ensure that either both operands are of the same vector type, or
10181   // one operand is of a vector type and the other is of its element type.
10182   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10183                                        /*AllowBothBool*/true,
10184                                        /*AllowBoolConversions*/false);
10185   if (vType.isNull())
10186     return InvalidOperands(Loc, LHS, RHS);
10187   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10188       vType->hasFloatingRepresentation())
10189     return InvalidOperands(Loc, LHS, RHS);
10190   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10191   //        usage of the logical operators && and || with vectors in C. This
10192   //        check could be notionally dropped.
10193   if (!getLangOpts().CPlusPlus &&
10194       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10195     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10196 
10197   return GetSignedVectorType(LHS.get()->getType());
10198 }
10199 
10200 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10201                                            SourceLocation Loc,
10202                                            BinaryOperatorKind Opc) {
10203   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10204 
10205   bool IsCompAssign =
10206       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10207 
10208   if (LHS.get()->getType()->isVectorType() ||
10209       RHS.get()->getType()->isVectorType()) {
10210     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10211         RHS.get()->getType()->hasIntegerRepresentation())
10212       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10213                         /*AllowBothBool*/true,
10214                         /*AllowBoolConversions*/getLangOpts().ZVector);
10215     return InvalidOperands(Loc, LHS, RHS);
10216   }
10217 
10218   if (Opc == BO_And)
10219     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10220 
10221   ExprResult LHSResult = LHS, RHSResult = RHS;
10222   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10223                                                  IsCompAssign);
10224   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10225     return QualType();
10226   LHS = LHSResult.get();
10227   RHS = RHSResult.get();
10228 
10229   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10230     return compType;
10231   return InvalidOperands(Loc, LHS, RHS);
10232 }
10233 
10234 // C99 6.5.[13,14]
10235 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10236                                            SourceLocation Loc,
10237                                            BinaryOperatorKind Opc) {
10238   // Check vector operands differently.
10239   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10240     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10241 
10242   // Diagnose cases where the user write a logical and/or but probably meant a
10243   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10244   // is a constant.
10245   if (LHS.get()->getType()->isIntegerType() &&
10246       !LHS.get()->getType()->isBooleanType() &&
10247       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10248       // Don't warn in macros or template instantiations.
10249       !Loc.isMacroID() && !inTemplateInstantiation()) {
10250     // If the RHS can be constant folded, and if it constant folds to something
10251     // that isn't 0 or 1 (which indicate a potential logical operation that
10252     // happened to fold to true/false) then warn.
10253     // Parens on the RHS are ignored.
10254     llvm::APSInt Result;
10255     if (RHS.get()->EvaluateAsInt(Result, Context))
10256       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10257            !RHS.get()->getExprLoc().isMacroID()) ||
10258           (Result != 0 && Result != 1)) {
10259         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10260           << RHS.get()->getSourceRange()
10261           << (Opc == BO_LAnd ? "&&" : "||");
10262         // Suggest replacing the logical operator with the bitwise version
10263         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10264             << (Opc == BO_LAnd ? "&" : "|")
10265             << FixItHint::CreateReplacement(SourceRange(
10266                                                  Loc, getLocForEndOfToken(Loc)),
10267                                             Opc == BO_LAnd ? "&" : "|");
10268         if (Opc == BO_LAnd)
10269           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10270           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10271               << FixItHint::CreateRemoval(
10272                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10273                               RHS.get()->getLocEnd()));
10274       }
10275   }
10276 
10277   if (!Context.getLangOpts().CPlusPlus) {
10278     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10279     // not operate on the built-in scalar and vector float types.
10280     if (Context.getLangOpts().OpenCL &&
10281         Context.getLangOpts().OpenCLVersion < 120) {
10282       if (LHS.get()->getType()->isFloatingType() ||
10283           RHS.get()->getType()->isFloatingType())
10284         return InvalidOperands(Loc, LHS, RHS);
10285     }
10286 
10287     LHS = UsualUnaryConversions(LHS.get());
10288     if (LHS.isInvalid())
10289       return QualType();
10290 
10291     RHS = UsualUnaryConversions(RHS.get());
10292     if (RHS.isInvalid())
10293       return QualType();
10294 
10295     if (!LHS.get()->getType()->isScalarType() ||
10296         !RHS.get()->getType()->isScalarType())
10297       return InvalidOperands(Loc, LHS, RHS);
10298 
10299     return Context.IntTy;
10300   }
10301 
10302   // The following is safe because we only use this method for
10303   // non-overloadable operands.
10304 
10305   // C++ [expr.log.and]p1
10306   // C++ [expr.log.or]p1
10307   // The operands are both contextually converted to type bool.
10308   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10309   if (LHSRes.isInvalid())
10310     return InvalidOperands(Loc, LHS, RHS);
10311   LHS = LHSRes;
10312 
10313   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10314   if (RHSRes.isInvalid())
10315     return InvalidOperands(Loc, LHS, RHS);
10316   RHS = RHSRes;
10317 
10318   // C++ [expr.log.and]p2
10319   // C++ [expr.log.or]p2
10320   // The result is a bool.
10321   return Context.BoolTy;
10322 }
10323 
10324 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10325   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10326   if (!ME) return false;
10327   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10328   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10329       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10330   if (!Base) return false;
10331   return Base->getMethodDecl() != nullptr;
10332 }
10333 
10334 /// Is the given expression (which must be 'const') a reference to a
10335 /// variable which was originally non-const, but which has become
10336 /// 'const' due to being captured within a block?
10337 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10338 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10339   assert(E->isLValue() && E->getType().isConstQualified());
10340   E = E->IgnoreParens();
10341 
10342   // Must be a reference to a declaration from an enclosing scope.
10343   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10344   if (!DRE) return NCCK_None;
10345   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10346 
10347   // The declaration must be a variable which is not declared 'const'.
10348   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10349   if (!var) return NCCK_None;
10350   if (var->getType().isConstQualified()) return NCCK_None;
10351   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10352 
10353   // Decide whether the first capture was for a block or a lambda.
10354   DeclContext *DC = S.CurContext, *Prev = nullptr;
10355   // Decide whether the first capture was for a block or a lambda.
10356   while (DC) {
10357     // For init-capture, it is possible that the variable belongs to the
10358     // template pattern of the current context.
10359     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10360       if (var->isInitCapture() &&
10361           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10362         break;
10363     if (DC == var->getDeclContext())
10364       break;
10365     Prev = DC;
10366     DC = DC->getParent();
10367   }
10368   // Unless we have an init-capture, we've gone one step too far.
10369   if (!var->isInitCapture())
10370     DC = Prev;
10371   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10372 }
10373 
10374 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10375   Ty = Ty.getNonReferenceType();
10376   if (IsDereference && Ty->isPointerType())
10377     Ty = Ty->getPointeeType();
10378   return !Ty.isConstQualified();
10379 }
10380 
10381 // Update err_typecheck_assign_const and note_typecheck_assign_const
10382 // when this enum is changed.
10383 enum {
10384   ConstFunction,
10385   ConstVariable,
10386   ConstMember,
10387   ConstMethod,
10388   NestedConstMember,
10389   ConstUnknown,  // Keep as last element
10390 };
10391 
10392 /// Emit the "read-only variable not assignable" error and print notes to give
10393 /// more information about why the variable is not assignable, such as pointing
10394 /// to the declaration of a const variable, showing that a method is const, or
10395 /// that the function is returning a const reference.
10396 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10397                                     SourceLocation Loc) {
10398   SourceRange ExprRange = E->getSourceRange();
10399 
10400   // Only emit one error on the first const found.  All other consts will emit
10401   // a note to the error.
10402   bool DiagnosticEmitted = false;
10403 
10404   // Track if the current expression is the result of a dereference, and if the
10405   // next checked expression is the result of a dereference.
10406   bool IsDereference = false;
10407   bool NextIsDereference = false;
10408 
10409   // Loop to process MemberExpr chains.
10410   while (true) {
10411     IsDereference = NextIsDereference;
10412 
10413     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10414     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10415       NextIsDereference = ME->isArrow();
10416       const ValueDecl *VD = ME->getMemberDecl();
10417       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10418         // Mutable fields can be modified even if the class is const.
10419         if (Field->isMutable()) {
10420           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10421           break;
10422         }
10423 
10424         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10425           if (!DiagnosticEmitted) {
10426             S.Diag(Loc, diag::err_typecheck_assign_const)
10427                 << ExprRange << ConstMember << false /*static*/ << Field
10428                 << Field->getType();
10429             DiagnosticEmitted = true;
10430           }
10431           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10432               << ConstMember << false /*static*/ << Field << Field->getType()
10433               << Field->getSourceRange();
10434         }
10435         E = ME->getBase();
10436         continue;
10437       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10438         if (VDecl->getType().isConstQualified()) {
10439           if (!DiagnosticEmitted) {
10440             S.Diag(Loc, diag::err_typecheck_assign_const)
10441                 << ExprRange << ConstMember << true /*static*/ << VDecl
10442                 << VDecl->getType();
10443             DiagnosticEmitted = true;
10444           }
10445           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10446               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10447               << VDecl->getSourceRange();
10448         }
10449         // Static fields do not inherit constness from parents.
10450         break;
10451       }
10452       break; // End MemberExpr
10453     } else if (const ArraySubscriptExpr *ASE =
10454                    dyn_cast<ArraySubscriptExpr>(E)) {
10455       E = ASE->getBase()->IgnoreParenImpCasts();
10456       continue;
10457     } else if (const ExtVectorElementExpr *EVE =
10458                    dyn_cast<ExtVectorElementExpr>(E)) {
10459       E = EVE->getBase()->IgnoreParenImpCasts();
10460       continue;
10461     }
10462     break;
10463   }
10464 
10465   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10466     // Function calls
10467     const FunctionDecl *FD = CE->getDirectCallee();
10468     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10469       if (!DiagnosticEmitted) {
10470         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10471                                                       << ConstFunction << FD;
10472         DiagnosticEmitted = true;
10473       }
10474       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10475              diag::note_typecheck_assign_const)
10476           << ConstFunction << FD << FD->getReturnType()
10477           << FD->getReturnTypeSourceRange();
10478     }
10479   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10480     // Point to variable declaration.
10481     if (const ValueDecl *VD = DRE->getDecl()) {
10482       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10483         if (!DiagnosticEmitted) {
10484           S.Diag(Loc, diag::err_typecheck_assign_const)
10485               << ExprRange << ConstVariable << VD << VD->getType();
10486           DiagnosticEmitted = true;
10487         }
10488         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10489             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10490       }
10491     }
10492   } else if (isa<CXXThisExpr>(E)) {
10493     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10494       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10495         if (MD->isConst()) {
10496           if (!DiagnosticEmitted) {
10497             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10498                                                           << ConstMethod << MD;
10499             DiagnosticEmitted = true;
10500           }
10501           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10502               << ConstMethod << MD << MD->getSourceRange();
10503         }
10504       }
10505     }
10506   }
10507 
10508   if (DiagnosticEmitted)
10509     return;
10510 
10511   // Can't determine a more specific message, so display the generic error.
10512   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10513 }
10514 
10515 enum OriginalExprKind {
10516   OEK_Variable,
10517   OEK_Member,
10518   OEK_LValue
10519 };
10520 
10521 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10522                                          const RecordType *Ty,
10523                                          SourceLocation Loc, SourceRange Range,
10524                                          OriginalExprKind OEK,
10525                                          bool &DiagnosticEmitted,
10526                                          bool IsNested = false) {
10527   // We walk the record hierarchy breadth-first to ensure that we print
10528   // diagnostics in field nesting order.
10529   // First, check every field for constness.
10530   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10531     if (Field->getType().isConstQualified()) {
10532       if (!DiagnosticEmitted) {
10533         S.Diag(Loc, diag::err_typecheck_assign_const)
10534             << Range << NestedConstMember << OEK << VD
10535             << IsNested << Field;
10536         DiagnosticEmitted = true;
10537       }
10538       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10539           << NestedConstMember << IsNested << Field
10540           << Field->getType() << Field->getSourceRange();
10541     }
10542   }
10543   // Then, recurse.
10544   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10545     QualType FTy = Field->getType();
10546     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10547       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10548                                    OEK, DiagnosticEmitted, true);
10549   }
10550 }
10551 
10552 /// Emit an error for the case where a record we are trying to assign to has a
10553 /// const-qualified field somewhere in its hierarchy.
10554 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10555                                          SourceLocation Loc) {
10556   QualType Ty = E->getType();
10557   assert(Ty->isRecordType() && "lvalue was not record?");
10558   SourceRange Range = E->getSourceRange();
10559   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10560   bool DiagEmitted = false;
10561 
10562   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10563     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10564             Range, OEK_Member, DiagEmitted);
10565   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10566     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10567             Range, OEK_Variable, DiagEmitted);
10568   else
10569     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10570             Range, OEK_LValue, DiagEmitted);
10571   if (!DiagEmitted)
10572     DiagnoseConstAssignment(S, E, Loc);
10573 }
10574 
10575 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10576 /// emit an error and return true.  If so, return false.
10577 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10578   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10579 
10580   S.CheckShadowingDeclModification(E, Loc);
10581 
10582   SourceLocation OrigLoc = Loc;
10583   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10584                                                               &Loc);
10585   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10586     IsLV = Expr::MLV_InvalidMessageExpression;
10587   if (IsLV == Expr::MLV_Valid)
10588     return false;
10589 
10590   unsigned DiagID = 0;
10591   bool NeedType = false;
10592   switch (IsLV) { // C99 6.5.16p2
10593   case Expr::MLV_ConstQualified:
10594     // Use a specialized diagnostic when we're assigning to an object
10595     // from an enclosing function or block.
10596     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10597       if (NCCK == NCCK_Block)
10598         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10599       else
10600         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10601       break;
10602     }
10603 
10604     // In ARC, use some specialized diagnostics for occasions where we
10605     // infer 'const'.  These are always pseudo-strong variables.
10606     if (S.getLangOpts().ObjCAutoRefCount) {
10607       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10608       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10609         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10610 
10611         // Use the normal diagnostic if it's pseudo-__strong but the
10612         // user actually wrote 'const'.
10613         if (var->isARCPseudoStrong() &&
10614             (!var->getTypeSourceInfo() ||
10615              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10616           // There are two pseudo-strong cases:
10617           //  - self
10618           ObjCMethodDecl *method = S.getCurMethodDecl();
10619           if (method && var == method->getSelfDecl())
10620             DiagID = method->isClassMethod()
10621               ? diag::err_typecheck_arc_assign_self_class_method
10622               : diag::err_typecheck_arc_assign_self;
10623 
10624           //  - fast enumeration variables
10625           else
10626             DiagID = diag::err_typecheck_arr_assign_enumeration;
10627 
10628           SourceRange Assign;
10629           if (Loc != OrigLoc)
10630             Assign = SourceRange(OrigLoc, OrigLoc);
10631           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10632           // We need to preserve the AST regardless, so migration tool
10633           // can do its job.
10634           return false;
10635         }
10636       }
10637     }
10638 
10639     // If none of the special cases above are triggered, then this is a
10640     // simple const assignment.
10641     if (DiagID == 0) {
10642       DiagnoseConstAssignment(S, E, Loc);
10643       return true;
10644     }
10645 
10646     break;
10647   case Expr::MLV_ConstAddrSpace:
10648     DiagnoseConstAssignment(S, E, Loc);
10649     return true;
10650   case Expr::MLV_ConstQualifiedField:
10651     DiagnoseRecursiveConstFields(S, E, Loc);
10652     return true;
10653   case Expr::MLV_ArrayType:
10654   case Expr::MLV_ArrayTemporary:
10655     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10656     NeedType = true;
10657     break;
10658   case Expr::MLV_NotObjectType:
10659     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10660     NeedType = true;
10661     break;
10662   case Expr::MLV_LValueCast:
10663     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10664     break;
10665   case Expr::MLV_Valid:
10666     llvm_unreachable("did not take early return for MLV_Valid");
10667   case Expr::MLV_InvalidExpression:
10668   case Expr::MLV_MemberFunction:
10669   case Expr::MLV_ClassTemporary:
10670     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10671     break;
10672   case Expr::MLV_IncompleteType:
10673   case Expr::MLV_IncompleteVoidType:
10674     return S.RequireCompleteType(Loc, E->getType(),
10675              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10676   case Expr::MLV_DuplicateVectorComponents:
10677     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10678     break;
10679   case Expr::MLV_NoSetterProperty:
10680     llvm_unreachable("readonly properties should be processed differently");
10681   case Expr::MLV_InvalidMessageExpression:
10682     DiagID = diag::err_readonly_message_assignment;
10683     break;
10684   case Expr::MLV_SubObjCPropertySetting:
10685     DiagID = diag::err_no_subobject_property_setting;
10686     break;
10687   }
10688 
10689   SourceRange Assign;
10690   if (Loc != OrigLoc)
10691     Assign = SourceRange(OrigLoc, OrigLoc);
10692   if (NeedType)
10693     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10694   else
10695     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10696   return true;
10697 }
10698 
10699 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10700                                          SourceLocation Loc,
10701                                          Sema &Sema) {
10702   // C / C++ fields
10703   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10704   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10705   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10706     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10707       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10708   }
10709 
10710   // Objective-C instance variables
10711   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10712   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10713   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10714     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10715     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10716     if (RL && RR && RL->getDecl() == RR->getDecl())
10717       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10718   }
10719 }
10720 
10721 // C99 6.5.16.1
10722 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10723                                        SourceLocation Loc,
10724                                        QualType CompoundType) {
10725   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10726 
10727   // Verify that LHS is a modifiable lvalue, and emit error if not.
10728   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10729     return QualType();
10730 
10731   QualType LHSType = LHSExpr->getType();
10732   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10733                                              CompoundType;
10734   // OpenCL v1.2 s6.1.1.1 p2:
10735   // The half data type can only be used to declare a pointer to a buffer that
10736   // contains half values
10737   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10738     LHSType->isHalfType()) {
10739     Diag(Loc, diag::err_opencl_half_load_store) << 1
10740         << LHSType.getUnqualifiedType();
10741     return QualType();
10742   }
10743 
10744   AssignConvertType ConvTy;
10745   if (CompoundType.isNull()) {
10746     Expr *RHSCheck = RHS.get();
10747 
10748     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10749 
10750     QualType LHSTy(LHSType);
10751     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10752     if (RHS.isInvalid())
10753       return QualType();
10754     // Special case of NSObject attributes on c-style pointer types.
10755     if (ConvTy == IncompatiblePointer &&
10756         ((Context.isObjCNSObjectType(LHSType) &&
10757           RHSType->isObjCObjectPointerType()) ||
10758          (Context.isObjCNSObjectType(RHSType) &&
10759           LHSType->isObjCObjectPointerType())))
10760       ConvTy = Compatible;
10761 
10762     if (ConvTy == Compatible &&
10763         LHSType->isObjCObjectType())
10764         Diag(Loc, diag::err_objc_object_assignment)
10765           << LHSType;
10766 
10767     // If the RHS is a unary plus or minus, check to see if they = and + are
10768     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10769     // instead of "x += 4".
10770     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10771       RHSCheck = ICE->getSubExpr();
10772     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10773       if ((UO->getOpcode() == UO_Plus ||
10774            UO->getOpcode() == UO_Minus) &&
10775           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10776           // Only if the two operators are exactly adjacent.
10777           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10778           // And there is a space or other character before the subexpr of the
10779           // unary +/-.  We don't want to warn on "x=-1".
10780           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10781           UO->getSubExpr()->getLocStart().isFileID()) {
10782         Diag(Loc, diag::warn_not_compound_assign)
10783           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10784           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10785       }
10786     }
10787 
10788     if (ConvTy == Compatible) {
10789       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10790         // Warn about retain cycles where a block captures the LHS, but
10791         // not if the LHS is a simple variable into which the block is
10792         // being stored...unless that variable can be captured by reference!
10793         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10794         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10795         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10796           checkRetainCycles(LHSExpr, RHS.get());
10797       }
10798 
10799       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10800           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10801         // It is safe to assign a weak reference into a strong variable.
10802         // Although this code can still have problems:
10803         //   id x = self.weakProp;
10804         //   id y = self.weakProp;
10805         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10806         // paths through the function. This should be revisited if
10807         // -Wrepeated-use-of-weak is made flow-sensitive.
10808         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10809         // variable, which will be valid for the current autorelease scope.
10810         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10811                              RHS.get()->getLocStart()))
10812           getCurFunction()->markSafeWeakUse(RHS.get());
10813 
10814       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10815         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10816       }
10817     }
10818   } else {
10819     // Compound assignment "x += y"
10820     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10821   }
10822 
10823   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10824                                RHS.get(), AA_Assigning))
10825     return QualType();
10826 
10827   CheckForNullPointerDereference(*this, LHSExpr);
10828 
10829   // C99 6.5.16p3: The type of an assignment expression is the type of the
10830   // left operand unless the left operand has qualified type, in which case
10831   // it is the unqualified version of the type of the left operand.
10832   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10833   // is converted to the type of the assignment expression (above).
10834   // C++ 5.17p1: the type of the assignment expression is that of its left
10835   // operand.
10836   return (getLangOpts().CPlusPlus
10837           ? LHSType : LHSType.getUnqualifiedType());
10838 }
10839 
10840 // Only ignore explicit casts to void.
10841 static bool IgnoreCommaOperand(const Expr *E) {
10842   E = E->IgnoreParens();
10843 
10844   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10845     if (CE->getCastKind() == CK_ToVoid) {
10846       return true;
10847     }
10848   }
10849 
10850   return false;
10851 }
10852 
10853 // Look for instances where it is likely the comma operator is confused with
10854 // another operator.  There is a whitelist of acceptable expressions for the
10855 // left hand side of the comma operator, otherwise emit a warning.
10856 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10857   // No warnings in macros
10858   if (Loc.isMacroID())
10859     return;
10860 
10861   // Don't warn in template instantiations.
10862   if (inTemplateInstantiation())
10863     return;
10864 
10865   // Scope isn't fine-grained enough to whitelist the specific cases, so
10866   // instead, skip more than needed, then call back into here with the
10867   // CommaVisitor in SemaStmt.cpp.
10868   // The whitelisted locations are the initialization and increment portions
10869   // of a for loop.  The additional checks are on the condition of
10870   // if statements, do/while loops, and for loops.
10871   const unsigned ForIncrementFlags =
10872       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10873   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10874   const unsigned ScopeFlags = getCurScope()->getFlags();
10875   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10876       (ScopeFlags & ForInitFlags) == ForInitFlags)
10877     return;
10878 
10879   // If there are multiple comma operators used together, get the RHS of the
10880   // of the comma operator as the LHS.
10881   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10882     if (BO->getOpcode() != BO_Comma)
10883       break;
10884     LHS = BO->getRHS();
10885   }
10886 
10887   // Only allow some expressions on LHS to not warn.
10888   if (IgnoreCommaOperand(LHS))
10889     return;
10890 
10891   Diag(Loc, diag::warn_comma_operator);
10892   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10893       << LHS->getSourceRange()
10894       << FixItHint::CreateInsertion(LHS->getLocStart(),
10895                                     LangOpts.CPlusPlus ? "static_cast<void>("
10896                                                        : "(void)(")
10897       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10898                                     ")");
10899 }
10900 
10901 // C99 6.5.17
10902 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10903                                    SourceLocation Loc) {
10904   LHS = S.CheckPlaceholderExpr(LHS.get());
10905   RHS = S.CheckPlaceholderExpr(RHS.get());
10906   if (LHS.isInvalid() || RHS.isInvalid())
10907     return QualType();
10908 
10909   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10910   // operands, but not unary promotions.
10911   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10912 
10913   // So we treat the LHS as a ignored value, and in C++ we allow the
10914   // containing site to determine what should be done with the RHS.
10915   LHS = S.IgnoredValueConversions(LHS.get());
10916   if (LHS.isInvalid())
10917     return QualType();
10918 
10919   S.DiagnoseUnusedExprResult(LHS.get());
10920 
10921   if (!S.getLangOpts().CPlusPlus) {
10922     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10923     if (RHS.isInvalid())
10924       return QualType();
10925     if (!RHS.get()->getType()->isVoidType())
10926       S.RequireCompleteType(Loc, RHS.get()->getType(),
10927                             diag::err_incomplete_type);
10928   }
10929 
10930   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10931     S.DiagnoseCommaOperator(LHS.get(), Loc);
10932 
10933   return RHS.get()->getType();
10934 }
10935 
10936 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10937 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10938 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10939                                                ExprValueKind &VK,
10940                                                ExprObjectKind &OK,
10941                                                SourceLocation OpLoc,
10942                                                bool IsInc, bool IsPrefix) {
10943   if (Op->isTypeDependent())
10944     return S.Context.DependentTy;
10945 
10946   QualType ResType = Op->getType();
10947   // Atomic types can be used for increment / decrement where the non-atomic
10948   // versions can, so ignore the _Atomic() specifier for the purpose of
10949   // checking.
10950   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10951     ResType = ResAtomicType->getValueType();
10952 
10953   assert(!ResType.isNull() && "no type for increment/decrement expression");
10954 
10955   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10956     // Decrement of bool is not allowed.
10957     if (!IsInc) {
10958       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10959       return QualType();
10960     }
10961     // Increment of bool sets it to true, but is deprecated.
10962     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
10963                                               : diag::warn_increment_bool)
10964       << Op->getSourceRange();
10965   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10966     // Error on enum increments and decrements in C++ mode
10967     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10968     return QualType();
10969   } else if (ResType->isRealType()) {
10970     // OK!
10971   } else if (ResType->isPointerType()) {
10972     // C99 6.5.2.4p2, 6.5.6p2
10973     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10974       return QualType();
10975   } else if (ResType->isObjCObjectPointerType()) {
10976     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10977     // Otherwise, we just need a complete type.
10978     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10979         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10980       return QualType();
10981   } else if (ResType->isAnyComplexType()) {
10982     // C99 does not support ++/-- on complex types, we allow as an extension.
10983     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10984       << ResType << Op->getSourceRange();
10985   } else if (ResType->isPlaceholderType()) {
10986     ExprResult PR = S.CheckPlaceholderExpr(Op);
10987     if (PR.isInvalid()) return QualType();
10988     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10989                                           IsInc, IsPrefix);
10990   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10991     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10992   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10993              (ResType->getAs<VectorType>()->getVectorKind() !=
10994               VectorType::AltiVecBool)) {
10995     // The z vector extensions allow ++ and -- for non-bool vectors.
10996   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10997             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10998     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10999   } else {
11000     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11001       << ResType << int(IsInc) << Op->getSourceRange();
11002     return QualType();
11003   }
11004   // At this point, we know we have a real, complex or pointer type.
11005   // Now make sure the operand is a modifiable lvalue.
11006   if (CheckForModifiableLvalue(Op, OpLoc, S))
11007     return QualType();
11008   // In C++, a prefix increment is the same type as the operand. Otherwise
11009   // (in C or with postfix), the increment is the unqualified type of the
11010   // operand.
11011   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11012     VK = VK_LValue;
11013     OK = Op->getObjectKind();
11014     return ResType;
11015   } else {
11016     VK = VK_RValue;
11017     return ResType.getUnqualifiedType();
11018   }
11019 }
11020 
11021 
11022 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11023 /// This routine allows us to typecheck complex/recursive expressions
11024 /// where the declaration is needed for type checking. We only need to
11025 /// handle cases when the expression references a function designator
11026 /// or is an lvalue. Here are some examples:
11027 ///  - &(x) => x
11028 ///  - &*****f => f for f a function designator.
11029 ///  - &s.xx => s
11030 ///  - &s.zz[1].yy -> s, if zz is an array
11031 ///  - *(x + 1) -> x, if x is an array
11032 ///  - &"123"[2] -> 0
11033 ///  - & __real__ x -> x
11034 static ValueDecl *getPrimaryDecl(Expr *E) {
11035   switch (E->getStmtClass()) {
11036   case Stmt::DeclRefExprClass:
11037     return cast<DeclRefExpr>(E)->getDecl();
11038   case Stmt::MemberExprClass:
11039     // If this is an arrow operator, the address is an offset from
11040     // the base's value, so the object the base refers to is
11041     // irrelevant.
11042     if (cast<MemberExpr>(E)->isArrow())
11043       return nullptr;
11044     // Otherwise, the expression refers to a part of the base
11045     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11046   case Stmt::ArraySubscriptExprClass: {
11047     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11048     // promotion of register arrays earlier.
11049     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11050     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11051       if (ICE->getSubExpr()->getType()->isArrayType())
11052         return getPrimaryDecl(ICE->getSubExpr());
11053     }
11054     return nullptr;
11055   }
11056   case Stmt::UnaryOperatorClass: {
11057     UnaryOperator *UO = cast<UnaryOperator>(E);
11058 
11059     switch(UO->getOpcode()) {
11060     case UO_Real:
11061     case UO_Imag:
11062     case UO_Extension:
11063       return getPrimaryDecl(UO->getSubExpr());
11064     default:
11065       return nullptr;
11066     }
11067   }
11068   case Stmt::ParenExprClass:
11069     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11070   case Stmt::ImplicitCastExprClass:
11071     // If the result of an implicit cast is an l-value, we care about
11072     // the sub-expression; otherwise, the result here doesn't matter.
11073     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11074   default:
11075     return nullptr;
11076   }
11077 }
11078 
11079 namespace {
11080   enum {
11081     AO_Bit_Field = 0,
11082     AO_Vector_Element = 1,
11083     AO_Property_Expansion = 2,
11084     AO_Register_Variable = 3,
11085     AO_No_Error = 4
11086   };
11087 }
11088 /// \brief Diagnose invalid operand for address of operations.
11089 ///
11090 /// \param Type The type of operand which cannot have its address taken.
11091 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11092                                          Expr *E, unsigned Type) {
11093   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11094 }
11095 
11096 /// CheckAddressOfOperand - The operand of & must be either a function
11097 /// designator or an lvalue designating an object. If it is an lvalue, the
11098 /// object cannot be declared with storage class register or be a bit field.
11099 /// Note: The usual conversions are *not* applied to the operand of the &
11100 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11101 /// In C++, the operand might be an overloaded function name, in which case
11102 /// we allow the '&' but retain the overloaded-function type.
11103 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11104   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11105     if (PTy->getKind() == BuiltinType::Overload) {
11106       Expr *E = OrigOp.get()->IgnoreParens();
11107       if (!isa<OverloadExpr>(E)) {
11108         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11109         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11110           << OrigOp.get()->getSourceRange();
11111         return QualType();
11112       }
11113 
11114       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11115       if (isa<UnresolvedMemberExpr>(Ovl))
11116         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11117           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11118             << OrigOp.get()->getSourceRange();
11119           return QualType();
11120         }
11121 
11122       return Context.OverloadTy;
11123     }
11124 
11125     if (PTy->getKind() == BuiltinType::UnknownAny)
11126       return Context.UnknownAnyTy;
11127 
11128     if (PTy->getKind() == BuiltinType::BoundMember) {
11129       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11130         << OrigOp.get()->getSourceRange();
11131       return QualType();
11132     }
11133 
11134     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11135     if (OrigOp.isInvalid()) return QualType();
11136   }
11137 
11138   if (OrigOp.get()->isTypeDependent())
11139     return Context.DependentTy;
11140 
11141   assert(!OrigOp.get()->getType()->isPlaceholderType());
11142 
11143   // Make sure to ignore parentheses in subsequent checks
11144   Expr *op = OrigOp.get()->IgnoreParens();
11145 
11146   // In OpenCL captures for blocks called as lambda functions
11147   // are located in the private address space. Blocks used in
11148   // enqueue_kernel can be located in a different address space
11149   // depending on a vendor implementation. Thus preventing
11150   // taking an address of the capture to avoid invalid AS casts.
11151   if (LangOpts.OpenCL) {
11152     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11153     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11154       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11155       return QualType();
11156     }
11157   }
11158 
11159   if (getLangOpts().C99) {
11160     // Implement C99-only parts of addressof rules.
11161     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11162       if (uOp->getOpcode() == UO_Deref)
11163         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11164         // (assuming the deref expression is valid).
11165         return uOp->getSubExpr()->getType();
11166     }
11167     // Technically, there should be a check for array subscript
11168     // expressions here, but the result of one is always an lvalue anyway.
11169   }
11170   ValueDecl *dcl = getPrimaryDecl(op);
11171 
11172   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11173     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11174                                            op->getLocStart()))
11175       return QualType();
11176 
11177   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11178   unsigned AddressOfError = AO_No_Error;
11179 
11180   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11181     bool sfinae = (bool)isSFINAEContext();
11182     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11183                                   : diag::ext_typecheck_addrof_temporary)
11184       << op->getType() << op->getSourceRange();
11185     if (sfinae)
11186       return QualType();
11187     // Materialize the temporary as an lvalue so that we can take its address.
11188     OrigOp = op =
11189         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11190   } else if (isa<ObjCSelectorExpr>(op)) {
11191     return Context.getPointerType(op->getType());
11192   } else if (lval == Expr::LV_MemberFunction) {
11193     // If it's an instance method, make a member pointer.
11194     // The expression must have exactly the form &A::foo.
11195 
11196     // If the underlying expression isn't a decl ref, give up.
11197     if (!isa<DeclRefExpr>(op)) {
11198       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11199         << OrigOp.get()->getSourceRange();
11200       return QualType();
11201     }
11202     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11203     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11204 
11205     // The id-expression was parenthesized.
11206     if (OrigOp.get() != DRE) {
11207       Diag(OpLoc, diag::err_parens_pointer_member_function)
11208         << OrigOp.get()->getSourceRange();
11209 
11210     // The method was named without a qualifier.
11211     } else if (!DRE->getQualifier()) {
11212       if (MD->getParent()->getName().empty())
11213         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11214           << op->getSourceRange();
11215       else {
11216         SmallString<32> Str;
11217         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11218         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11219           << op->getSourceRange()
11220           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11221       }
11222     }
11223 
11224     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11225     if (isa<CXXDestructorDecl>(MD))
11226       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11227 
11228     QualType MPTy = Context.getMemberPointerType(
11229         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11230     // Under the MS ABI, lock down the inheritance model now.
11231     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11232       (void)isCompleteType(OpLoc, MPTy);
11233     return MPTy;
11234   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11235     // C99 6.5.3.2p1
11236     // The operand must be either an l-value or a function designator
11237     if (!op->getType()->isFunctionType()) {
11238       // Use a special diagnostic for loads from property references.
11239       if (isa<PseudoObjectExpr>(op)) {
11240         AddressOfError = AO_Property_Expansion;
11241       } else {
11242         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11243           << op->getType() << op->getSourceRange();
11244         return QualType();
11245       }
11246     }
11247   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11248     // The operand cannot be a bit-field
11249     AddressOfError = AO_Bit_Field;
11250   } else if (op->getObjectKind() == OK_VectorComponent) {
11251     // The operand cannot be an element of a vector
11252     AddressOfError = AO_Vector_Element;
11253   } else if (dcl) { // C99 6.5.3.2p1
11254     // We have an lvalue with a decl. Make sure the decl is not declared
11255     // with the register storage-class specifier.
11256     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11257       // in C++ it is not error to take address of a register
11258       // variable (c++03 7.1.1P3)
11259       if (vd->getStorageClass() == SC_Register &&
11260           !getLangOpts().CPlusPlus) {
11261         AddressOfError = AO_Register_Variable;
11262       }
11263     } else if (isa<MSPropertyDecl>(dcl)) {
11264       AddressOfError = AO_Property_Expansion;
11265     } else if (isa<FunctionTemplateDecl>(dcl)) {
11266       return Context.OverloadTy;
11267     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11268       // Okay: we can take the address of a field.
11269       // Could be a pointer to member, though, if there is an explicit
11270       // scope qualifier for the class.
11271       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11272         DeclContext *Ctx = dcl->getDeclContext();
11273         if (Ctx && Ctx->isRecord()) {
11274           if (dcl->getType()->isReferenceType()) {
11275             Diag(OpLoc,
11276                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11277               << dcl->getDeclName() << dcl->getType();
11278             return QualType();
11279           }
11280 
11281           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11282             Ctx = Ctx->getParent();
11283 
11284           QualType MPTy = Context.getMemberPointerType(
11285               op->getType(),
11286               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11287           // Under the MS ABI, lock down the inheritance model now.
11288           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11289             (void)isCompleteType(OpLoc, MPTy);
11290           return MPTy;
11291         }
11292       }
11293     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11294                !isa<BindingDecl>(dcl))
11295       llvm_unreachable("Unknown/unexpected decl type");
11296   }
11297 
11298   if (AddressOfError != AO_No_Error) {
11299     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11300     return QualType();
11301   }
11302 
11303   if (lval == Expr::LV_IncompleteVoidType) {
11304     // Taking the address of a void variable is technically illegal, but we
11305     // allow it in cases which are otherwise valid.
11306     // Example: "extern void x; void* y = &x;".
11307     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11308   }
11309 
11310   // If the operand has type "type", the result has type "pointer to type".
11311   if (op->getType()->isObjCObjectType())
11312     return Context.getObjCObjectPointerType(op->getType());
11313 
11314   CheckAddressOfPackedMember(op);
11315 
11316   return Context.getPointerType(op->getType());
11317 }
11318 
11319 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11320   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11321   if (!DRE)
11322     return;
11323   const Decl *D = DRE->getDecl();
11324   if (!D)
11325     return;
11326   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11327   if (!Param)
11328     return;
11329   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11330     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11331       return;
11332   if (FunctionScopeInfo *FD = S.getCurFunction())
11333     if (!FD->ModifiedNonNullParams.count(Param))
11334       FD->ModifiedNonNullParams.insert(Param);
11335 }
11336 
11337 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11338 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11339                                         SourceLocation OpLoc) {
11340   if (Op->isTypeDependent())
11341     return S.Context.DependentTy;
11342 
11343   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11344   if (ConvResult.isInvalid())
11345     return QualType();
11346   Op = ConvResult.get();
11347   QualType OpTy = Op->getType();
11348   QualType Result;
11349 
11350   if (isa<CXXReinterpretCastExpr>(Op)) {
11351     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11352     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11353                                      Op->getSourceRange());
11354   }
11355 
11356   if (const PointerType *PT = OpTy->getAs<PointerType>())
11357   {
11358     Result = PT->getPointeeType();
11359   }
11360   else if (const ObjCObjectPointerType *OPT =
11361              OpTy->getAs<ObjCObjectPointerType>())
11362     Result = OPT->getPointeeType();
11363   else {
11364     ExprResult PR = S.CheckPlaceholderExpr(Op);
11365     if (PR.isInvalid()) return QualType();
11366     if (PR.get() != Op)
11367       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11368   }
11369 
11370   if (Result.isNull()) {
11371     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11372       << OpTy << Op->getSourceRange();
11373     return QualType();
11374   }
11375 
11376   // Note that per both C89 and C99, indirection is always legal, even if Result
11377   // is an incomplete type or void.  It would be possible to warn about
11378   // dereferencing a void pointer, but it's completely well-defined, and such a
11379   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11380   // for pointers to 'void' but is fine for any other pointer type:
11381   //
11382   // C++ [expr.unary.op]p1:
11383   //   [...] the expression to which [the unary * operator] is applied shall
11384   //   be a pointer to an object type, or a pointer to a function type
11385   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11386     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11387       << OpTy << Op->getSourceRange();
11388 
11389   // Dereferences are usually l-values...
11390   VK = VK_LValue;
11391 
11392   // ...except that certain expressions are never l-values in C.
11393   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11394     VK = VK_RValue;
11395 
11396   return Result;
11397 }
11398 
11399 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11400   BinaryOperatorKind Opc;
11401   switch (Kind) {
11402   default: llvm_unreachable("Unknown binop!");
11403   case tok::periodstar:           Opc = BO_PtrMemD; break;
11404   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11405   case tok::star:                 Opc = BO_Mul; break;
11406   case tok::slash:                Opc = BO_Div; break;
11407   case tok::percent:              Opc = BO_Rem; break;
11408   case tok::plus:                 Opc = BO_Add; break;
11409   case tok::minus:                Opc = BO_Sub; break;
11410   case tok::lessless:             Opc = BO_Shl; break;
11411   case tok::greatergreater:       Opc = BO_Shr; break;
11412   case tok::lessequal:            Opc = BO_LE; break;
11413   case tok::less:                 Opc = BO_LT; break;
11414   case tok::greaterequal:         Opc = BO_GE; break;
11415   case tok::greater:              Opc = BO_GT; break;
11416   case tok::exclaimequal:         Opc = BO_NE; break;
11417   case tok::equalequal:           Opc = BO_EQ; break;
11418   case tok::spaceship:            Opc = BO_Cmp; break;
11419   case tok::amp:                  Opc = BO_And; break;
11420   case tok::caret:                Opc = BO_Xor; break;
11421   case tok::pipe:                 Opc = BO_Or; break;
11422   case tok::ampamp:               Opc = BO_LAnd; break;
11423   case tok::pipepipe:             Opc = BO_LOr; break;
11424   case tok::equal:                Opc = BO_Assign; break;
11425   case tok::starequal:            Opc = BO_MulAssign; break;
11426   case tok::slashequal:           Opc = BO_DivAssign; break;
11427   case tok::percentequal:         Opc = BO_RemAssign; break;
11428   case tok::plusequal:            Opc = BO_AddAssign; break;
11429   case tok::minusequal:           Opc = BO_SubAssign; break;
11430   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11431   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11432   case tok::ampequal:             Opc = BO_AndAssign; break;
11433   case tok::caretequal:           Opc = BO_XorAssign; break;
11434   case tok::pipeequal:            Opc = BO_OrAssign; break;
11435   case tok::comma:                Opc = BO_Comma; break;
11436   }
11437   return Opc;
11438 }
11439 
11440 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11441   tok::TokenKind Kind) {
11442   UnaryOperatorKind Opc;
11443   switch (Kind) {
11444   default: llvm_unreachable("Unknown unary op!");
11445   case tok::plusplus:     Opc = UO_PreInc; break;
11446   case tok::minusminus:   Opc = UO_PreDec; break;
11447   case tok::amp:          Opc = UO_AddrOf; break;
11448   case tok::star:         Opc = UO_Deref; break;
11449   case tok::plus:         Opc = UO_Plus; break;
11450   case tok::minus:        Opc = UO_Minus; break;
11451   case tok::tilde:        Opc = UO_Not; break;
11452   case tok::exclaim:      Opc = UO_LNot; break;
11453   case tok::kw___real:    Opc = UO_Real; break;
11454   case tok::kw___imag:    Opc = UO_Imag; break;
11455   case tok::kw___extension__: Opc = UO_Extension; break;
11456   }
11457   return Opc;
11458 }
11459 
11460 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11461 /// This warning is only emitted for builtin assignment operations. It is also
11462 /// suppressed in the event of macro expansions.
11463 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11464                                    SourceLocation OpLoc) {
11465   if (S.inTemplateInstantiation())
11466     return;
11467   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11468     return;
11469   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11470   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11471   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11472   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11473   if (!LHSDeclRef || !RHSDeclRef ||
11474       LHSDeclRef->getLocation().isMacroID() ||
11475       RHSDeclRef->getLocation().isMacroID())
11476     return;
11477   const ValueDecl *LHSDecl =
11478     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11479   const ValueDecl *RHSDecl =
11480     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11481   if (LHSDecl != RHSDecl)
11482     return;
11483   if (LHSDecl->getType().isVolatileQualified())
11484     return;
11485   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11486     if (RefTy->getPointeeType().isVolatileQualified())
11487       return;
11488 
11489   S.Diag(OpLoc, diag::warn_self_assignment)
11490       << LHSDeclRef->getType()
11491       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11492 }
11493 
11494 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11495 /// is usually indicative of introspection within the Objective-C pointer.
11496 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11497                                           SourceLocation OpLoc) {
11498   if (!S.getLangOpts().ObjC1)
11499     return;
11500 
11501   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11502   const Expr *LHS = L.get();
11503   const Expr *RHS = R.get();
11504 
11505   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11506     ObjCPointerExpr = LHS;
11507     OtherExpr = RHS;
11508   }
11509   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11510     ObjCPointerExpr = RHS;
11511     OtherExpr = LHS;
11512   }
11513 
11514   // This warning is deliberately made very specific to reduce false
11515   // positives with logic that uses '&' for hashing.  This logic mainly
11516   // looks for code trying to introspect into tagged pointers, which
11517   // code should generally never do.
11518   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11519     unsigned Diag = diag::warn_objc_pointer_masking;
11520     // Determine if we are introspecting the result of performSelectorXXX.
11521     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11522     // Special case messages to -performSelector and friends, which
11523     // can return non-pointer values boxed in a pointer value.
11524     // Some clients may wish to silence warnings in this subcase.
11525     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11526       Selector S = ME->getSelector();
11527       StringRef SelArg0 = S.getNameForSlot(0);
11528       if (SelArg0.startswith("performSelector"))
11529         Diag = diag::warn_objc_pointer_masking_performSelector;
11530     }
11531 
11532     S.Diag(OpLoc, Diag)
11533       << ObjCPointerExpr->getSourceRange();
11534   }
11535 }
11536 
11537 static NamedDecl *getDeclFromExpr(Expr *E) {
11538   if (!E)
11539     return nullptr;
11540   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11541     return DRE->getDecl();
11542   if (auto *ME = dyn_cast<MemberExpr>(E))
11543     return ME->getMemberDecl();
11544   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11545     return IRE->getDecl();
11546   return nullptr;
11547 }
11548 
11549 // This helper function promotes a binary operator's operands (which are of a
11550 // half vector type) to a vector of floats and then truncates the result to
11551 // a vector of either half or short.
11552 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11553                                       BinaryOperatorKind Opc, QualType ResultTy,
11554                                       ExprValueKind VK, ExprObjectKind OK,
11555                                       bool IsCompAssign, SourceLocation OpLoc,
11556                                       FPOptions FPFeatures) {
11557   auto &Context = S.getASTContext();
11558   assert((isVector(ResultTy, Context.HalfTy) ||
11559           isVector(ResultTy, Context.ShortTy)) &&
11560          "Result must be a vector of half or short");
11561   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11562          isVector(RHS.get()->getType(), Context.HalfTy) &&
11563          "both operands expected to be a half vector");
11564 
11565   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11566   QualType BinOpResTy = RHS.get()->getType();
11567 
11568   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11569   // change BinOpResTy to a vector of ints.
11570   if (isVector(ResultTy, Context.ShortTy))
11571     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11572 
11573   if (IsCompAssign)
11574     return new (Context) CompoundAssignOperator(
11575         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11576         OpLoc, FPFeatures);
11577 
11578   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11579   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11580                                           VK, OK, OpLoc, FPFeatures);
11581   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11582 }
11583 
11584 static std::pair<ExprResult, ExprResult>
11585 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11586                            Expr *RHSExpr) {
11587   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11588   if (!S.getLangOpts().CPlusPlus) {
11589     // C cannot handle TypoExpr nodes on either side of a binop because it
11590     // doesn't handle dependent types properly, so make sure any TypoExprs have
11591     // been dealt with before checking the operands.
11592     LHS = S.CorrectDelayedTyposInExpr(LHS);
11593     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11594       if (Opc != BO_Assign)
11595         return ExprResult(E);
11596       // Avoid correcting the RHS to the same Expr as the LHS.
11597       Decl *D = getDeclFromExpr(E);
11598       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11599     });
11600   }
11601   return std::make_pair(LHS, RHS);
11602 }
11603 
11604 /// Returns true if conversion between vectors of halfs and vectors of floats
11605 /// is needed.
11606 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11607                                      QualType SrcType) {
11608   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11609          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11610          isVector(SrcType, Ctx.HalfTy);
11611 }
11612 
11613 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11614 /// operator @p Opc at location @c TokLoc. This routine only supports
11615 /// built-in operations; ActOnBinOp handles overloaded operators.
11616 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11617                                     BinaryOperatorKind Opc,
11618                                     Expr *LHSExpr, Expr *RHSExpr) {
11619   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11620     // The syntax only allows initializer lists on the RHS of assignment,
11621     // so we don't need to worry about accepting invalid code for
11622     // non-assignment operators.
11623     // C++11 5.17p9:
11624     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11625     //   of x = {} is x = T().
11626     InitializationKind Kind = InitializationKind::CreateDirectList(
11627         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
11628     InitializedEntity Entity =
11629         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11630     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11631     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11632     if (Init.isInvalid())
11633       return Init;
11634     RHSExpr = Init.get();
11635   }
11636 
11637   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11638   QualType ResultTy;     // Result type of the binary operator.
11639   // The following two variables are used for compound assignment operators
11640   QualType CompLHSTy;    // Type of LHS after promotions for computation
11641   QualType CompResultTy; // Type of computation result
11642   ExprValueKind VK = VK_RValue;
11643   ExprObjectKind OK = OK_Ordinary;
11644   bool ConvertHalfVec = false;
11645 
11646   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11647   if (!LHS.isUsable() || !RHS.isUsable())
11648     return ExprError();
11649 
11650   if (getLangOpts().OpenCL) {
11651     QualType LHSTy = LHSExpr->getType();
11652     QualType RHSTy = RHSExpr->getType();
11653     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11654     // the ATOMIC_VAR_INIT macro.
11655     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11656       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11657       if (BO_Assign == Opc)
11658         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11659       else
11660         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11661       return ExprError();
11662     }
11663 
11664     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11665     // only with a builtin functions and therefore should be disallowed here.
11666     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11667         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11668         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11669         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11670       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11671       return ExprError();
11672     }
11673   }
11674 
11675   switch (Opc) {
11676   case BO_Assign:
11677     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11678     if (getLangOpts().CPlusPlus &&
11679         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11680       VK = LHS.get()->getValueKind();
11681       OK = LHS.get()->getObjectKind();
11682     }
11683     if (!ResultTy.isNull()) {
11684       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11685       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11686     }
11687     RecordModifiableNonNullParam(*this, LHS.get());
11688     break;
11689   case BO_PtrMemD:
11690   case BO_PtrMemI:
11691     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11692                                             Opc == BO_PtrMemI);
11693     break;
11694   case BO_Mul:
11695   case BO_Div:
11696     ConvertHalfVec = true;
11697     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11698                                            Opc == BO_Div);
11699     break;
11700   case BO_Rem:
11701     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11702     break;
11703   case BO_Add:
11704     ConvertHalfVec = true;
11705     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11706     break;
11707   case BO_Sub:
11708     ConvertHalfVec = true;
11709     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11710     break;
11711   case BO_Shl:
11712   case BO_Shr:
11713     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11714     break;
11715   case BO_LE:
11716   case BO_LT:
11717   case BO_GE:
11718   case BO_GT:
11719     ConvertHalfVec = true;
11720     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11721     break;
11722   case BO_EQ:
11723   case BO_NE:
11724     ConvertHalfVec = true;
11725     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11726     break;
11727   case BO_Cmp:
11728     // FIXME: Implement proper semantic checking of '<=>'.
11729     ConvertHalfVec = true;
11730     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11731     if (!ResultTy.isNull())
11732       ResultTy = Context.VoidTy;
11733     break;
11734   case BO_And:
11735     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11736     LLVM_FALLTHROUGH;
11737   case BO_Xor:
11738   case BO_Or:
11739     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11740     break;
11741   case BO_LAnd:
11742   case BO_LOr:
11743     ConvertHalfVec = true;
11744     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11745     break;
11746   case BO_MulAssign:
11747   case BO_DivAssign:
11748     ConvertHalfVec = true;
11749     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11750                                                Opc == BO_DivAssign);
11751     CompLHSTy = CompResultTy;
11752     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11753       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11754     break;
11755   case BO_RemAssign:
11756     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11757     CompLHSTy = CompResultTy;
11758     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11759       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11760     break;
11761   case BO_AddAssign:
11762     ConvertHalfVec = true;
11763     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11764     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11765       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11766     break;
11767   case BO_SubAssign:
11768     ConvertHalfVec = true;
11769     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11770     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11771       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11772     break;
11773   case BO_ShlAssign:
11774   case BO_ShrAssign:
11775     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11776     CompLHSTy = CompResultTy;
11777     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11778       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11779     break;
11780   case BO_AndAssign:
11781   case BO_OrAssign: // fallthrough
11782     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11783     LLVM_FALLTHROUGH;
11784   case BO_XorAssign:
11785     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11786     CompLHSTy = CompResultTy;
11787     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11788       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11789     break;
11790   case BO_Comma:
11791     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11792     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11793       VK = RHS.get()->getValueKind();
11794       OK = RHS.get()->getObjectKind();
11795     }
11796     break;
11797   }
11798   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11799     return ExprError();
11800 
11801   // Some of the binary operations require promoting operands of half vector to
11802   // float vectors and truncating the result back to half vector. For now, we do
11803   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
11804   // arm64).
11805   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
11806          isVector(LHS.get()->getType(), Context.HalfTy) &&
11807          "both sides are half vectors or neither sides are");
11808   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
11809                                             LHS.get()->getType());
11810 
11811   // Check for array bounds violations for both sides of the BinaryOperator
11812   CheckArrayAccess(LHS.get());
11813   CheckArrayAccess(RHS.get());
11814 
11815   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11816     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11817                                                  &Context.Idents.get("object_setClass"),
11818                                                  SourceLocation(), LookupOrdinaryName);
11819     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11820       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11821       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11822       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11823       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11824       FixItHint::CreateInsertion(RHSLocEnd, ")");
11825     }
11826     else
11827       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11828   }
11829   else if (const ObjCIvarRefExpr *OIRE =
11830            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11831     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11832 
11833   // Opc is not a compound assignment if CompResultTy is null.
11834   if (CompResultTy.isNull()) {
11835     if (ConvertHalfVec)
11836       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
11837                                  OpLoc, FPFeatures);
11838     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11839                                         OK, OpLoc, FPFeatures);
11840   }
11841 
11842   // Handle compound assignments.
11843   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11844       OK_ObjCProperty) {
11845     VK = VK_LValue;
11846     OK = LHS.get()->getObjectKind();
11847   }
11848 
11849   if (ConvertHalfVec)
11850     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
11851                                OpLoc, FPFeatures);
11852 
11853   return new (Context) CompoundAssignOperator(
11854       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11855       OpLoc, FPFeatures);
11856 }
11857 
11858 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11859 /// operators are mixed in a way that suggests that the programmer forgot that
11860 /// comparison operators have higher precedence. The most typical example of
11861 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11862 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11863                                       SourceLocation OpLoc, Expr *LHSExpr,
11864                                       Expr *RHSExpr) {
11865   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11866   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11867 
11868   // Check that one of the sides is a comparison operator and the other isn't.
11869   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11870   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11871   if (isLeftComp == isRightComp)
11872     return;
11873 
11874   // Bitwise operations are sometimes used as eager logical ops.
11875   // Don't diagnose this.
11876   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11877   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11878   if (isLeftBitwise || isRightBitwise)
11879     return;
11880 
11881   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11882                                                    OpLoc)
11883                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11884   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11885   SourceRange ParensRange = isLeftComp ?
11886       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11887     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11888 
11889   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11890     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11891   SuggestParentheses(Self, OpLoc,
11892     Self.PDiag(diag::note_precedence_silence) << OpStr,
11893     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11894   SuggestParentheses(Self, OpLoc,
11895     Self.PDiag(diag::note_precedence_bitwise_first)
11896       << BinaryOperator::getOpcodeStr(Opc),
11897     ParensRange);
11898 }
11899 
11900 /// \brief It accepts a '&&' expr that is inside a '||' one.
11901 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11902 /// in parentheses.
11903 static void
11904 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11905                                        BinaryOperator *Bop) {
11906   assert(Bop->getOpcode() == BO_LAnd);
11907   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11908       << Bop->getSourceRange() << OpLoc;
11909   SuggestParentheses(Self, Bop->getOperatorLoc(),
11910     Self.PDiag(diag::note_precedence_silence)
11911       << Bop->getOpcodeStr(),
11912     Bop->getSourceRange());
11913 }
11914 
11915 /// \brief Returns true if the given expression can be evaluated as a constant
11916 /// 'true'.
11917 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11918   bool Res;
11919   return !E->isValueDependent() &&
11920          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11921 }
11922 
11923 /// \brief Returns true if the given expression can be evaluated as a constant
11924 /// 'false'.
11925 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11926   bool Res;
11927   return !E->isValueDependent() &&
11928          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11929 }
11930 
11931 /// \brief Look for '&&' in the left hand of a '||' expr.
11932 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11933                                              Expr *LHSExpr, Expr *RHSExpr) {
11934   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11935     if (Bop->getOpcode() == BO_LAnd) {
11936       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11937       if (EvaluatesAsFalse(S, RHSExpr))
11938         return;
11939       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11940       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11941         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11942     } else if (Bop->getOpcode() == BO_LOr) {
11943       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11944         // If it's "a || b && 1 || c" we didn't warn earlier for
11945         // "a || b && 1", but warn now.
11946         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11947           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11948       }
11949     }
11950   }
11951 }
11952 
11953 /// \brief Look for '&&' in the right hand of a '||' expr.
11954 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11955                                              Expr *LHSExpr, Expr *RHSExpr) {
11956   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11957     if (Bop->getOpcode() == BO_LAnd) {
11958       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11959       if (EvaluatesAsFalse(S, LHSExpr))
11960         return;
11961       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11962       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11963         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11964     }
11965   }
11966 }
11967 
11968 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11969 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11970 /// the '&' expression in parentheses.
11971 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11972                                          SourceLocation OpLoc, Expr *SubExpr) {
11973   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11974     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11975       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11976         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11977         << Bop->getSourceRange() << OpLoc;
11978       SuggestParentheses(S, Bop->getOperatorLoc(),
11979         S.PDiag(diag::note_precedence_silence)
11980           << Bop->getOpcodeStr(),
11981         Bop->getSourceRange());
11982     }
11983   }
11984 }
11985 
11986 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11987                                     Expr *SubExpr, StringRef Shift) {
11988   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11989     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11990       StringRef Op = Bop->getOpcodeStr();
11991       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11992           << Bop->getSourceRange() << OpLoc << Shift << Op;
11993       SuggestParentheses(S, Bop->getOperatorLoc(),
11994           S.PDiag(diag::note_precedence_silence) << Op,
11995           Bop->getSourceRange());
11996     }
11997   }
11998 }
11999 
12000 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12001                                  Expr *LHSExpr, Expr *RHSExpr) {
12002   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12003   if (!OCE)
12004     return;
12005 
12006   FunctionDecl *FD = OCE->getDirectCallee();
12007   if (!FD || !FD->isOverloadedOperator())
12008     return;
12009 
12010   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12011   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12012     return;
12013 
12014   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12015       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12016       << (Kind == OO_LessLess);
12017   SuggestParentheses(S, OCE->getOperatorLoc(),
12018                      S.PDiag(diag::note_precedence_silence)
12019                          << (Kind == OO_LessLess ? "<<" : ">>"),
12020                      OCE->getSourceRange());
12021   SuggestParentheses(S, OpLoc,
12022                      S.PDiag(diag::note_evaluate_comparison_first),
12023                      SourceRange(OCE->getArg(1)->getLocStart(),
12024                                  RHSExpr->getLocEnd()));
12025 }
12026 
12027 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12028 /// precedence.
12029 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12030                                     SourceLocation OpLoc, Expr *LHSExpr,
12031                                     Expr *RHSExpr){
12032   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12033   if (BinaryOperator::isBitwiseOp(Opc))
12034     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12035 
12036   // Diagnose "arg1 & arg2 | arg3"
12037   if ((Opc == BO_Or || Opc == BO_Xor) &&
12038       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12039     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12040     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12041   }
12042 
12043   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12044   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12045   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12046     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12047     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12048   }
12049 
12050   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12051       || Opc == BO_Shr) {
12052     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12053     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12054     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12055   }
12056 
12057   // Warn on overloaded shift operators and comparisons, such as:
12058   // cout << 5 == 4;
12059   if (BinaryOperator::isComparisonOp(Opc))
12060     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12061 }
12062 
12063 // Binary Operators.  'Tok' is the token for the operator.
12064 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12065                             tok::TokenKind Kind,
12066                             Expr *LHSExpr, Expr *RHSExpr) {
12067   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12068   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12069   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12070 
12071   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12072   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12073 
12074   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12075 }
12076 
12077 /// Build an overloaded binary operator expression in the given scope.
12078 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12079                                        BinaryOperatorKind Opc,
12080                                        Expr *LHS, Expr *RHS) {
12081   // Find all of the overloaded operators visible from this
12082   // point. We perform both an operator-name lookup from the local
12083   // scope and an argument-dependent lookup based on the types of
12084   // the arguments.
12085   UnresolvedSet<16> Functions;
12086   OverloadedOperatorKind OverOp
12087     = BinaryOperator::getOverloadedOperator(Opc);
12088   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12089     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12090                                    RHS->getType(), Functions);
12091 
12092   // Build the (potentially-overloaded, potentially-dependent)
12093   // binary operation.
12094   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12095 }
12096 
12097 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12098                             BinaryOperatorKind Opc,
12099                             Expr *LHSExpr, Expr *RHSExpr) {
12100   ExprResult LHS, RHS;
12101   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12102   if (!LHS.isUsable() || !RHS.isUsable())
12103     return ExprError();
12104   LHSExpr = LHS.get();
12105   RHSExpr = RHS.get();
12106 
12107   // We want to end up calling one of checkPseudoObjectAssignment
12108   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12109   // both expressions are overloadable or either is type-dependent),
12110   // or CreateBuiltinBinOp (in any other case).  We also want to get
12111   // any placeholder types out of the way.
12112 
12113   // Handle pseudo-objects in the LHS.
12114   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12115     // Assignments with a pseudo-object l-value need special analysis.
12116     if (pty->getKind() == BuiltinType::PseudoObject &&
12117         BinaryOperator::isAssignmentOp(Opc))
12118       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12119 
12120     // Don't resolve overloads if the other type is overloadable.
12121     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12122       // We can't actually test that if we still have a placeholder,
12123       // though.  Fortunately, none of the exceptions we see in that
12124       // code below are valid when the LHS is an overload set.  Note
12125       // that an overload set can be dependently-typed, but it never
12126       // instantiates to having an overloadable type.
12127       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12128       if (resolvedRHS.isInvalid()) return ExprError();
12129       RHSExpr = resolvedRHS.get();
12130 
12131       if (RHSExpr->isTypeDependent() ||
12132           RHSExpr->getType()->isOverloadableType())
12133         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12134     }
12135 
12136     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12137     // template, diagnose the missing 'template' keyword instead of diagnosing
12138     // an invalid use of a bound member function.
12139     //
12140     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12141     // to C++1z [over.over]/1.4, but we already checked for that case above.
12142     if (Opc == BO_LT && inTemplateInstantiation() &&
12143         (pty->getKind() == BuiltinType::BoundMember ||
12144          pty->getKind() == BuiltinType::Overload)) {
12145       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12146       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12147           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12148             return isa<FunctionTemplateDecl>(ND);
12149           })) {
12150         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12151                                 : OE->getNameLoc(),
12152              diag::err_template_kw_missing)
12153           << OE->getName().getAsString() << "";
12154         return ExprError();
12155       }
12156     }
12157 
12158     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12159     if (LHS.isInvalid()) return ExprError();
12160     LHSExpr = LHS.get();
12161   }
12162 
12163   // Handle pseudo-objects in the RHS.
12164   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12165     // An overload in the RHS can potentially be resolved by the type
12166     // being assigned to.
12167     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12168       if (getLangOpts().CPlusPlus &&
12169           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12170            LHSExpr->getType()->isOverloadableType()))
12171         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12172 
12173       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12174     }
12175 
12176     // Don't resolve overloads if the other type is overloadable.
12177     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12178         LHSExpr->getType()->isOverloadableType())
12179       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12180 
12181     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12182     if (!resolvedRHS.isUsable()) return ExprError();
12183     RHSExpr = resolvedRHS.get();
12184   }
12185 
12186   if (getLangOpts().CPlusPlus) {
12187     // If either expression is type-dependent, always build an
12188     // overloaded op.
12189     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12190       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12191 
12192     // Otherwise, build an overloaded op if either expression has an
12193     // overloadable type.
12194     if (LHSExpr->getType()->isOverloadableType() ||
12195         RHSExpr->getType()->isOverloadableType())
12196       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12197   }
12198 
12199   // Build a built-in binary operation.
12200   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12201 }
12202 
12203 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12204   if (T.isNull() || T->isDependentType())
12205     return false;
12206 
12207   if (!T->isPromotableIntegerType())
12208     return true;
12209 
12210   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12211 }
12212 
12213 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12214                                       UnaryOperatorKind Opc,
12215                                       Expr *InputExpr) {
12216   ExprResult Input = InputExpr;
12217   ExprValueKind VK = VK_RValue;
12218   ExprObjectKind OK = OK_Ordinary;
12219   QualType resultType;
12220   bool CanOverflow = false;
12221 
12222   bool ConvertHalfVec = false;
12223   if (getLangOpts().OpenCL) {
12224     QualType Ty = InputExpr->getType();
12225     // The only legal unary operation for atomics is '&'.
12226     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12227     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12228     // only with a builtin functions and therefore should be disallowed here.
12229         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12230         || Ty->isBlockPointerType())) {
12231       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12232                        << InputExpr->getType()
12233                        << Input.get()->getSourceRange());
12234     }
12235   }
12236   switch (Opc) {
12237   case UO_PreInc:
12238   case UO_PreDec:
12239   case UO_PostInc:
12240   case UO_PostDec:
12241     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12242                                                 OpLoc,
12243                                                 Opc == UO_PreInc ||
12244                                                 Opc == UO_PostInc,
12245                                                 Opc == UO_PreInc ||
12246                                                 Opc == UO_PreDec);
12247     CanOverflow = isOverflowingIntegerType(Context, resultType);
12248     break;
12249   case UO_AddrOf:
12250     resultType = CheckAddressOfOperand(Input, OpLoc);
12251     RecordModifiableNonNullParam(*this, InputExpr);
12252     break;
12253   case UO_Deref: {
12254     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12255     if (Input.isInvalid()) return ExprError();
12256     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12257     break;
12258   }
12259   case UO_Plus:
12260   case UO_Minus:
12261     CanOverflow = Opc == UO_Minus &&
12262                   isOverflowingIntegerType(Context, Input.get()->getType());
12263     Input = UsualUnaryConversions(Input.get());
12264     if (Input.isInvalid()) return ExprError();
12265     // Unary plus and minus require promoting an operand of half vector to a
12266     // float vector and truncating the result back to a half vector. For now, we
12267     // do this only when HalfArgsAndReturns is set (that is, when the target is
12268     // arm or arm64).
12269     ConvertHalfVec =
12270         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12271 
12272     // If the operand is a half vector, promote it to a float vector.
12273     if (ConvertHalfVec)
12274       Input = convertVector(Input.get(), Context.FloatTy, *this);
12275     resultType = Input.get()->getType();
12276     if (resultType->isDependentType())
12277       break;
12278     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12279       break;
12280     else if (resultType->isVectorType() &&
12281              // The z vector extensions don't allow + or - with bool vectors.
12282              (!Context.getLangOpts().ZVector ||
12283               resultType->getAs<VectorType>()->getVectorKind() !=
12284               VectorType::AltiVecBool))
12285       break;
12286     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12287              Opc == UO_Plus &&
12288              resultType->isPointerType())
12289       break;
12290 
12291     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12292       << resultType << Input.get()->getSourceRange());
12293 
12294   case UO_Not: // bitwise complement
12295     Input = UsualUnaryConversions(Input.get());
12296     if (Input.isInvalid())
12297       return ExprError();
12298     resultType = Input.get()->getType();
12299 
12300     if (resultType->isDependentType())
12301       break;
12302     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12303     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12304       // C99 does not support '~' for complex conjugation.
12305       Diag(OpLoc, diag::ext_integer_complement_complex)
12306           << resultType << Input.get()->getSourceRange();
12307     else if (resultType->hasIntegerRepresentation())
12308       break;
12309     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12310       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12311       // on vector float types.
12312       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12313       if (!T->isIntegerType())
12314         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12315                           << resultType << Input.get()->getSourceRange());
12316     } else {
12317       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12318                        << resultType << Input.get()->getSourceRange());
12319     }
12320     break;
12321 
12322   case UO_LNot: // logical negation
12323     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12324     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12325     if (Input.isInvalid()) return ExprError();
12326     resultType = Input.get()->getType();
12327 
12328     // Though we still have to promote half FP to float...
12329     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12330       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12331       resultType = Context.FloatTy;
12332     }
12333 
12334     if (resultType->isDependentType())
12335       break;
12336     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12337       // C99 6.5.3.3p1: ok, fallthrough;
12338       if (Context.getLangOpts().CPlusPlus) {
12339         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12340         // operand contextually converted to bool.
12341         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12342                                   ScalarTypeToBooleanCastKind(resultType));
12343       } else if (Context.getLangOpts().OpenCL &&
12344                  Context.getLangOpts().OpenCLVersion < 120) {
12345         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12346         // operate on scalar float types.
12347         if (!resultType->isIntegerType() && !resultType->isPointerType())
12348           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12349                            << resultType << Input.get()->getSourceRange());
12350       }
12351     } else if (resultType->isExtVectorType()) {
12352       if (Context.getLangOpts().OpenCL &&
12353           Context.getLangOpts().OpenCLVersion < 120) {
12354         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12355         // operate on vector float types.
12356         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12357         if (!T->isIntegerType())
12358           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12359                            << resultType << Input.get()->getSourceRange());
12360       }
12361       // Vector logical not returns the signed variant of the operand type.
12362       resultType = GetSignedVectorType(resultType);
12363       break;
12364     } else {
12365       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12366       //        type in C++. We should allow that here too.
12367       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12368         << resultType << Input.get()->getSourceRange());
12369     }
12370 
12371     // LNot always has type int. C99 6.5.3.3p5.
12372     // In C++, it's bool. C++ 5.3.1p8
12373     resultType = Context.getLogicalOperationType();
12374     break;
12375   case UO_Real:
12376   case UO_Imag:
12377     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12378     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12379     // complex l-values to ordinary l-values and all other values to r-values.
12380     if (Input.isInvalid()) return ExprError();
12381     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12382       if (Input.get()->getValueKind() != VK_RValue &&
12383           Input.get()->getObjectKind() == OK_Ordinary)
12384         VK = Input.get()->getValueKind();
12385     } else if (!getLangOpts().CPlusPlus) {
12386       // In C, a volatile scalar is read by __imag. In C++, it is not.
12387       Input = DefaultLvalueConversion(Input.get());
12388     }
12389     break;
12390   case UO_Extension:
12391     resultType = Input.get()->getType();
12392     VK = Input.get()->getValueKind();
12393     OK = Input.get()->getObjectKind();
12394     break;
12395   case UO_Coawait:
12396     // It's unnessesary to represent the pass-through operator co_await in the
12397     // AST; just return the input expression instead.
12398     assert(!Input.get()->getType()->isDependentType() &&
12399                    "the co_await expression must be non-dependant before "
12400                    "building operator co_await");
12401     return Input;
12402   }
12403   if (resultType.isNull() || Input.isInvalid())
12404     return ExprError();
12405 
12406   // Check for array bounds violations in the operand of the UnaryOperator,
12407   // except for the '*' and '&' operators that have to be handled specially
12408   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12409   // that are explicitly defined as valid by the standard).
12410   if (Opc != UO_AddrOf && Opc != UO_Deref)
12411     CheckArrayAccess(Input.get());
12412 
12413   auto *UO = new (Context)
12414       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12415   // Convert the result back to a half vector.
12416   if (ConvertHalfVec)
12417     return convertVector(UO, Context.HalfTy, *this);
12418   return UO;
12419 }
12420 
12421 /// \brief Determine whether the given expression is a qualified member
12422 /// access expression, of a form that could be turned into a pointer to member
12423 /// with the address-of operator.
12424 static bool isQualifiedMemberAccess(Expr *E) {
12425   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12426     if (!DRE->getQualifier())
12427       return false;
12428 
12429     ValueDecl *VD = DRE->getDecl();
12430     if (!VD->isCXXClassMember())
12431       return false;
12432 
12433     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12434       return true;
12435     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12436       return Method->isInstance();
12437 
12438     return false;
12439   }
12440 
12441   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12442     if (!ULE->getQualifier())
12443       return false;
12444 
12445     for (NamedDecl *D : ULE->decls()) {
12446       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12447         if (Method->isInstance())
12448           return true;
12449       } else {
12450         // Overload set does not contain methods.
12451         break;
12452       }
12453     }
12454 
12455     return false;
12456   }
12457 
12458   return false;
12459 }
12460 
12461 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12462                               UnaryOperatorKind Opc, Expr *Input) {
12463   // First things first: handle placeholders so that the
12464   // overloaded-operator check considers the right type.
12465   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12466     // Increment and decrement of pseudo-object references.
12467     if (pty->getKind() == BuiltinType::PseudoObject &&
12468         UnaryOperator::isIncrementDecrementOp(Opc))
12469       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12470 
12471     // extension is always a builtin operator.
12472     if (Opc == UO_Extension)
12473       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12474 
12475     // & gets special logic for several kinds of placeholder.
12476     // The builtin code knows what to do.
12477     if (Opc == UO_AddrOf &&
12478         (pty->getKind() == BuiltinType::Overload ||
12479          pty->getKind() == BuiltinType::UnknownAny ||
12480          pty->getKind() == BuiltinType::BoundMember))
12481       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12482 
12483     // Anything else needs to be handled now.
12484     ExprResult Result = CheckPlaceholderExpr(Input);
12485     if (Result.isInvalid()) return ExprError();
12486     Input = Result.get();
12487   }
12488 
12489   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12490       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12491       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12492     // Find all of the overloaded operators visible from this
12493     // point. We perform both an operator-name lookup from the local
12494     // scope and an argument-dependent lookup based on the types of
12495     // the arguments.
12496     UnresolvedSet<16> Functions;
12497     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12498     if (S && OverOp != OO_None)
12499       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12500                                    Functions);
12501 
12502     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12503   }
12504 
12505   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12506 }
12507 
12508 // Unary Operators.  'Tok' is the token for the operator.
12509 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12510                               tok::TokenKind Op, Expr *Input) {
12511   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12512 }
12513 
12514 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12515 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12516                                 LabelDecl *TheDecl) {
12517   TheDecl->markUsed(Context);
12518   // Create the AST node.  The address of a label always has type 'void*'.
12519   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12520                                      Context.getPointerType(Context.VoidTy));
12521 }
12522 
12523 /// Given the last statement in a statement-expression, check whether
12524 /// the result is a producing expression (like a call to an
12525 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12526 /// release out of the full-expression.  Otherwise, return null.
12527 /// Cannot fail.
12528 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12529   // Should always be wrapped with one of these.
12530   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12531   if (!cleanups) return nullptr;
12532 
12533   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12534   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12535     return nullptr;
12536 
12537   // Splice out the cast.  This shouldn't modify any interesting
12538   // features of the statement.
12539   Expr *producer = cast->getSubExpr();
12540   assert(producer->getType() == cast->getType());
12541   assert(producer->getValueKind() == cast->getValueKind());
12542   cleanups->setSubExpr(producer);
12543   return cleanups;
12544 }
12545 
12546 void Sema::ActOnStartStmtExpr() {
12547   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12548 }
12549 
12550 void Sema::ActOnStmtExprError() {
12551   // Note that function is also called by TreeTransform when leaving a
12552   // StmtExpr scope without rebuilding anything.
12553 
12554   DiscardCleanupsInEvaluationContext();
12555   PopExpressionEvaluationContext();
12556 }
12557 
12558 ExprResult
12559 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12560                     SourceLocation RPLoc) { // "({..})"
12561   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12562   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12563 
12564   if (hasAnyUnrecoverableErrorsInThisFunction())
12565     DiscardCleanupsInEvaluationContext();
12566   assert(!Cleanup.exprNeedsCleanups() &&
12567          "cleanups within StmtExpr not correctly bound!");
12568   PopExpressionEvaluationContext();
12569 
12570   // FIXME: there are a variety of strange constraints to enforce here, for
12571   // example, it is not possible to goto into a stmt expression apparently.
12572   // More semantic analysis is needed.
12573 
12574   // If there are sub-stmts in the compound stmt, take the type of the last one
12575   // as the type of the stmtexpr.
12576   QualType Ty = Context.VoidTy;
12577   bool StmtExprMayBindToTemp = false;
12578   if (!Compound->body_empty()) {
12579     Stmt *LastStmt = Compound->body_back();
12580     LabelStmt *LastLabelStmt = nullptr;
12581     // If LastStmt is a label, skip down through into the body.
12582     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12583       LastLabelStmt = Label;
12584       LastStmt = Label->getSubStmt();
12585     }
12586 
12587     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12588       // Do function/array conversion on the last expression, but not
12589       // lvalue-to-rvalue.  However, initialize an unqualified type.
12590       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12591       if (LastExpr.isInvalid())
12592         return ExprError();
12593       Ty = LastExpr.get()->getType().getUnqualifiedType();
12594 
12595       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12596         // In ARC, if the final expression ends in a consume, splice
12597         // the consume out and bind it later.  In the alternate case
12598         // (when dealing with a retainable type), the result
12599         // initialization will create a produce.  In both cases the
12600         // result will be +1, and we'll need to balance that out with
12601         // a bind.
12602         if (Expr *rebuiltLastStmt
12603               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12604           LastExpr = rebuiltLastStmt;
12605         } else {
12606           LastExpr = PerformCopyInitialization(
12607                             InitializedEntity::InitializeResult(LPLoc,
12608                                                                 Ty,
12609                                                                 false),
12610                                                    SourceLocation(),
12611                                                LastExpr);
12612         }
12613 
12614         if (LastExpr.isInvalid())
12615           return ExprError();
12616         if (LastExpr.get() != nullptr) {
12617           if (!LastLabelStmt)
12618             Compound->setLastStmt(LastExpr.get());
12619           else
12620             LastLabelStmt->setSubStmt(LastExpr.get());
12621           StmtExprMayBindToTemp = true;
12622         }
12623       }
12624     }
12625   }
12626 
12627   // FIXME: Check that expression type is complete/non-abstract; statement
12628   // expressions are not lvalues.
12629   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12630   if (StmtExprMayBindToTemp)
12631     return MaybeBindToTemporary(ResStmtExpr);
12632   return ResStmtExpr;
12633 }
12634 
12635 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12636                                       TypeSourceInfo *TInfo,
12637                                       ArrayRef<OffsetOfComponent> Components,
12638                                       SourceLocation RParenLoc) {
12639   QualType ArgTy = TInfo->getType();
12640   bool Dependent = ArgTy->isDependentType();
12641   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12642 
12643   // We must have at least one component that refers to the type, and the first
12644   // one is known to be a field designator.  Verify that the ArgTy represents
12645   // a struct/union/class.
12646   if (!Dependent && !ArgTy->isRecordType())
12647     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12648                        << ArgTy << TypeRange);
12649 
12650   // Type must be complete per C99 7.17p3 because a declaring a variable
12651   // with an incomplete type would be ill-formed.
12652   if (!Dependent
12653       && RequireCompleteType(BuiltinLoc, ArgTy,
12654                              diag::err_offsetof_incomplete_type, TypeRange))
12655     return ExprError();
12656 
12657   bool DidWarnAboutNonPOD = false;
12658   QualType CurrentType = ArgTy;
12659   SmallVector<OffsetOfNode, 4> Comps;
12660   SmallVector<Expr*, 4> Exprs;
12661   for (const OffsetOfComponent &OC : Components) {
12662     if (OC.isBrackets) {
12663       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12664       if (!CurrentType->isDependentType()) {
12665         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12666         if(!AT)
12667           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12668                            << CurrentType);
12669         CurrentType = AT->getElementType();
12670       } else
12671         CurrentType = Context.DependentTy;
12672 
12673       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12674       if (IdxRval.isInvalid())
12675         return ExprError();
12676       Expr *Idx = IdxRval.get();
12677 
12678       // The expression must be an integral expression.
12679       // FIXME: An integral constant expression?
12680       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12681           !Idx->getType()->isIntegerType())
12682         return ExprError(Diag(Idx->getLocStart(),
12683                               diag::err_typecheck_subscript_not_integer)
12684                          << Idx->getSourceRange());
12685 
12686       // Record this array index.
12687       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12688       Exprs.push_back(Idx);
12689       continue;
12690     }
12691 
12692     // Offset of a field.
12693     if (CurrentType->isDependentType()) {
12694       // We have the offset of a field, but we can't look into the dependent
12695       // type. Just record the identifier of the field.
12696       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12697       CurrentType = Context.DependentTy;
12698       continue;
12699     }
12700 
12701     // We need to have a complete type to look into.
12702     if (RequireCompleteType(OC.LocStart, CurrentType,
12703                             diag::err_offsetof_incomplete_type))
12704       return ExprError();
12705 
12706     // Look for the designated field.
12707     const RecordType *RC = CurrentType->getAs<RecordType>();
12708     if (!RC)
12709       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12710                        << CurrentType);
12711     RecordDecl *RD = RC->getDecl();
12712 
12713     // C++ [lib.support.types]p5:
12714     //   The macro offsetof accepts a restricted set of type arguments in this
12715     //   International Standard. type shall be a POD structure or a POD union
12716     //   (clause 9).
12717     // C++11 [support.types]p4:
12718     //   If type is not a standard-layout class (Clause 9), the results are
12719     //   undefined.
12720     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12721       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12722       unsigned DiagID =
12723         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12724                             : diag::ext_offsetof_non_pod_type;
12725 
12726       if (!IsSafe && !DidWarnAboutNonPOD &&
12727           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12728                               PDiag(DiagID)
12729                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12730                               << CurrentType))
12731         DidWarnAboutNonPOD = true;
12732     }
12733 
12734     // Look for the field.
12735     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12736     LookupQualifiedName(R, RD);
12737     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12738     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12739     if (!MemberDecl) {
12740       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12741         MemberDecl = IndirectMemberDecl->getAnonField();
12742     }
12743 
12744     if (!MemberDecl)
12745       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12746                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12747                                                               OC.LocEnd));
12748 
12749     // C99 7.17p3:
12750     //   (If the specified member is a bit-field, the behavior is undefined.)
12751     //
12752     // We diagnose this as an error.
12753     if (MemberDecl->isBitField()) {
12754       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12755         << MemberDecl->getDeclName()
12756         << SourceRange(BuiltinLoc, RParenLoc);
12757       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12758       return ExprError();
12759     }
12760 
12761     RecordDecl *Parent = MemberDecl->getParent();
12762     if (IndirectMemberDecl)
12763       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12764 
12765     // If the member was found in a base class, introduce OffsetOfNodes for
12766     // the base class indirections.
12767     CXXBasePaths Paths;
12768     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12769                       Paths)) {
12770       if (Paths.getDetectedVirtual()) {
12771         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12772           << MemberDecl->getDeclName()
12773           << SourceRange(BuiltinLoc, RParenLoc);
12774         return ExprError();
12775       }
12776 
12777       CXXBasePath &Path = Paths.front();
12778       for (const CXXBasePathElement &B : Path)
12779         Comps.push_back(OffsetOfNode(B.Base));
12780     }
12781 
12782     if (IndirectMemberDecl) {
12783       for (auto *FI : IndirectMemberDecl->chain()) {
12784         assert(isa<FieldDecl>(FI));
12785         Comps.push_back(OffsetOfNode(OC.LocStart,
12786                                      cast<FieldDecl>(FI), OC.LocEnd));
12787       }
12788     } else
12789       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12790 
12791     CurrentType = MemberDecl->getType().getNonReferenceType();
12792   }
12793 
12794   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12795                               Comps, Exprs, RParenLoc);
12796 }
12797 
12798 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12799                                       SourceLocation BuiltinLoc,
12800                                       SourceLocation TypeLoc,
12801                                       ParsedType ParsedArgTy,
12802                                       ArrayRef<OffsetOfComponent> Components,
12803                                       SourceLocation RParenLoc) {
12804 
12805   TypeSourceInfo *ArgTInfo;
12806   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12807   if (ArgTy.isNull())
12808     return ExprError();
12809 
12810   if (!ArgTInfo)
12811     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12812 
12813   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12814 }
12815 
12816 
12817 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12818                                  Expr *CondExpr,
12819                                  Expr *LHSExpr, Expr *RHSExpr,
12820                                  SourceLocation RPLoc) {
12821   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12822 
12823   ExprValueKind VK = VK_RValue;
12824   ExprObjectKind OK = OK_Ordinary;
12825   QualType resType;
12826   bool ValueDependent = false;
12827   bool CondIsTrue = false;
12828   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12829     resType = Context.DependentTy;
12830     ValueDependent = true;
12831   } else {
12832     // The conditional expression is required to be a constant expression.
12833     llvm::APSInt condEval(32);
12834     ExprResult CondICE
12835       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12836           diag::err_typecheck_choose_expr_requires_constant, false);
12837     if (CondICE.isInvalid())
12838       return ExprError();
12839     CondExpr = CondICE.get();
12840     CondIsTrue = condEval.getZExtValue();
12841 
12842     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12843     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12844 
12845     resType = ActiveExpr->getType();
12846     ValueDependent = ActiveExpr->isValueDependent();
12847     VK = ActiveExpr->getValueKind();
12848     OK = ActiveExpr->getObjectKind();
12849   }
12850 
12851   return new (Context)
12852       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12853                  CondIsTrue, resType->isDependentType(), ValueDependent);
12854 }
12855 
12856 //===----------------------------------------------------------------------===//
12857 // Clang Extensions.
12858 //===----------------------------------------------------------------------===//
12859 
12860 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12861 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12862   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12863 
12864   if (LangOpts.CPlusPlus) {
12865     Decl *ManglingContextDecl;
12866     if (MangleNumberingContext *MCtx =
12867             getCurrentMangleNumberContext(Block->getDeclContext(),
12868                                           ManglingContextDecl)) {
12869       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12870       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12871     }
12872   }
12873 
12874   PushBlockScope(CurScope, Block);
12875   CurContext->addDecl(Block);
12876   if (CurScope)
12877     PushDeclContext(CurScope, Block);
12878   else
12879     CurContext = Block;
12880 
12881   getCurBlock()->HasImplicitReturnType = true;
12882 
12883   // Enter a new evaluation context to insulate the block from any
12884   // cleanups from the enclosing full-expression.
12885   PushExpressionEvaluationContext(
12886       ExpressionEvaluationContext::PotentiallyEvaluated);
12887 }
12888 
12889 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12890                                Scope *CurScope) {
12891   assert(ParamInfo.getIdentifier() == nullptr &&
12892          "block-id should have no identifier!");
12893   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
12894   BlockScopeInfo *CurBlock = getCurBlock();
12895 
12896   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12897   QualType T = Sig->getType();
12898 
12899   // FIXME: We should allow unexpanded parameter packs here, but that would,
12900   // in turn, make the block expression contain unexpanded parameter packs.
12901   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12902     // Drop the parameters.
12903     FunctionProtoType::ExtProtoInfo EPI;
12904     EPI.HasTrailingReturn = false;
12905     EPI.TypeQuals |= DeclSpec::TQ_const;
12906     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12907     Sig = Context.getTrivialTypeSourceInfo(T);
12908   }
12909 
12910   // GetTypeForDeclarator always produces a function type for a block
12911   // literal signature.  Furthermore, it is always a FunctionProtoType
12912   // unless the function was written with a typedef.
12913   assert(T->isFunctionType() &&
12914          "GetTypeForDeclarator made a non-function block signature");
12915 
12916   // Look for an explicit signature in that function type.
12917   FunctionProtoTypeLoc ExplicitSignature;
12918 
12919   if ((ExplicitSignature =
12920            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
12921 
12922     // Check whether that explicit signature was synthesized by
12923     // GetTypeForDeclarator.  If so, don't save that as part of the
12924     // written signature.
12925     if (ExplicitSignature.getLocalRangeBegin() ==
12926         ExplicitSignature.getLocalRangeEnd()) {
12927       // This would be much cheaper if we stored TypeLocs instead of
12928       // TypeSourceInfos.
12929       TypeLoc Result = ExplicitSignature.getReturnLoc();
12930       unsigned Size = Result.getFullDataSize();
12931       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12932       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12933 
12934       ExplicitSignature = FunctionProtoTypeLoc();
12935     }
12936   }
12937 
12938   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12939   CurBlock->FunctionType = T;
12940 
12941   const FunctionType *Fn = T->getAs<FunctionType>();
12942   QualType RetTy = Fn->getReturnType();
12943   bool isVariadic =
12944     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12945 
12946   CurBlock->TheDecl->setIsVariadic(isVariadic);
12947 
12948   // Context.DependentTy is used as a placeholder for a missing block
12949   // return type.  TODO:  what should we do with declarators like:
12950   //   ^ * { ... }
12951   // If the answer is "apply template argument deduction"....
12952   if (RetTy != Context.DependentTy) {
12953     CurBlock->ReturnType = RetTy;
12954     CurBlock->TheDecl->setBlockMissingReturnType(false);
12955     CurBlock->HasImplicitReturnType = false;
12956   }
12957 
12958   // Push block parameters from the declarator if we had them.
12959   SmallVector<ParmVarDecl*, 8> Params;
12960   if (ExplicitSignature) {
12961     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12962       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12963       if (Param->getIdentifier() == nullptr &&
12964           !Param->isImplicit() &&
12965           !Param->isInvalidDecl() &&
12966           !getLangOpts().CPlusPlus)
12967         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12968       Params.push_back(Param);
12969     }
12970 
12971   // Fake up parameter variables if we have a typedef, like
12972   //   ^ fntype { ... }
12973   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12974     for (const auto &I : Fn->param_types()) {
12975       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12976           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12977       Params.push_back(Param);
12978     }
12979   }
12980 
12981   // Set the parameters on the block decl.
12982   if (!Params.empty()) {
12983     CurBlock->TheDecl->setParams(Params);
12984     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12985                              /*CheckParameterNames=*/false);
12986   }
12987 
12988   // Finally we can process decl attributes.
12989   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12990 
12991   // Put the parameter variables in scope.
12992   for (auto AI : CurBlock->TheDecl->parameters()) {
12993     AI->setOwningFunction(CurBlock->TheDecl);
12994 
12995     // If this has an identifier, add it to the scope stack.
12996     if (AI->getIdentifier()) {
12997       CheckShadow(CurBlock->TheScope, AI);
12998 
12999       PushOnScopeChains(AI, CurBlock->TheScope);
13000     }
13001   }
13002 }
13003 
13004 /// ActOnBlockError - If there is an error parsing a block, this callback
13005 /// is invoked to pop the information about the block from the action impl.
13006 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13007   // Leave the expression-evaluation context.
13008   DiscardCleanupsInEvaluationContext();
13009   PopExpressionEvaluationContext();
13010 
13011   // Pop off CurBlock, handle nested blocks.
13012   PopDeclContext();
13013   PopFunctionScopeInfo();
13014 }
13015 
13016 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13017 /// literal was successfully completed.  ^(int x){...}
13018 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13019                                     Stmt *Body, Scope *CurScope) {
13020   // If blocks are disabled, emit an error.
13021   if (!LangOpts.Blocks)
13022     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13023 
13024   // Leave the expression-evaluation context.
13025   if (hasAnyUnrecoverableErrorsInThisFunction())
13026     DiscardCleanupsInEvaluationContext();
13027   assert(!Cleanup.exprNeedsCleanups() &&
13028          "cleanups within block not correctly bound!");
13029   PopExpressionEvaluationContext();
13030 
13031   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13032 
13033   if (BSI->HasImplicitReturnType)
13034     deduceClosureReturnType(*BSI);
13035 
13036   PopDeclContext();
13037 
13038   QualType RetTy = Context.VoidTy;
13039   if (!BSI->ReturnType.isNull())
13040     RetTy = BSI->ReturnType;
13041 
13042   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13043   QualType BlockTy;
13044 
13045   // Set the captured variables on the block.
13046   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13047   SmallVector<BlockDecl::Capture, 4> Captures;
13048   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
13049     if (Cap.isThisCapture())
13050       continue;
13051     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13052                               Cap.isNested(), Cap.getInitExpr());
13053     Captures.push_back(NewCap);
13054   }
13055   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13056 
13057   // If the user wrote a function type in some form, try to use that.
13058   if (!BSI->FunctionType.isNull()) {
13059     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13060 
13061     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13062     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13063 
13064     // Turn protoless block types into nullary block types.
13065     if (isa<FunctionNoProtoType>(FTy)) {
13066       FunctionProtoType::ExtProtoInfo EPI;
13067       EPI.ExtInfo = Ext;
13068       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13069 
13070     // Otherwise, if we don't need to change anything about the function type,
13071     // preserve its sugar structure.
13072     } else if (FTy->getReturnType() == RetTy &&
13073                (!NoReturn || FTy->getNoReturnAttr())) {
13074       BlockTy = BSI->FunctionType;
13075 
13076     // Otherwise, make the minimal modifications to the function type.
13077     } else {
13078       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13079       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13080       EPI.TypeQuals = 0; // FIXME: silently?
13081       EPI.ExtInfo = Ext;
13082       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13083     }
13084 
13085   // If we don't have a function type, just build one from nothing.
13086   } else {
13087     FunctionProtoType::ExtProtoInfo EPI;
13088     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13089     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13090   }
13091 
13092   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13093   BlockTy = Context.getBlockPointerType(BlockTy);
13094 
13095   // If needed, diagnose invalid gotos and switches in the block.
13096   if (getCurFunction()->NeedsScopeChecking() &&
13097       !PP.isCodeCompletionEnabled())
13098     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13099 
13100   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13101 
13102   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13103     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13104 
13105   // Try to apply the named return value optimization. We have to check again
13106   // if we can do this, though, because blocks keep return statements around
13107   // to deduce an implicit return type.
13108   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13109       !BSI->TheDecl->isDependentContext())
13110     computeNRVO(Body, BSI);
13111 
13112   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13113   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13114   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13115 
13116   // If the block isn't obviously global, i.e. it captures anything at
13117   // all, then we need to do a few things in the surrounding context:
13118   if (Result->getBlockDecl()->hasCaptures()) {
13119     // First, this expression has a new cleanup object.
13120     ExprCleanupObjects.push_back(Result->getBlockDecl());
13121     Cleanup.setExprNeedsCleanups(true);
13122 
13123     // It also gets a branch-protected scope if any of the captured
13124     // variables needs destruction.
13125     for (const auto &CI : Result->getBlockDecl()->captures()) {
13126       const VarDecl *var = CI.getVariable();
13127       if (var->getType().isDestructedType() != QualType::DK_none) {
13128         getCurFunction()->setHasBranchProtectedScope();
13129         break;
13130       }
13131     }
13132   }
13133 
13134   return Result;
13135 }
13136 
13137 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13138                             SourceLocation RPLoc) {
13139   TypeSourceInfo *TInfo;
13140   GetTypeFromParser(Ty, &TInfo);
13141   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13142 }
13143 
13144 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13145                                 Expr *E, TypeSourceInfo *TInfo,
13146                                 SourceLocation RPLoc) {
13147   Expr *OrigExpr = E;
13148   bool IsMS = false;
13149 
13150   // CUDA device code does not support varargs.
13151   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13152     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13153       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13154       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13155         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13156     }
13157   }
13158 
13159   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13160   // as Microsoft ABI on an actual Microsoft platform, where
13161   // __builtin_ms_va_list and __builtin_va_list are the same.)
13162   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13163       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13164     QualType MSVaListType = Context.getBuiltinMSVaListType();
13165     if (Context.hasSameType(MSVaListType, E->getType())) {
13166       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13167         return ExprError();
13168       IsMS = true;
13169     }
13170   }
13171 
13172   // Get the va_list type
13173   QualType VaListType = Context.getBuiltinVaListType();
13174   if (!IsMS) {
13175     if (VaListType->isArrayType()) {
13176       // Deal with implicit array decay; for example, on x86-64,
13177       // va_list is an array, but it's supposed to decay to
13178       // a pointer for va_arg.
13179       VaListType = Context.getArrayDecayedType(VaListType);
13180       // Make sure the input expression also decays appropriately.
13181       ExprResult Result = UsualUnaryConversions(E);
13182       if (Result.isInvalid())
13183         return ExprError();
13184       E = Result.get();
13185     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13186       // If va_list is a record type and we are compiling in C++ mode,
13187       // check the argument using reference binding.
13188       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13189           Context, Context.getLValueReferenceType(VaListType), false);
13190       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13191       if (Init.isInvalid())
13192         return ExprError();
13193       E = Init.getAs<Expr>();
13194     } else {
13195       // Otherwise, the va_list argument must be an l-value because
13196       // it is modified by va_arg.
13197       if (!E->isTypeDependent() &&
13198           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13199         return ExprError();
13200     }
13201   }
13202 
13203   if (!IsMS && !E->isTypeDependent() &&
13204       !Context.hasSameType(VaListType, E->getType()))
13205     return ExprError(Diag(E->getLocStart(),
13206                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13207       << OrigExpr->getType() << E->getSourceRange());
13208 
13209   if (!TInfo->getType()->isDependentType()) {
13210     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13211                             diag::err_second_parameter_to_va_arg_incomplete,
13212                             TInfo->getTypeLoc()))
13213       return ExprError();
13214 
13215     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13216                                TInfo->getType(),
13217                                diag::err_second_parameter_to_va_arg_abstract,
13218                                TInfo->getTypeLoc()))
13219       return ExprError();
13220 
13221     if (!TInfo->getType().isPODType(Context)) {
13222       Diag(TInfo->getTypeLoc().getBeginLoc(),
13223            TInfo->getType()->isObjCLifetimeType()
13224              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13225              : diag::warn_second_parameter_to_va_arg_not_pod)
13226         << TInfo->getType()
13227         << TInfo->getTypeLoc().getSourceRange();
13228     }
13229 
13230     // Check for va_arg where arguments of the given type will be promoted
13231     // (i.e. this va_arg is guaranteed to have undefined behavior).
13232     QualType PromoteType;
13233     if (TInfo->getType()->isPromotableIntegerType()) {
13234       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13235       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13236         PromoteType = QualType();
13237     }
13238     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13239       PromoteType = Context.DoubleTy;
13240     if (!PromoteType.isNull())
13241       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13242                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13243                           << TInfo->getType()
13244                           << PromoteType
13245                           << TInfo->getTypeLoc().getSourceRange());
13246   }
13247 
13248   QualType T = TInfo->getType().getNonLValueExprType(Context);
13249   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13250 }
13251 
13252 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13253   // The type of __null will be int or long, depending on the size of
13254   // pointers on the target.
13255   QualType Ty;
13256   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13257   if (pw == Context.getTargetInfo().getIntWidth())
13258     Ty = Context.IntTy;
13259   else if (pw == Context.getTargetInfo().getLongWidth())
13260     Ty = Context.LongTy;
13261   else if (pw == Context.getTargetInfo().getLongLongWidth())
13262     Ty = Context.LongLongTy;
13263   else {
13264     llvm_unreachable("I don't know size of pointer!");
13265   }
13266 
13267   return new (Context) GNUNullExpr(Ty, TokenLoc);
13268 }
13269 
13270 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13271                                               bool Diagnose) {
13272   if (!getLangOpts().ObjC1)
13273     return false;
13274 
13275   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13276   if (!PT)
13277     return false;
13278 
13279   if (!PT->isObjCIdType()) {
13280     // Check if the destination is the 'NSString' interface.
13281     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13282     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13283       return false;
13284   }
13285 
13286   // Ignore any parens, implicit casts (should only be
13287   // array-to-pointer decays), and not-so-opaque values.  The last is
13288   // important for making this trigger for property assignments.
13289   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13290   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13291     if (OV->getSourceExpr())
13292       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13293 
13294   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13295   if (!SL || !SL->isAscii())
13296     return false;
13297   if (Diagnose) {
13298     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13299       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13300     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13301   }
13302   return true;
13303 }
13304 
13305 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13306                                               const Expr *SrcExpr) {
13307   if (!DstType->isFunctionPointerType() ||
13308       !SrcExpr->getType()->isFunctionType())
13309     return false;
13310 
13311   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13312   if (!DRE)
13313     return false;
13314 
13315   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13316   if (!FD)
13317     return false;
13318 
13319   return !S.checkAddressOfFunctionIsAvailable(FD,
13320                                               /*Complain=*/true,
13321                                               SrcExpr->getLocStart());
13322 }
13323 
13324 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13325                                     SourceLocation Loc,
13326                                     QualType DstType, QualType SrcType,
13327                                     Expr *SrcExpr, AssignmentAction Action,
13328                                     bool *Complained) {
13329   if (Complained)
13330     *Complained = false;
13331 
13332   // Decode the result (notice that AST's are still created for extensions).
13333   bool CheckInferredResultType = false;
13334   bool isInvalid = false;
13335   unsigned DiagKind = 0;
13336   FixItHint Hint;
13337   ConversionFixItGenerator ConvHints;
13338   bool MayHaveConvFixit = false;
13339   bool MayHaveFunctionDiff = false;
13340   const ObjCInterfaceDecl *IFace = nullptr;
13341   const ObjCProtocolDecl *PDecl = nullptr;
13342 
13343   switch (ConvTy) {
13344   case Compatible:
13345       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13346       return false;
13347 
13348   case PointerToInt:
13349     DiagKind = diag::ext_typecheck_convert_pointer_int;
13350     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13351     MayHaveConvFixit = true;
13352     break;
13353   case IntToPointer:
13354     DiagKind = diag::ext_typecheck_convert_int_pointer;
13355     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13356     MayHaveConvFixit = true;
13357     break;
13358   case IncompatiblePointer:
13359     if (Action == AA_Passing_CFAudited)
13360       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13361     else if (SrcType->isFunctionPointerType() &&
13362              DstType->isFunctionPointerType())
13363       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13364     else
13365       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13366 
13367     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13368       SrcType->isObjCObjectPointerType();
13369     if (Hint.isNull() && !CheckInferredResultType) {
13370       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13371     }
13372     else if (CheckInferredResultType) {
13373       SrcType = SrcType.getUnqualifiedType();
13374       DstType = DstType.getUnqualifiedType();
13375     }
13376     MayHaveConvFixit = true;
13377     break;
13378   case IncompatiblePointerSign:
13379     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13380     break;
13381   case FunctionVoidPointer:
13382     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13383     break;
13384   case IncompatiblePointerDiscardsQualifiers: {
13385     // Perform array-to-pointer decay if necessary.
13386     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13387 
13388     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13389     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13390     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13391       DiagKind = diag::err_typecheck_incompatible_address_space;
13392       break;
13393 
13394 
13395     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13396       DiagKind = diag::err_typecheck_incompatible_ownership;
13397       break;
13398     }
13399 
13400     llvm_unreachable("unknown error case for discarding qualifiers!");
13401     // fallthrough
13402   }
13403   case CompatiblePointerDiscardsQualifiers:
13404     // If the qualifiers lost were because we were applying the
13405     // (deprecated) C++ conversion from a string literal to a char*
13406     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13407     // Ideally, this check would be performed in
13408     // checkPointerTypesForAssignment. However, that would require a
13409     // bit of refactoring (so that the second argument is an
13410     // expression, rather than a type), which should be done as part
13411     // of a larger effort to fix checkPointerTypesForAssignment for
13412     // C++ semantics.
13413     if (getLangOpts().CPlusPlus &&
13414         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13415       return false;
13416     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13417     break;
13418   case IncompatibleNestedPointerQualifiers:
13419     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13420     break;
13421   case IntToBlockPointer:
13422     DiagKind = diag::err_int_to_block_pointer;
13423     break;
13424   case IncompatibleBlockPointer:
13425     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13426     break;
13427   case IncompatibleObjCQualifiedId: {
13428     if (SrcType->isObjCQualifiedIdType()) {
13429       const ObjCObjectPointerType *srcOPT =
13430                 SrcType->getAs<ObjCObjectPointerType>();
13431       for (auto *srcProto : srcOPT->quals()) {
13432         PDecl = srcProto;
13433         break;
13434       }
13435       if (const ObjCInterfaceType *IFaceT =
13436             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13437         IFace = IFaceT->getDecl();
13438     }
13439     else if (DstType->isObjCQualifiedIdType()) {
13440       const ObjCObjectPointerType *dstOPT =
13441         DstType->getAs<ObjCObjectPointerType>();
13442       for (auto *dstProto : dstOPT->quals()) {
13443         PDecl = dstProto;
13444         break;
13445       }
13446       if (const ObjCInterfaceType *IFaceT =
13447             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13448         IFace = IFaceT->getDecl();
13449     }
13450     DiagKind = diag::warn_incompatible_qualified_id;
13451     break;
13452   }
13453   case IncompatibleVectors:
13454     DiagKind = diag::warn_incompatible_vectors;
13455     break;
13456   case IncompatibleObjCWeakRef:
13457     DiagKind = diag::err_arc_weak_unavailable_assign;
13458     break;
13459   case Incompatible:
13460     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13461       if (Complained)
13462         *Complained = true;
13463       return true;
13464     }
13465 
13466     DiagKind = diag::err_typecheck_convert_incompatible;
13467     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13468     MayHaveConvFixit = true;
13469     isInvalid = true;
13470     MayHaveFunctionDiff = true;
13471     break;
13472   }
13473 
13474   QualType FirstType, SecondType;
13475   switch (Action) {
13476   case AA_Assigning:
13477   case AA_Initializing:
13478     // The destination type comes first.
13479     FirstType = DstType;
13480     SecondType = SrcType;
13481     break;
13482 
13483   case AA_Returning:
13484   case AA_Passing:
13485   case AA_Passing_CFAudited:
13486   case AA_Converting:
13487   case AA_Sending:
13488   case AA_Casting:
13489     // The source type comes first.
13490     FirstType = SrcType;
13491     SecondType = DstType;
13492     break;
13493   }
13494 
13495   PartialDiagnostic FDiag = PDiag(DiagKind);
13496   if (Action == AA_Passing_CFAudited)
13497     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13498   else
13499     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13500 
13501   // If we can fix the conversion, suggest the FixIts.
13502   assert(ConvHints.isNull() || Hint.isNull());
13503   if (!ConvHints.isNull()) {
13504     for (FixItHint &H : ConvHints.Hints)
13505       FDiag << H;
13506   } else {
13507     FDiag << Hint;
13508   }
13509   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13510 
13511   if (MayHaveFunctionDiff)
13512     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13513 
13514   Diag(Loc, FDiag);
13515   if (DiagKind == diag::warn_incompatible_qualified_id &&
13516       PDecl && IFace && !IFace->hasDefinition())
13517       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13518         << IFace->getName() << PDecl->getName();
13519 
13520   if (SecondType == Context.OverloadTy)
13521     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13522                               FirstType, /*TakingAddress=*/true);
13523 
13524   if (CheckInferredResultType)
13525     EmitRelatedResultTypeNote(SrcExpr);
13526 
13527   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13528     EmitRelatedResultTypeNoteForReturn(DstType);
13529 
13530   if (Complained)
13531     *Complained = true;
13532   return isInvalid;
13533 }
13534 
13535 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13536                                                  llvm::APSInt *Result) {
13537   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13538   public:
13539     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13540       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13541     }
13542   } Diagnoser;
13543 
13544   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13545 }
13546 
13547 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13548                                                  llvm::APSInt *Result,
13549                                                  unsigned DiagID,
13550                                                  bool AllowFold) {
13551   class IDDiagnoser : public VerifyICEDiagnoser {
13552     unsigned DiagID;
13553 
13554   public:
13555     IDDiagnoser(unsigned DiagID)
13556       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13557 
13558     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13559       S.Diag(Loc, DiagID) << SR;
13560     }
13561   } Diagnoser(DiagID);
13562 
13563   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13564 }
13565 
13566 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13567                                             SourceRange SR) {
13568   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13569 }
13570 
13571 ExprResult
13572 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13573                                       VerifyICEDiagnoser &Diagnoser,
13574                                       bool AllowFold) {
13575   SourceLocation DiagLoc = E->getLocStart();
13576 
13577   if (getLangOpts().CPlusPlus11) {
13578     // C++11 [expr.const]p5:
13579     //   If an expression of literal class type is used in a context where an
13580     //   integral constant expression is required, then that class type shall
13581     //   have a single non-explicit conversion function to an integral or
13582     //   unscoped enumeration type
13583     ExprResult Converted;
13584     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13585     public:
13586       CXX11ConvertDiagnoser(bool Silent)
13587           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13588                                 Silent, true) {}
13589 
13590       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13591                                            QualType T) override {
13592         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13593       }
13594 
13595       SemaDiagnosticBuilder diagnoseIncomplete(
13596           Sema &S, SourceLocation Loc, QualType T) override {
13597         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13598       }
13599 
13600       SemaDiagnosticBuilder diagnoseExplicitConv(
13601           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13602         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13603       }
13604 
13605       SemaDiagnosticBuilder noteExplicitConv(
13606           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13607         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13608                  << ConvTy->isEnumeralType() << ConvTy;
13609       }
13610 
13611       SemaDiagnosticBuilder diagnoseAmbiguous(
13612           Sema &S, SourceLocation Loc, QualType T) override {
13613         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13614       }
13615 
13616       SemaDiagnosticBuilder noteAmbiguous(
13617           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13618         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13619                  << ConvTy->isEnumeralType() << ConvTy;
13620       }
13621 
13622       SemaDiagnosticBuilder diagnoseConversion(
13623           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13624         llvm_unreachable("conversion functions are permitted");
13625       }
13626     } ConvertDiagnoser(Diagnoser.Suppress);
13627 
13628     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13629                                                     ConvertDiagnoser);
13630     if (Converted.isInvalid())
13631       return Converted;
13632     E = Converted.get();
13633     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13634       return ExprError();
13635   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13636     // An ICE must be of integral or unscoped enumeration type.
13637     if (!Diagnoser.Suppress)
13638       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13639     return ExprError();
13640   }
13641 
13642   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13643   // in the non-ICE case.
13644   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13645     if (Result)
13646       *Result = E->EvaluateKnownConstInt(Context);
13647     return E;
13648   }
13649 
13650   Expr::EvalResult EvalResult;
13651   SmallVector<PartialDiagnosticAt, 8> Notes;
13652   EvalResult.Diag = &Notes;
13653 
13654   // Try to evaluate the expression, and produce diagnostics explaining why it's
13655   // not a constant expression as a side-effect.
13656   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13657                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13658 
13659   // In C++11, we can rely on diagnostics being produced for any expression
13660   // which is not a constant expression. If no diagnostics were produced, then
13661   // this is a constant expression.
13662   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13663     if (Result)
13664       *Result = EvalResult.Val.getInt();
13665     return E;
13666   }
13667 
13668   // If our only note is the usual "invalid subexpression" note, just point
13669   // the caret at its location rather than producing an essentially
13670   // redundant note.
13671   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13672         diag::note_invalid_subexpr_in_const_expr) {
13673     DiagLoc = Notes[0].first;
13674     Notes.clear();
13675   }
13676 
13677   if (!Folded || !AllowFold) {
13678     if (!Diagnoser.Suppress) {
13679       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13680       for (const PartialDiagnosticAt &Note : Notes)
13681         Diag(Note.first, Note.second);
13682     }
13683 
13684     return ExprError();
13685   }
13686 
13687   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13688   for (const PartialDiagnosticAt &Note : Notes)
13689     Diag(Note.first, Note.second);
13690 
13691   if (Result)
13692     *Result = EvalResult.Val.getInt();
13693   return E;
13694 }
13695 
13696 namespace {
13697   // Handle the case where we conclude a expression which we speculatively
13698   // considered to be unevaluated is actually evaluated.
13699   class TransformToPE : public TreeTransform<TransformToPE> {
13700     typedef TreeTransform<TransformToPE> BaseTransform;
13701 
13702   public:
13703     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13704 
13705     // Make sure we redo semantic analysis
13706     bool AlwaysRebuild() { return true; }
13707 
13708     // Make sure we handle LabelStmts correctly.
13709     // FIXME: This does the right thing, but maybe we need a more general
13710     // fix to TreeTransform?
13711     StmtResult TransformLabelStmt(LabelStmt *S) {
13712       S->getDecl()->setStmt(nullptr);
13713       return BaseTransform::TransformLabelStmt(S);
13714     }
13715 
13716     // We need to special-case DeclRefExprs referring to FieldDecls which
13717     // are not part of a member pointer formation; normal TreeTransforming
13718     // doesn't catch this case because of the way we represent them in the AST.
13719     // FIXME: This is a bit ugly; is it really the best way to handle this
13720     // case?
13721     //
13722     // Error on DeclRefExprs referring to FieldDecls.
13723     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13724       if (isa<FieldDecl>(E->getDecl()) &&
13725           !SemaRef.isUnevaluatedContext())
13726         return SemaRef.Diag(E->getLocation(),
13727                             diag::err_invalid_non_static_member_use)
13728             << E->getDecl() << E->getSourceRange();
13729 
13730       return BaseTransform::TransformDeclRefExpr(E);
13731     }
13732 
13733     // Exception: filter out member pointer formation
13734     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13735       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13736         return E;
13737 
13738       return BaseTransform::TransformUnaryOperator(E);
13739     }
13740 
13741     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13742       // Lambdas never need to be transformed.
13743       return E;
13744     }
13745   };
13746 }
13747 
13748 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13749   assert(isUnevaluatedContext() &&
13750          "Should only transform unevaluated expressions");
13751   ExprEvalContexts.back().Context =
13752       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13753   if (isUnevaluatedContext())
13754     return E;
13755   return TransformToPE(*this).TransformExpr(E);
13756 }
13757 
13758 void
13759 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13760                                       Decl *LambdaContextDecl,
13761                                       bool IsDecltype) {
13762   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13763                                 LambdaContextDecl, IsDecltype);
13764   Cleanup.reset();
13765   if (!MaybeODRUseExprs.empty())
13766     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13767 }
13768 
13769 void
13770 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13771                                       ReuseLambdaContextDecl_t,
13772                                       bool IsDecltype) {
13773   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13774   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13775 }
13776 
13777 void Sema::PopExpressionEvaluationContext() {
13778   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13779   unsigned NumTypos = Rec.NumTypos;
13780 
13781   if (!Rec.Lambdas.empty()) {
13782     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13783       unsigned D;
13784       if (Rec.isUnevaluated()) {
13785         // C++11 [expr.prim.lambda]p2:
13786         //   A lambda-expression shall not appear in an unevaluated operand
13787         //   (Clause 5).
13788         D = diag::err_lambda_unevaluated_operand;
13789       } else {
13790         // C++1y [expr.const]p2:
13791         //   A conditional-expression e is a core constant expression unless the
13792         //   evaluation of e, following the rules of the abstract machine, would
13793         //   evaluate [...] a lambda-expression.
13794         D = diag::err_lambda_in_constant_expression;
13795       }
13796 
13797       // C++1z allows lambda expressions as core constant expressions.
13798       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13799       // 1607) from appearing within template-arguments and array-bounds that
13800       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13801       // unevaluated contexts) might lift some of these restrictions in a
13802       // future version.
13803       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
13804         for (const auto *L : Rec.Lambdas)
13805           Diag(L->getLocStart(), D);
13806     } else {
13807       // Mark the capture expressions odr-used. This was deferred
13808       // during lambda expression creation.
13809       for (auto *Lambda : Rec.Lambdas) {
13810         for (auto *C : Lambda->capture_inits())
13811           MarkDeclarationsReferencedInExpr(C);
13812       }
13813     }
13814   }
13815 
13816   // When are coming out of an unevaluated context, clear out any
13817   // temporaries that we may have created as part of the evaluation of
13818   // the expression in that context: they aren't relevant because they
13819   // will never be constructed.
13820   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13821     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13822                              ExprCleanupObjects.end());
13823     Cleanup = Rec.ParentCleanup;
13824     CleanupVarDeclMarking();
13825     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13826   // Otherwise, merge the contexts together.
13827   } else {
13828     Cleanup.mergeFrom(Rec.ParentCleanup);
13829     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13830                             Rec.SavedMaybeODRUseExprs.end());
13831   }
13832 
13833   // Pop the current expression evaluation context off the stack.
13834   ExprEvalContexts.pop_back();
13835 
13836   if (!ExprEvalContexts.empty())
13837     ExprEvalContexts.back().NumTypos += NumTypos;
13838   else
13839     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13840                             "last ExpressionEvaluationContextRecord");
13841 }
13842 
13843 void Sema::DiscardCleanupsInEvaluationContext() {
13844   ExprCleanupObjects.erase(
13845          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13846          ExprCleanupObjects.end());
13847   Cleanup.reset();
13848   MaybeODRUseExprs.clear();
13849 }
13850 
13851 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13852   if (!E->getType()->isVariablyModifiedType())
13853     return E;
13854   return TransformToPotentiallyEvaluated(E);
13855 }
13856 
13857 /// Are we within a context in which some evaluation could be performed (be it
13858 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13859 /// captured by C++'s idea of an "unevaluated context".
13860 static bool isEvaluatableContext(Sema &SemaRef) {
13861   switch (SemaRef.ExprEvalContexts.back().Context) {
13862     case Sema::ExpressionEvaluationContext::Unevaluated:
13863     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13864     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13865       // Expressions in this context are never evaluated.
13866       return false;
13867 
13868     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13869     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13870     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13871       // Expressions in this context could be evaluated.
13872       return true;
13873 
13874     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13875       // Referenced declarations will only be used if the construct in the
13876       // containing expression is used, at which point we'll be given another
13877       // turn to mark them.
13878       return false;
13879   }
13880   llvm_unreachable("Invalid context");
13881 }
13882 
13883 /// Are we within a context in which references to resolved functions or to
13884 /// variables result in odr-use?
13885 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13886   // An expression in a template is not really an expression until it's been
13887   // instantiated, so it doesn't trigger odr-use.
13888   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13889     return false;
13890 
13891   switch (SemaRef.ExprEvalContexts.back().Context) {
13892     case Sema::ExpressionEvaluationContext::Unevaluated:
13893     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13894     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13895     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13896       return false;
13897 
13898     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13899     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13900       return true;
13901 
13902     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13903       return false;
13904   }
13905   llvm_unreachable("Invalid context");
13906 }
13907 
13908 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13909   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13910   return Func->isConstexpr() &&
13911          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13912 }
13913 
13914 /// \brief Mark a function referenced, and check whether it is odr-used
13915 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13916 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13917                                   bool MightBeOdrUse) {
13918   assert(Func && "No function?");
13919 
13920   Func->setReferenced();
13921 
13922   // C++11 [basic.def.odr]p3:
13923   //   A function whose name appears as a potentially-evaluated expression is
13924   //   odr-used if it is the unique lookup result or the selected member of a
13925   //   set of overloaded functions [...].
13926   //
13927   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13928   // can just check that here.
13929   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13930 
13931   // Determine whether we require a function definition to exist, per
13932   // C++11 [temp.inst]p3:
13933   //   Unless a function template specialization has been explicitly
13934   //   instantiated or explicitly specialized, the function template
13935   //   specialization is implicitly instantiated when the specialization is
13936   //   referenced in a context that requires a function definition to exist.
13937   //
13938   // That is either when this is an odr-use, or when a usage of a constexpr
13939   // function occurs within an evaluatable context.
13940   bool NeedDefinition =
13941       OdrUse || (isEvaluatableContext(*this) &&
13942                  isImplicitlyDefinableConstexprFunction(Func));
13943 
13944   // C++14 [temp.expl.spec]p6:
13945   //   If a template [...] is explicitly specialized then that specialization
13946   //   shall be declared before the first use of that specialization that would
13947   //   cause an implicit instantiation to take place, in every translation unit
13948   //   in which such a use occurs
13949   if (NeedDefinition &&
13950       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13951        Func->getMemberSpecializationInfo()))
13952     checkSpecializationVisibility(Loc, Func);
13953 
13954   // C++14 [except.spec]p17:
13955   //   An exception-specification is considered to be needed when:
13956   //   - the function is odr-used or, if it appears in an unevaluated operand,
13957   //     would be odr-used if the expression were potentially-evaluated;
13958   //
13959   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13960   // function is a pure virtual function we're calling, and in that case the
13961   // function was selected by overload resolution and we need to resolve its
13962   // exception specification for a different reason.
13963   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13964   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13965     ResolveExceptionSpec(Loc, FPT);
13966 
13967   // If we don't need to mark the function as used, and we don't need to
13968   // try to provide a definition, there's nothing more to do.
13969   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13970       (!NeedDefinition || Func->getBody()))
13971     return;
13972 
13973   // Note that this declaration has been used.
13974   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13975     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13976     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13977       if (Constructor->isDefaultConstructor()) {
13978         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13979           return;
13980         DefineImplicitDefaultConstructor(Loc, Constructor);
13981       } else if (Constructor->isCopyConstructor()) {
13982         DefineImplicitCopyConstructor(Loc, Constructor);
13983       } else if (Constructor->isMoveConstructor()) {
13984         DefineImplicitMoveConstructor(Loc, Constructor);
13985       }
13986     } else if (Constructor->getInheritedConstructor()) {
13987       DefineInheritingConstructor(Loc, Constructor);
13988     }
13989   } else if (CXXDestructorDecl *Destructor =
13990                  dyn_cast<CXXDestructorDecl>(Func)) {
13991     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13992     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13993       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13994         return;
13995       DefineImplicitDestructor(Loc, Destructor);
13996     }
13997     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13998       MarkVTableUsed(Loc, Destructor->getParent());
13999   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14000     if (MethodDecl->isOverloadedOperator() &&
14001         MethodDecl->getOverloadedOperator() == OO_Equal) {
14002       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14003       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14004         if (MethodDecl->isCopyAssignmentOperator())
14005           DefineImplicitCopyAssignment(Loc, MethodDecl);
14006         else if (MethodDecl->isMoveAssignmentOperator())
14007           DefineImplicitMoveAssignment(Loc, MethodDecl);
14008       }
14009     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14010                MethodDecl->getParent()->isLambda()) {
14011       CXXConversionDecl *Conversion =
14012           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14013       if (Conversion->isLambdaToBlockPointerConversion())
14014         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14015       else
14016         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14017     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14018       MarkVTableUsed(Loc, MethodDecl->getParent());
14019   }
14020 
14021   // Recursive functions should be marked when used from another function.
14022   // FIXME: Is this really right?
14023   if (CurContext == Func) return;
14024 
14025   // Implicit instantiation of function templates and member functions of
14026   // class templates.
14027   if (Func->isImplicitlyInstantiable()) {
14028     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14029     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14030     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14031     if (FirstInstantiation) {
14032       PointOfInstantiation = Loc;
14033       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14034     } else if (TSK != TSK_ImplicitInstantiation) {
14035       // Use the point of use as the point of instantiation, instead of the
14036       // point of explicit instantiation (which we track as the actual point of
14037       // instantiation). This gives better backtraces in diagnostics.
14038       PointOfInstantiation = Loc;
14039     }
14040 
14041     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14042         Func->isConstexpr()) {
14043       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14044           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14045           CodeSynthesisContexts.size())
14046         PendingLocalImplicitInstantiations.push_back(
14047             std::make_pair(Func, PointOfInstantiation));
14048       else if (Func->isConstexpr())
14049         // Do not defer instantiations of constexpr functions, to avoid the
14050         // expression evaluator needing to call back into Sema if it sees a
14051         // call to such a function.
14052         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14053       else {
14054         Func->setInstantiationIsPending(true);
14055         PendingInstantiations.push_back(std::make_pair(Func,
14056                                                        PointOfInstantiation));
14057         // Notify the consumer that a function was implicitly instantiated.
14058         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14059       }
14060     }
14061   } else {
14062     // Walk redefinitions, as some of them may be instantiable.
14063     for (auto i : Func->redecls()) {
14064       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14065         MarkFunctionReferenced(Loc, i, OdrUse);
14066     }
14067   }
14068 
14069   if (!OdrUse) return;
14070 
14071   // Keep track of used but undefined functions.
14072   if (!Func->isDefined()) {
14073     if (mightHaveNonExternalLinkage(Func))
14074       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14075     else if (Func->getMostRecentDecl()->isInlined() &&
14076              !LangOpts.GNUInline &&
14077              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14078       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14079     else if (isExternalWithNoLinkageType(Func))
14080       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14081   }
14082 
14083   Func->markUsed(Context);
14084 }
14085 
14086 static void
14087 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14088                                    ValueDecl *var, DeclContext *DC) {
14089   DeclContext *VarDC = var->getDeclContext();
14090 
14091   //  If the parameter still belongs to the translation unit, then
14092   //  we're actually just using one parameter in the declaration of
14093   //  the next.
14094   if (isa<ParmVarDecl>(var) &&
14095       isa<TranslationUnitDecl>(VarDC))
14096     return;
14097 
14098   // For C code, don't diagnose about capture if we're not actually in code
14099   // right now; it's impossible to write a non-constant expression outside of
14100   // function context, so we'll get other (more useful) diagnostics later.
14101   //
14102   // For C++, things get a bit more nasty... it would be nice to suppress this
14103   // diagnostic for certain cases like using a local variable in an array bound
14104   // for a member of a local class, but the correct predicate is not obvious.
14105   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14106     return;
14107 
14108   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14109   unsigned ContextKind = 3; // unknown
14110   if (isa<CXXMethodDecl>(VarDC) &&
14111       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14112     ContextKind = 2;
14113   } else if (isa<FunctionDecl>(VarDC)) {
14114     ContextKind = 0;
14115   } else if (isa<BlockDecl>(VarDC)) {
14116     ContextKind = 1;
14117   }
14118 
14119   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14120     << var << ValueKind << ContextKind << VarDC;
14121   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14122       << var;
14123 
14124   // FIXME: Add additional diagnostic info about class etc. which prevents
14125   // capture.
14126 }
14127 
14128 
14129 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14130                                       bool &SubCapturesAreNested,
14131                                       QualType &CaptureType,
14132                                       QualType &DeclRefType) {
14133    // Check whether we've already captured it.
14134   if (CSI->CaptureMap.count(Var)) {
14135     // If we found a capture, any subcaptures are nested.
14136     SubCapturesAreNested = true;
14137 
14138     // Retrieve the capture type for this variable.
14139     CaptureType = CSI->getCapture(Var).getCaptureType();
14140 
14141     // Compute the type of an expression that refers to this variable.
14142     DeclRefType = CaptureType.getNonReferenceType();
14143 
14144     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14145     // are mutable in the sense that user can change their value - they are
14146     // private instances of the captured declarations.
14147     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
14148     if (Cap.isCopyCapture() &&
14149         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14150         !(isa<CapturedRegionScopeInfo>(CSI) &&
14151           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14152       DeclRefType.addConst();
14153     return true;
14154   }
14155   return false;
14156 }
14157 
14158 // Only block literals, captured statements, and lambda expressions can
14159 // capture; other scopes don't work.
14160 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14161                                  SourceLocation Loc,
14162                                  const bool Diagnose, Sema &S) {
14163   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14164     return getLambdaAwareParentOfDeclContext(DC);
14165   else if (Var->hasLocalStorage()) {
14166     if (Diagnose)
14167        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14168   }
14169   return nullptr;
14170 }
14171 
14172 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14173 // certain types of variables (unnamed, variably modified types etc.)
14174 // so check for eligibility.
14175 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14176                                  SourceLocation Loc,
14177                                  const bool Diagnose, Sema &S) {
14178 
14179   bool IsBlock = isa<BlockScopeInfo>(CSI);
14180   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14181 
14182   // Lambdas are not allowed to capture unnamed variables
14183   // (e.g. anonymous unions).
14184   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14185   // assuming that's the intent.
14186   if (IsLambda && !Var->getDeclName()) {
14187     if (Diagnose) {
14188       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14189       S.Diag(Var->getLocation(), diag::note_declared_at);
14190     }
14191     return false;
14192   }
14193 
14194   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14195   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14196     if (Diagnose) {
14197       S.Diag(Loc, diag::err_ref_vm_type);
14198       S.Diag(Var->getLocation(), diag::note_previous_decl)
14199         << Var->getDeclName();
14200     }
14201     return false;
14202   }
14203   // Prohibit structs with flexible array members too.
14204   // We cannot capture what is in the tail end of the struct.
14205   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14206     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14207       if (Diagnose) {
14208         if (IsBlock)
14209           S.Diag(Loc, diag::err_ref_flexarray_type);
14210         else
14211           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14212             << Var->getDeclName();
14213         S.Diag(Var->getLocation(), diag::note_previous_decl)
14214           << Var->getDeclName();
14215       }
14216       return false;
14217     }
14218   }
14219   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14220   // Lambdas and captured statements are not allowed to capture __block
14221   // variables; they don't support the expected semantics.
14222   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14223     if (Diagnose) {
14224       S.Diag(Loc, diag::err_capture_block_variable)
14225         << Var->getDeclName() << !IsLambda;
14226       S.Diag(Var->getLocation(), diag::note_previous_decl)
14227         << Var->getDeclName();
14228     }
14229     return false;
14230   }
14231   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14232   if (S.getLangOpts().OpenCL && IsBlock &&
14233       Var->getType()->isBlockPointerType()) {
14234     if (Diagnose)
14235       S.Diag(Loc, diag::err_opencl_block_ref_block);
14236     return false;
14237   }
14238 
14239   return true;
14240 }
14241 
14242 // Returns true if the capture by block was successful.
14243 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14244                                  SourceLocation Loc,
14245                                  const bool BuildAndDiagnose,
14246                                  QualType &CaptureType,
14247                                  QualType &DeclRefType,
14248                                  const bool Nested,
14249                                  Sema &S) {
14250   Expr *CopyExpr = nullptr;
14251   bool ByRef = false;
14252 
14253   // Blocks are not allowed to capture arrays.
14254   if (CaptureType->isArrayType()) {
14255     if (BuildAndDiagnose) {
14256       S.Diag(Loc, diag::err_ref_array_type);
14257       S.Diag(Var->getLocation(), diag::note_previous_decl)
14258       << Var->getDeclName();
14259     }
14260     return false;
14261   }
14262 
14263   // Forbid the block-capture of autoreleasing variables.
14264   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14265     if (BuildAndDiagnose) {
14266       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14267         << /*block*/ 0;
14268       S.Diag(Var->getLocation(), diag::note_previous_decl)
14269         << Var->getDeclName();
14270     }
14271     return false;
14272   }
14273 
14274   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14275   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14276     // This function finds out whether there is an AttributedType of kind
14277     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14278     // attr_objc_ownership implies __autoreleasing was explicitly specified
14279     // rather than being added implicitly by the compiler.
14280     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14281       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14282         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14283           return true;
14284 
14285         // Peel off AttributedTypes that are not of kind objc_ownership.
14286         Ty = AttrTy->getModifiedType();
14287       }
14288 
14289       return false;
14290     };
14291 
14292     QualType PointeeTy = PT->getPointeeType();
14293 
14294     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14295         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14296         !IsObjCOwnershipAttributedType(PointeeTy)) {
14297       if (BuildAndDiagnose) {
14298         SourceLocation VarLoc = Var->getLocation();
14299         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14300         {
14301           auto AddAutoreleaseNote =
14302               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
14303           // Provide a fix-it for the '__autoreleasing' keyword at the
14304           // appropriate location in the variable's type.
14305           if (const auto *TSI = Var->getTypeSourceInfo()) {
14306             PointerTypeLoc PTL =
14307                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
14308             if (PTL) {
14309               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
14310               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
14311                                                S.getLangOpts());
14312               if (Loc.isValid()) {
14313                 StringRef CharAtLoc = Lexer::getSourceText(
14314                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
14315                     S.getSourceManager(), S.getLangOpts());
14316                 AddAutoreleaseNote << FixItHint::CreateInsertion(
14317                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
14318                              ? " __autoreleasing "
14319                              : " __autoreleasing");
14320               }
14321             }
14322           }
14323         }
14324         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14325       }
14326     }
14327   }
14328 
14329   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14330   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14331       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
14332     // Block capture by reference does not change the capture or
14333     // declaration reference types.
14334     ByRef = true;
14335   } else {
14336     // Block capture by copy introduces 'const'.
14337     CaptureType = CaptureType.getNonReferenceType().withConst();
14338     DeclRefType = CaptureType;
14339 
14340     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14341       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14342         // The capture logic needs the destructor, so make sure we mark it.
14343         // Usually this is unnecessary because most local variables have
14344         // their destructors marked at declaration time, but parameters are
14345         // an exception because it's technically only the call site that
14346         // actually requires the destructor.
14347         if (isa<ParmVarDecl>(Var))
14348           S.FinalizeVarWithDestructor(Var, Record);
14349 
14350         // Enter a new evaluation context to insulate the copy
14351         // full-expression.
14352         EnterExpressionEvaluationContext scope(
14353             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14354 
14355         // According to the blocks spec, the capture of a variable from
14356         // the stack requires a const copy constructor.  This is not true
14357         // of the copy/move done to move a __block variable to the heap.
14358         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14359                                                   DeclRefType.withConst(),
14360                                                   VK_LValue, Loc);
14361 
14362         ExprResult Result
14363           = S.PerformCopyInitialization(
14364               InitializedEntity::InitializeBlock(Var->getLocation(),
14365                                                   CaptureType, false),
14366               Loc, DeclRef);
14367 
14368         // Build a full-expression copy expression if initialization
14369         // succeeded and used a non-trivial constructor.  Recover from
14370         // errors by pretending that the copy isn't necessary.
14371         if (!Result.isInvalid() &&
14372             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14373                 ->isTrivial()) {
14374           Result = S.MaybeCreateExprWithCleanups(Result);
14375           CopyExpr = Result.get();
14376         }
14377       }
14378     }
14379   }
14380 
14381   // Actually capture the variable.
14382   if (BuildAndDiagnose)
14383     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14384                     SourceLocation(), CaptureType, CopyExpr);
14385 
14386   return true;
14387 
14388 }
14389 
14390 
14391 /// \brief Capture the given variable in the captured region.
14392 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14393                                     VarDecl *Var,
14394                                     SourceLocation Loc,
14395                                     const bool BuildAndDiagnose,
14396                                     QualType &CaptureType,
14397                                     QualType &DeclRefType,
14398                                     const bool RefersToCapturedVariable,
14399                                     Sema &S) {
14400   // By default, capture variables by reference.
14401   bool ByRef = true;
14402   // Using an LValue reference type is consistent with Lambdas (see below).
14403   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14404     if (S.IsOpenMPCapturedDecl(Var)) {
14405       bool HasConst = DeclRefType.isConstQualified();
14406       DeclRefType = DeclRefType.getUnqualifiedType();
14407       // Don't lose diagnostics about assignments to const.
14408       if (HasConst)
14409         DeclRefType.addConst();
14410     }
14411     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14412   }
14413 
14414   if (ByRef)
14415     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14416   else
14417     CaptureType = DeclRefType;
14418 
14419   Expr *CopyExpr = nullptr;
14420   if (BuildAndDiagnose) {
14421     // The current implementation assumes that all variables are captured
14422     // by references. Since there is no capture by copy, no expression
14423     // evaluation will be needed.
14424     RecordDecl *RD = RSI->TheRecordDecl;
14425 
14426     FieldDecl *Field
14427       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14428                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14429                           nullptr, false, ICIS_NoInit);
14430     Field->setImplicit(true);
14431     Field->setAccess(AS_private);
14432     RD->addDecl(Field);
14433     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14434       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14435 
14436     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14437                                             DeclRefType, VK_LValue, Loc);
14438     Var->setReferenced(true);
14439     Var->markUsed(S.Context);
14440   }
14441 
14442   // Actually capture the variable.
14443   if (BuildAndDiagnose)
14444     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14445                     SourceLocation(), CaptureType, CopyExpr);
14446 
14447 
14448   return true;
14449 }
14450 
14451 /// \brief Create a field within the lambda class for the variable
14452 /// being captured.
14453 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14454                                     QualType FieldType, QualType DeclRefType,
14455                                     SourceLocation Loc,
14456                                     bool RefersToCapturedVariable) {
14457   CXXRecordDecl *Lambda = LSI->Lambda;
14458 
14459   // Build the non-static data member.
14460   FieldDecl *Field
14461     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14462                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14463                         nullptr, false, ICIS_NoInit);
14464   Field->setImplicit(true);
14465   Field->setAccess(AS_private);
14466   Lambda->addDecl(Field);
14467 }
14468 
14469 /// \brief Capture the given variable in the lambda.
14470 static bool captureInLambda(LambdaScopeInfo *LSI,
14471                             VarDecl *Var,
14472                             SourceLocation Loc,
14473                             const bool BuildAndDiagnose,
14474                             QualType &CaptureType,
14475                             QualType &DeclRefType,
14476                             const bool RefersToCapturedVariable,
14477                             const Sema::TryCaptureKind Kind,
14478                             SourceLocation EllipsisLoc,
14479                             const bool IsTopScope,
14480                             Sema &S) {
14481 
14482   // Determine whether we are capturing by reference or by value.
14483   bool ByRef = false;
14484   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14485     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14486   } else {
14487     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14488   }
14489 
14490   // Compute the type of the field that will capture this variable.
14491   if (ByRef) {
14492     // C++11 [expr.prim.lambda]p15:
14493     //   An entity is captured by reference if it is implicitly or
14494     //   explicitly captured but not captured by copy. It is
14495     //   unspecified whether additional unnamed non-static data
14496     //   members are declared in the closure type for entities
14497     //   captured by reference.
14498     //
14499     // FIXME: It is not clear whether we want to build an lvalue reference
14500     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14501     // to do the former, while EDG does the latter. Core issue 1249 will
14502     // clarify, but for now we follow GCC because it's a more permissive and
14503     // easily defensible position.
14504     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14505   } else {
14506     // C++11 [expr.prim.lambda]p14:
14507     //   For each entity captured by copy, an unnamed non-static
14508     //   data member is declared in the closure type. The
14509     //   declaration order of these members is unspecified. The type
14510     //   of such a data member is the type of the corresponding
14511     //   captured entity if the entity is not a reference to an
14512     //   object, or the referenced type otherwise. [Note: If the
14513     //   captured entity is a reference to a function, the
14514     //   corresponding data member is also a reference to a
14515     //   function. - end note ]
14516     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14517       if (!RefType->getPointeeType()->isFunctionType())
14518         CaptureType = RefType->getPointeeType();
14519     }
14520 
14521     // Forbid the lambda copy-capture of autoreleasing variables.
14522     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14523       if (BuildAndDiagnose) {
14524         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14525         S.Diag(Var->getLocation(), diag::note_previous_decl)
14526           << Var->getDeclName();
14527       }
14528       return false;
14529     }
14530 
14531     // Make sure that by-copy captures are of a complete and non-abstract type.
14532     if (BuildAndDiagnose) {
14533       if (!CaptureType->isDependentType() &&
14534           S.RequireCompleteType(Loc, CaptureType,
14535                                 diag::err_capture_of_incomplete_type,
14536                                 Var->getDeclName()))
14537         return false;
14538 
14539       if (S.RequireNonAbstractType(Loc, CaptureType,
14540                                    diag::err_capture_of_abstract_type))
14541         return false;
14542     }
14543   }
14544 
14545   // Capture this variable in the lambda.
14546   if (BuildAndDiagnose)
14547     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14548                             RefersToCapturedVariable);
14549 
14550   // Compute the type of a reference to this captured variable.
14551   if (ByRef)
14552     DeclRefType = CaptureType.getNonReferenceType();
14553   else {
14554     // C++ [expr.prim.lambda]p5:
14555     //   The closure type for a lambda-expression has a public inline
14556     //   function call operator [...]. This function call operator is
14557     //   declared const (9.3.1) if and only if the lambda-expression's
14558     //   parameter-declaration-clause is not followed by mutable.
14559     DeclRefType = CaptureType.getNonReferenceType();
14560     if (!LSI->Mutable && !CaptureType->isReferenceType())
14561       DeclRefType.addConst();
14562   }
14563 
14564   // Add the capture.
14565   if (BuildAndDiagnose)
14566     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14567                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14568 
14569   return true;
14570 }
14571 
14572 bool Sema::tryCaptureVariable(
14573     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14574     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14575     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14576   // An init-capture is notionally from the context surrounding its
14577   // declaration, but its parent DC is the lambda class.
14578   DeclContext *VarDC = Var->getDeclContext();
14579   if (Var->isInitCapture())
14580     VarDC = VarDC->getParent();
14581 
14582   DeclContext *DC = CurContext;
14583   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14584       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14585   // We need to sync up the Declaration Context with the
14586   // FunctionScopeIndexToStopAt
14587   if (FunctionScopeIndexToStopAt) {
14588     unsigned FSIndex = FunctionScopes.size() - 1;
14589     while (FSIndex != MaxFunctionScopesIndex) {
14590       DC = getLambdaAwareParentOfDeclContext(DC);
14591       --FSIndex;
14592     }
14593   }
14594 
14595 
14596   // If the variable is declared in the current context, there is no need to
14597   // capture it.
14598   if (VarDC == DC) return true;
14599 
14600   // Capture global variables if it is required to use private copy of this
14601   // variable.
14602   bool IsGlobal = !Var->hasLocalStorage();
14603   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14604     return true;
14605   Var = Var->getCanonicalDecl();
14606 
14607   // Walk up the stack to determine whether we can capture the variable,
14608   // performing the "simple" checks that don't depend on type. We stop when
14609   // we've either hit the declared scope of the variable or find an existing
14610   // capture of that variable.  We start from the innermost capturing-entity
14611   // (the DC) and ensure that all intervening capturing-entities
14612   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14613   // declcontext can either capture the variable or have already captured
14614   // the variable.
14615   CaptureType = Var->getType();
14616   DeclRefType = CaptureType.getNonReferenceType();
14617   bool Nested = false;
14618   bool Explicit = (Kind != TryCapture_Implicit);
14619   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14620   do {
14621     // Only block literals, captured statements, and lambda expressions can
14622     // capture; other scopes don't work.
14623     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14624                                                               ExprLoc,
14625                                                               BuildAndDiagnose,
14626                                                               *this);
14627     // We need to check for the parent *first* because, if we *have*
14628     // private-captured a global variable, we need to recursively capture it in
14629     // intermediate blocks, lambdas, etc.
14630     if (!ParentDC) {
14631       if (IsGlobal) {
14632         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14633         break;
14634       }
14635       return true;
14636     }
14637 
14638     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14639     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14640 
14641 
14642     // Check whether we've already captured it.
14643     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14644                                              DeclRefType)) {
14645       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14646       break;
14647     }
14648     // If we are instantiating a generic lambda call operator body,
14649     // we do not want to capture new variables.  What was captured
14650     // during either a lambdas transformation or initial parsing
14651     // should be used.
14652     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14653       if (BuildAndDiagnose) {
14654         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14655         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14656           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14657           Diag(Var->getLocation(), diag::note_previous_decl)
14658              << Var->getDeclName();
14659           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14660         } else
14661           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14662       }
14663       return true;
14664     }
14665     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14666     // certain types of variables (unnamed, variably modified types etc.)
14667     // so check for eligibility.
14668     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14669        return true;
14670 
14671     // Try to capture variable-length arrays types.
14672     if (Var->getType()->isVariablyModifiedType()) {
14673       // We're going to walk down into the type and look for VLA
14674       // expressions.
14675       QualType QTy = Var->getType();
14676       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14677         QTy = PVD->getOriginalType();
14678       captureVariablyModifiedType(Context, QTy, CSI);
14679     }
14680 
14681     if (getLangOpts().OpenMP) {
14682       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14683         // OpenMP private variables should not be captured in outer scope, so
14684         // just break here. Similarly, global variables that are captured in a
14685         // target region should not be captured outside the scope of the region.
14686         if (RSI->CapRegionKind == CR_OpenMP) {
14687           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
14688           auto IsTargetCap = !IsOpenMPPrivateDecl &&
14689                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14690           // When we detect target captures we are looking from inside the
14691           // target region, therefore we need to propagate the capture from the
14692           // enclosing region. Therefore, the capture is not initially nested.
14693           if (IsTargetCap)
14694             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
14695 
14696           if (IsTargetCap || IsOpenMPPrivateDecl) {
14697             Nested = !IsTargetCap;
14698             DeclRefType = DeclRefType.getUnqualifiedType();
14699             CaptureType = Context.getLValueReferenceType(DeclRefType);
14700             break;
14701           }
14702         }
14703       }
14704     }
14705     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14706       // No capture-default, and this is not an explicit capture
14707       // so cannot capture this variable.
14708       if (BuildAndDiagnose) {
14709         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14710         Diag(Var->getLocation(), diag::note_previous_decl)
14711           << Var->getDeclName();
14712         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14713           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14714                diag::note_lambda_decl);
14715         // FIXME: If we error out because an outer lambda can not implicitly
14716         // capture a variable that an inner lambda explicitly captures, we
14717         // should have the inner lambda do the explicit capture - because
14718         // it makes for cleaner diagnostics later.  This would purely be done
14719         // so that the diagnostic does not misleadingly claim that a variable
14720         // can not be captured by a lambda implicitly even though it is captured
14721         // explicitly.  Suggestion:
14722         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14723         //    at the function head
14724         //  - cache the StartingDeclContext - this must be a lambda
14725         //  - captureInLambda in the innermost lambda the variable.
14726       }
14727       return true;
14728     }
14729 
14730     FunctionScopesIndex--;
14731     DC = ParentDC;
14732     Explicit = false;
14733   } while (!VarDC->Equals(DC));
14734 
14735   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14736   // computing the type of the capture at each step, checking type-specific
14737   // requirements, and adding captures if requested.
14738   // If the variable had already been captured previously, we start capturing
14739   // at the lambda nested within that one.
14740   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14741        ++I) {
14742     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14743 
14744     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14745       if (!captureInBlock(BSI, Var, ExprLoc,
14746                           BuildAndDiagnose, CaptureType,
14747                           DeclRefType, Nested, *this))
14748         return true;
14749       Nested = true;
14750     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14751       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14752                                    BuildAndDiagnose, CaptureType,
14753                                    DeclRefType, Nested, *this))
14754         return true;
14755       Nested = true;
14756     } else {
14757       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14758       if (!captureInLambda(LSI, Var, ExprLoc,
14759                            BuildAndDiagnose, CaptureType,
14760                            DeclRefType, Nested, Kind, EllipsisLoc,
14761                             /*IsTopScope*/I == N - 1, *this))
14762         return true;
14763       Nested = true;
14764     }
14765   }
14766   return false;
14767 }
14768 
14769 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14770                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14771   QualType CaptureType;
14772   QualType DeclRefType;
14773   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14774                             /*BuildAndDiagnose=*/true, CaptureType,
14775                             DeclRefType, nullptr);
14776 }
14777 
14778 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14779   QualType CaptureType;
14780   QualType DeclRefType;
14781   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14782                              /*BuildAndDiagnose=*/false, CaptureType,
14783                              DeclRefType, nullptr);
14784 }
14785 
14786 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14787   QualType CaptureType;
14788   QualType DeclRefType;
14789 
14790   // Determine whether we can capture this variable.
14791   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14792                          /*BuildAndDiagnose=*/false, CaptureType,
14793                          DeclRefType, nullptr))
14794     return QualType();
14795 
14796   return DeclRefType;
14797 }
14798 
14799 
14800 
14801 // If either the type of the variable or the initializer is dependent,
14802 // return false. Otherwise, determine whether the variable is a constant
14803 // expression. Use this if you need to know if a variable that might or
14804 // might not be dependent is truly a constant expression.
14805 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14806     ASTContext &Context) {
14807 
14808   if (Var->getType()->isDependentType())
14809     return false;
14810   const VarDecl *DefVD = nullptr;
14811   Var->getAnyInitializer(DefVD);
14812   if (!DefVD)
14813     return false;
14814   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14815   Expr *Init = cast<Expr>(Eval->Value);
14816   if (Init->isValueDependent())
14817     return false;
14818   return IsVariableAConstantExpression(Var, Context);
14819 }
14820 
14821 
14822 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14823   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14824   // an object that satisfies the requirements for appearing in a
14825   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14826   // is immediately applied."  This function handles the lvalue-to-rvalue
14827   // conversion part.
14828   MaybeODRUseExprs.erase(E->IgnoreParens());
14829 
14830   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14831   // to a variable that is a constant expression, and if so, identify it as
14832   // a reference to a variable that does not involve an odr-use of that
14833   // variable.
14834   if (LambdaScopeInfo *LSI = getCurLambda()) {
14835     Expr *SansParensExpr = E->IgnoreParens();
14836     VarDecl *Var = nullptr;
14837     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14838       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14839     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14840       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14841 
14842     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14843       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14844   }
14845 }
14846 
14847 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14848   Res = CorrectDelayedTyposInExpr(Res);
14849 
14850   if (!Res.isUsable())
14851     return Res;
14852 
14853   // If a constant-expression is a reference to a variable where we delay
14854   // deciding whether it is an odr-use, just assume we will apply the
14855   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14856   // (a non-type template argument), we have special handling anyway.
14857   UpdateMarkingForLValueToRValue(Res.get());
14858   return Res;
14859 }
14860 
14861 void Sema::CleanupVarDeclMarking() {
14862   for (Expr *E : MaybeODRUseExprs) {
14863     VarDecl *Var;
14864     SourceLocation Loc;
14865     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14866       Var = cast<VarDecl>(DRE->getDecl());
14867       Loc = DRE->getLocation();
14868     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14869       Var = cast<VarDecl>(ME->getMemberDecl());
14870       Loc = ME->getMemberLoc();
14871     } else {
14872       llvm_unreachable("Unexpected expression");
14873     }
14874 
14875     MarkVarDeclODRUsed(Var, Loc, *this,
14876                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14877   }
14878 
14879   MaybeODRUseExprs.clear();
14880 }
14881 
14882 
14883 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14884                                     VarDecl *Var, Expr *E) {
14885   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14886          "Invalid Expr argument to DoMarkVarDeclReferenced");
14887   Var->setReferenced();
14888 
14889   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14890 
14891   bool OdrUseContext = isOdrUseContext(SemaRef);
14892   bool UsableInConstantExpr =
14893       Var->isUsableInConstantExpressions(SemaRef.Context);
14894   bool NeedDefinition =
14895       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
14896 
14897   VarTemplateSpecializationDecl *VarSpec =
14898       dyn_cast<VarTemplateSpecializationDecl>(Var);
14899   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14900          "Can't instantiate a partial template specialization.");
14901 
14902   // If this might be a member specialization of a static data member, check
14903   // the specialization is visible. We already did the checks for variable
14904   // template specializations when we created them.
14905   if (NeedDefinition && TSK != TSK_Undeclared &&
14906       !isa<VarTemplateSpecializationDecl>(Var))
14907     SemaRef.checkSpecializationVisibility(Loc, Var);
14908 
14909   // Perform implicit instantiation of static data members, static data member
14910   // templates of class templates, and variable template specializations. Delay
14911   // instantiations of variable templates, except for those that could be used
14912   // in a constant expression.
14913   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14914     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
14915     // instantiation declaration if a variable is usable in a constant
14916     // expression (among other cases).
14917     bool TryInstantiating =
14918         TSK == TSK_ImplicitInstantiation ||
14919         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
14920 
14921     if (TryInstantiating) {
14922       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14923       bool FirstInstantiation = PointOfInstantiation.isInvalid();
14924       if (FirstInstantiation) {
14925         PointOfInstantiation = Loc;
14926         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14927       }
14928 
14929       bool InstantiationDependent = false;
14930       bool IsNonDependent =
14931           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14932                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14933                   : true;
14934 
14935       // Do not instantiate specializations that are still type-dependent.
14936       if (IsNonDependent) {
14937         if (UsableInConstantExpr) {
14938           // Do not defer instantiations of variables that could be used in a
14939           // constant expression.
14940           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14941         } else if (FirstInstantiation ||
14942                    isa<VarTemplateSpecializationDecl>(Var)) {
14943           // FIXME: For a specialization of a variable template, we don't
14944           // distinguish between "declaration and type implicitly instantiated"
14945           // and "implicit instantiation of definition requested", so we have
14946           // no direct way to avoid enqueueing the pending instantiation
14947           // multiple times.
14948           SemaRef.PendingInstantiations
14949               .push_back(std::make_pair(Var, PointOfInstantiation));
14950         }
14951       }
14952     }
14953   }
14954 
14955   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14956   // the requirements for appearing in a constant expression (5.19) and, if
14957   // it is an object, the lvalue-to-rvalue conversion (4.1)
14958   // is immediately applied."  We check the first part here, and
14959   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14960   // Note that we use the C++11 definition everywhere because nothing in
14961   // C++03 depends on whether we get the C++03 version correct. The second
14962   // part does not apply to references, since they are not objects.
14963   if (OdrUseContext && E &&
14964       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14965     // A reference initialized by a constant expression can never be
14966     // odr-used, so simply ignore it.
14967     if (!Var->getType()->isReferenceType() ||
14968         (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var)))
14969       SemaRef.MaybeODRUseExprs.insert(E);
14970   } else if (OdrUseContext) {
14971     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14972                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14973   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14974     // If this is a dependent context, we don't need to mark variables as
14975     // odr-used, but we may still need to track them for lambda capture.
14976     // FIXME: Do we also need to do this inside dependent typeid expressions
14977     // (which are modeled as unevaluated at this point)?
14978     const bool RefersToEnclosingScope =
14979         (SemaRef.CurContext != Var->getDeclContext() &&
14980          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14981     if (RefersToEnclosingScope) {
14982       LambdaScopeInfo *const LSI =
14983           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14984       if (LSI && (!LSI->CallOperator ||
14985                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
14986         // If a variable could potentially be odr-used, defer marking it so
14987         // until we finish analyzing the full expression for any
14988         // lvalue-to-rvalue
14989         // or discarded value conversions that would obviate odr-use.
14990         // Add it to the list of potential captures that will be analyzed
14991         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14992         // unless the variable is a reference that was initialized by a constant
14993         // expression (this will never need to be captured or odr-used).
14994         assert(E && "Capture variable should be used in an expression.");
14995         if (!Var->getType()->isReferenceType() ||
14996             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14997           LSI->addPotentialCapture(E->IgnoreParens());
14998       }
14999     }
15000   }
15001 }
15002 
15003 /// \brief Mark a variable referenced, and check whether it is odr-used
15004 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15005 /// used directly for normal expressions referring to VarDecl.
15006 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15007   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15008 }
15009 
15010 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15011                                Decl *D, Expr *E, bool MightBeOdrUse) {
15012   if (SemaRef.isInOpenMPDeclareTargetContext())
15013     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15014 
15015   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15016     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15017     return;
15018   }
15019 
15020   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15021 
15022   // If this is a call to a method via a cast, also mark the method in the
15023   // derived class used in case codegen can devirtualize the call.
15024   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15025   if (!ME)
15026     return;
15027   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15028   if (!MD)
15029     return;
15030   // Only attempt to devirtualize if this is truly a virtual call.
15031   bool IsVirtualCall = MD->isVirtual() &&
15032                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15033   if (!IsVirtualCall)
15034     return;
15035 
15036   // If it's possible to devirtualize the call, mark the called function
15037   // referenced.
15038   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15039       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15040   if (DM)
15041     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15042 }
15043 
15044 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
15045 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15046   // TODO: update this with DR# once a defect report is filed.
15047   // C++11 defect. The address of a pure member should not be an ODR use, even
15048   // if it's a qualified reference.
15049   bool OdrUse = true;
15050   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15051     if (Method->isVirtual() &&
15052         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15053       OdrUse = false;
15054   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15055 }
15056 
15057 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
15058 void Sema::MarkMemberReferenced(MemberExpr *E) {
15059   // C++11 [basic.def.odr]p2:
15060   //   A non-overloaded function whose name appears as a potentially-evaluated
15061   //   expression or a member of a set of candidate functions, if selected by
15062   //   overload resolution when referred to from a potentially-evaluated
15063   //   expression, is odr-used, unless it is a pure virtual function and its
15064   //   name is not explicitly qualified.
15065   bool MightBeOdrUse = true;
15066   if (E->performsVirtualDispatch(getLangOpts())) {
15067     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15068       if (Method->isPure())
15069         MightBeOdrUse = false;
15070   }
15071   SourceLocation Loc = E->getMemberLoc().isValid() ?
15072                             E->getMemberLoc() : E->getLocStart();
15073   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15074 }
15075 
15076 /// \brief Perform marking for a reference to an arbitrary declaration.  It
15077 /// marks the declaration referenced, and performs odr-use checking for
15078 /// functions and variables. This method should not be used when building a
15079 /// normal expression which refers to a variable.
15080 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15081                                  bool MightBeOdrUse) {
15082   if (MightBeOdrUse) {
15083     if (auto *VD = dyn_cast<VarDecl>(D)) {
15084       MarkVariableReferenced(Loc, VD);
15085       return;
15086     }
15087   }
15088   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15089     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15090     return;
15091   }
15092   D->setReferenced();
15093 }
15094 
15095 namespace {
15096   // Mark all of the declarations used by a type as referenced.
15097   // FIXME: Not fully implemented yet! We need to have a better understanding
15098   // of when we're entering a context we should not recurse into.
15099   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15100   // TreeTransforms rebuilding the type in a new context. Rather than
15101   // duplicating the TreeTransform logic, we should consider reusing it here.
15102   // Currently that causes problems when rebuilding LambdaExprs.
15103   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15104     Sema &S;
15105     SourceLocation Loc;
15106 
15107   public:
15108     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15109 
15110     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15111 
15112     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15113   };
15114 }
15115 
15116 bool MarkReferencedDecls::TraverseTemplateArgument(
15117     const TemplateArgument &Arg) {
15118   {
15119     // A non-type template argument is a constant-evaluated context.
15120     EnterExpressionEvaluationContext Evaluated(
15121         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15122     if (Arg.getKind() == TemplateArgument::Declaration) {
15123       if (Decl *D = Arg.getAsDecl())
15124         S.MarkAnyDeclReferenced(Loc, D, true);
15125     } else if (Arg.getKind() == TemplateArgument::Expression) {
15126       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15127     }
15128   }
15129 
15130   return Inherited::TraverseTemplateArgument(Arg);
15131 }
15132 
15133 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15134   MarkReferencedDecls Marker(*this, Loc);
15135   Marker.TraverseType(T);
15136 }
15137 
15138 namespace {
15139   /// \brief Helper class that marks all of the declarations referenced by
15140   /// potentially-evaluated subexpressions as "referenced".
15141   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15142     Sema &S;
15143     bool SkipLocalVariables;
15144 
15145   public:
15146     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15147 
15148     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15149       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15150 
15151     void VisitDeclRefExpr(DeclRefExpr *E) {
15152       // If we were asked not to visit local variables, don't.
15153       if (SkipLocalVariables) {
15154         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15155           if (VD->hasLocalStorage())
15156             return;
15157       }
15158 
15159       S.MarkDeclRefReferenced(E);
15160     }
15161 
15162     void VisitMemberExpr(MemberExpr *E) {
15163       S.MarkMemberReferenced(E);
15164       Inherited::VisitMemberExpr(E);
15165     }
15166 
15167     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15168       S.MarkFunctionReferenced(E->getLocStart(),
15169             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15170       Visit(E->getSubExpr());
15171     }
15172 
15173     void VisitCXXNewExpr(CXXNewExpr *E) {
15174       if (E->getOperatorNew())
15175         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15176       if (E->getOperatorDelete())
15177         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15178       Inherited::VisitCXXNewExpr(E);
15179     }
15180 
15181     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15182       if (E->getOperatorDelete())
15183         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15184       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15185       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15186         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15187         S.MarkFunctionReferenced(E->getLocStart(),
15188                                     S.LookupDestructor(Record));
15189       }
15190 
15191       Inherited::VisitCXXDeleteExpr(E);
15192     }
15193 
15194     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15195       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15196       Inherited::VisitCXXConstructExpr(E);
15197     }
15198 
15199     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15200       Visit(E->getExpr());
15201     }
15202 
15203     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15204       Inherited::VisitImplicitCastExpr(E);
15205 
15206       if (E->getCastKind() == CK_LValueToRValue)
15207         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15208     }
15209   };
15210 }
15211 
15212 /// \brief Mark any declarations that appear within this expression or any
15213 /// potentially-evaluated subexpressions as "referenced".
15214 ///
15215 /// \param SkipLocalVariables If true, don't mark local variables as
15216 /// 'referenced'.
15217 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15218                                             bool SkipLocalVariables) {
15219   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15220 }
15221 
15222 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
15223 /// of the program being compiled.
15224 ///
15225 /// This routine emits the given diagnostic when the code currently being
15226 /// type-checked is "potentially evaluated", meaning that there is a
15227 /// possibility that the code will actually be executable. Code in sizeof()
15228 /// expressions, code used only during overload resolution, etc., are not
15229 /// potentially evaluated. This routine will suppress such diagnostics or,
15230 /// in the absolutely nutty case of potentially potentially evaluated
15231 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15232 /// later.
15233 ///
15234 /// This routine should be used for all diagnostics that describe the run-time
15235 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15236 /// Failure to do so will likely result in spurious diagnostics or failures
15237 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15238 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15239                                const PartialDiagnostic &PD) {
15240   switch (ExprEvalContexts.back().Context) {
15241   case ExpressionEvaluationContext::Unevaluated:
15242   case ExpressionEvaluationContext::UnevaluatedList:
15243   case ExpressionEvaluationContext::UnevaluatedAbstract:
15244   case ExpressionEvaluationContext::DiscardedStatement:
15245     // The argument will never be evaluated, so don't complain.
15246     break;
15247 
15248   case ExpressionEvaluationContext::ConstantEvaluated:
15249     // Relevant diagnostics should be produced by constant evaluation.
15250     break;
15251 
15252   case ExpressionEvaluationContext::PotentiallyEvaluated:
15253   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15254     if (Statement && getCurFunctionOrMethodDecl()) {
15255       FunctionScopes.back()->PossiblyUnreachableDiags.
15256         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15257       return true;
15258     }
15259 
15260     // The initializer of a constexpr variable or of the first declaration of a
15261     // static data member is not syntactically a constant evaluated constant,
15262     // but nonetheless is always required to be a constant expression, so we
15263     // can skip diagnosing.
15264     // FIXME: Using the mangling context here is a hack.
15265     if (auto *VD = dyn_cast_or_null<VarDecl>(
15266             ExprEvalContexts.back().ManglingContextDecl)) {
15267       if (VD->isConstexpr() ||
15268           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15269         break;
15270       // FIXME: For any other kind of variable, we should build a CFG for its
15271       // initializer and check whether the context in question is reachable.
15272     }
15273 
15274     Diag(Loc, PD);
15275     return true;
15276   }
15277 
15278   return false;
15279 }
15280 
15281 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15282                                CallExpr *CE, FunctionDecl *FD) {
15283   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15284     return false;
15285 
15286   // If we're inside a decltype's expression, don't check for a valid return
15287   // type or construct temporaries until we know whether this is the last call.
15288   if (ExprEvalContexts.back().IsDecltype) {
15289     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15290     return false;
15291   }
15292 
15293   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15294     FunctionDecl *FD;
15295     CallExpr *CE;
15296 
15297   public:
15298     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15299       : FD(FD), CE(CE) { }
15300 
15301     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15302       if (!FD) {
15303         S.Diag(Loc, diag::err_call_incomplete_return)
15304           << T << CE->getSourceRange();
15305         return;
15306       }
15307 
15308       S.Diag(Loc, diag::err_call_function_incomplete_return)
15309         << CE->getSourceRange() << FD->getDeclName() << T;
15310       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15311           << FD->getDeclName();
15312     }
15313   } Diagnoser(FD, CE);
15314 
15315   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15316     return true;
15317 
15318   return false;
15319 }
15320 
15321 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15322 // will prevent this condition from triggering, which is what we want.
15323 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15324   SourceLocation Loc;
15325 
15326   unsigned diagnostic = diag::warn_condition_is_assignment;
15327   bool IsOrAssign = false;
15328 
15329   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15330     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15331       return;
15332 
15333     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15334 
15335     // Greylist some idioms by putting them into a warning subcategory.
15336     if (ObjCMessageExpr *ME
15337           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15338       Selector Sel = ME->getSelector();
15339 
15340       // self = [<foo> init...]
15341       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15342         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15343 
15344       // <foo> = [<bar> nextObject]
15345       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15346         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15347     }
15348 
15349     Loc = Op->getOperatorLoc();
15350   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15351     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15352       return;
15353 
15354     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15355     Loc = Op->getOperatorLoc();
15356   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15357     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15358   else {
15359     // Not an assignment.
15360     return;
15361   }
15362 
15363   Diag(Loc, diagnostic) << E->getSourceRange();
15364 
15365   SourceLocation Open = E->getLocStart();
15366   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15367   Diag(Loc, diag::note_condition_assign_silence)
15368         << FixItHint::CreateInsertion(Open, "(")
15369         << FixItHint::CreateInsertion(Close, ")");
15370 
15371   if (IsOrAssign)
15372     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15373       << FixItHint::CreateReplacement(Loc, "!=");
15374   else
15375     Diag(Loc, diag::note_condition_assign_to_comparison)
15376       << FixItHint::CreateReplacement(Loc, "==");
15377 }
15378 
15379 /// \brief Redundant parentheses over an equality comparison can indicate
15380 /// that the user intended an assignment used as condition.
15381 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15382   // Don't warn if the parens came from a macro.
15383   SourceLocation parenLoc = ParenE->getLocStart();
15384   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15385     return;
15386   // Don't warn for dependent expressions.
15387   if (ParenE->isTypeDependent())
15388     return;
15389 
15390   Expr *E = ParenE->IgnoreParens();
15391 
15392   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15393     if (opE->getOpcode() == BO_EQ &&
15394         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15395                                                            == Expr::MLV_Valid) {
15396       SourceLocation Loc = opE->getOperatorLoc();
15397 
15398       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15399       SourceRange ParenERange = ParenE->getSourceRange();
15400       Diag(Loc, diag::note_equality_comparison_silence)
15401         << FixItHint::CreateRemoval(ParenERange.getBegin())
15402         << FixItHint::CreateRemoval(ParenERange.getEnd());
15403       Diag(Loc, diag::note_equality_comparison_to_assign)
15404         << FixItHint::CreateReplacement(Loc, "=");
15405     }
15406 }
15407 
15408 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15409                                        bool IsConstexpr) {
15410   DiagnoseAssignmentAsCondition(E);
15411   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15412     DiagnoseEqualityWithExtraParens(parenE);
15413 
15414   ExprResult result = CheckPlaceholderExpr(E);
15415   if (result.isInvalid()) return ExprError();
15416   E = result.get();
15417 
15418   if (!E->isTypeDependent()) {
15419     if (getLangOpts().CPlusPlus)
15420       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15421 
15422     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15423     if (ERes.isInvalid())
15424       return ExprError();
15425     E = ERes.get();
15426 
15427     QualType T = E->getType();
15428     if (!T->isScalarType()) { // C99 6.8.4.1p1
15429       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15430         << T << E->getSourceRange();
15431       return ExprError();
15432     }
15433     CheckBoolLikeConversion(E, Loc);
15434   }
15435 
15436   return E;
15437 }
15438 
15439 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15440                                            Expr *SubExpr, ConditionKind CK) {
15441   // Empty conditions are valid in for-statements.
15442   if (!SubExpr)
15443     return ConditionResult();
15444 
15445   ExprResult Cond;
15446   switch (CK) {
15447   case ConditionKind::Boolean:
15448     Cond = CheckBooleanCondition(Loc, SubExpr);
15449     break;
15450 
15451   case ConditionKind::ConstexprIf:
15452     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15453     break;
15454 
15455   case ConditionKind::Switch:
15456     Cond = CheckSwitchCondition(Loc, SubExpr);
15457     break;
15458   }
15459   if (Cond.isInvalid())
15460     return ConditionError();
15461 
15462   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15463   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15464   if (!FullExpr.get())
15465     return ConditionError();
15466 
15467   return ConditionResult(*this, nullptr, FullExpr,
15468                          CK == ConditionKind::ConstexprIf);
15469 }
15470 
15471 namespace {
15472   /// A visitor for rebuilding a call to an __unknown_any expression
15473   /// to have an appropriate type.
15474   struct RebuildUnknownAnyFunction
15475     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15476 
15477     Sema &S;
15478 
15479     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15480 
15481     ExprResult VisitStmt(Stmt *S) {
15482       llvm_unreachable("unexpected statement!");
15483     }
15484 
15485     ExprResult VisitExpr(Expr *E) {
15486       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15487         << E->getSourceRange();
15488       return ExprError();
15489     }
15490 
15491     /// Rebuild an expression which simply semantically wraps another
15492     /// expression which it shares the type and value kind of.
15493     template <class T> ExprResult rebuildSugarExpr(T *E) {
15494       ExprResult SubResult = Visit(E->getSubExpr());
15495       if (SubResult.isInvalid()) return ExprError();
15496 
15497       Expr *SubExpr = SubResult.get();
15498       E->setSubExpr(SubExpr);
15499       E->setType(SubExpr->getType());
15500       E->setValueKind(SubExpr->getValueKind());
15501       assert(E->getObjectKind() == OK_Ordinary);
15502       return E;
15503     }
15504 
15505     ExprResult VisitParenExpr(ParenExpr *E) {
15506       return rebuildSugarExpr(E);
15507     }
15508 
15509     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15510       return rebuildSugarExpr(E);
15511     }
15512 
15513     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15514       ExprResult SubResult = Visit(E->getSubExpr());
15515       if (SubResult.isInvalid()) return ExprError();
15516 
15517       Expr *SubExpr = SubResult.get();
15518       E->setSubExpr(SubExpr);
15519       E->setType(S.Context.getPointerType(SubExpr->getType()));
15520       assert(E->getValueKind() == VK_RValue);
15521       assert(E->getObjectKind() == OK_Ordinary);
15522       return E;
15523     }
15524 
15525     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15526       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15527 
15528       E->setType(VD->getType());
15529 
15530       assert(E->getValueKind() == VK_RValue);
15531       if (S.getLangOpts().CPlusPlus &&
15532           !(isa<CXXMethodDecl>(VD) &&
15533             cast<CXXMethodDecl>(VD)->isInstance()))
15534         E->setValueKind(VK_LValue);
15535 
15536       return E;
15537     }
15538 
15539     ExprResult VisitMemberExpr(MemberExpr *E) {
15540       return resolveDecl(E, E->getMemberDecl());
15541     }
15542 
15543     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15544       return resolveDecl(E, E->getDecl());
15545     }
15546   };
15547 }
15548 
15549 /// Given a function expression of unknown-any type, try to rebuild it
15550 /// to have a function type.
15551 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15552   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15553   if (Result.isInvalid()) return ExprError();
15554   return S.DefaultFunctionArrayConversion(Result.get());
15555 }
15556 
15557 namespace {
15558   /// A visitor for rebuilding an expression of type __unknown_anytype
15559   /// into one which resolves the type directly on the referring
15560   /// expression.  Strict preservation of the original source
15561   /// structure is not a goal.
15562   struct RebuildUnknownAnyExpr
15563     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15564 
15565     Sema &S;
15566 
15567     /// The current destination type.
15568     QualType DestType;
15569 
15570     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15571       : S(S), DestType(CastType) {}
15572 
15573     ExprResult VisitStmt(Stmt *S) {
15574       llvm_unreachable("unexpected statement!");
15575     }
15576 
15577     ExprResult VisitExpr(Expr *E) {
15578       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15579         << E->getSourceRange();
15580       return ExprError();
15581     }
15582 
15583     ExprResult VisitCallExpr(CallExpr *E);
15584     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15585 
15586     /// Rebuild an expression which simply semantically wraps another
15587     /// expression which it shares the type and value kind of.
15588     template <class T> ExprResult rebuildSugarExpr(T *E) {
15589       ExprResult SubResult = Visit(E->getSubExpr());
15590       if (SubResult.isInvalid()) return ExprError();
15591       Expr *SubExpr = SubResult.get();
15592       E->setSubExpr(SubExpr);
15593       E->setType(SubExpr->getType());
15594       E->setValueKind(SubExpr->getValueKind());
15595       assert(E->getObjectKind() == OK_Ordinary);
15596       return E;
15597     }
15598 
15599     ExprResult VisitParenExpr(ParenExpr *E) {
15600       return rebuildSugarExpr(E);
15601     }
15602 
15603     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15604       return rebuildSugarExpr(E);
15605     }
15606 
15607     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15608       const PointerType *Ptr = DestType->getAs<PointerType>();
15609       if (!Ptr) {
15610         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15611           << E->getSourceRange();
15612         return ExprError();
15613       }
15614 
15615       if (isa<CallExpr>(E->getSubExpr())) {
15616         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15617           << E->getSourceRange();
15618         return ExprError();
15619       }
15620 
15621       assert(E->getValueKind() == VK_RValue);
15622       assert(E->getObjectKind() == OK_Ordinary);
15623       E->setType(DestType);
15624 
15625       // Build the sub-expression as if it were an object of the pointee type.
15626       DestType = Ptr->getPointeeType();
15627       ExprResult SubResult = Visit(E->getSubExpr());
15628       if (SubResult.isInvalid()) return ExprError();
15629       E->setSubExpr(SubResult.get());
15630       return E;
15631     }
15632 
15633     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15634 
15635     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15636 
15637     ExprResult VisitMemberExpr(MemberExpr *E) {
15638       return resolveDecl(E, E->getMemberDecl());
15639     }
15640 
15641     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15642       return resolveDecl(E, E->getDecl());
15643     }
15644   };
15645 }
15646 
15647 /// Rebuilds a call expression which yielded __unknown_anytype.
15648 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15649   Expr *CalleeExpr = E->getCallee();
15650 
15651   enum FnKind {
15652     FK_MemberFunction,
15653     FK_FunctionPointer,
15654     FK_BlockPointer
15655   };
15656 
15657   FnKind Kind;
15658   QualType CalleeType = CalleeExpr->getType();
15659   if (CalleeType == S.Context.BoundMemberTy) {
15660     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15661     Kind = FK_MemberFunction;
15662     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15663   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15664     CalleeType = Ptr->getPointeeType();
15665     Kind = FK_FunctionPointer;
15666   } else {
15667     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15668     Kind = FK_BlockPointer;
15669   }
15670   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15671 
15672   // Verify that this is a legal result type of a function.
15673   if (DestType->isArrayType() || DestType->isFunctionType()) {
15674     unsigned diagID = diag::err_func_returning_array_function;
15675     if (Kind == FK_BlockPointer)
15676       diagID = diag::err_block_returning_array_function;
15677 
15678     S.Diag(E->getExprLoc(), diagID)
15679       << DestType->isFunctionType() << DestType;
15680     return ExprError();
15681   }
15682 
15683   // Otherwise, go ahead and set DestType as the call's result.
15684   E->setType(DestType.getNonLValueExprType(S.Context));
15685   E->setValueKind(Expr::getValueKindForType(DestType));
15686   assert(E->getObjectKind() == OK_Ordinary);
15687 
15688   // Rebuild the function type, replacing the result type with DestType.
15689   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15690   if (Proto) {
15691     // __unknown_anytype(...) is a special case used by the debugger when
15692     // it has no idea what a function's signature is.
15693     //
15694     // We want to build this call essentially under the K&R
15695     // unprototyped rules, but making a FunctionNoProtoType in C++
15696     // would foul up all sorts of assumptions.  However, we cannot
15697     // simply pass all arguments as variadic arguments, nor can we
15698     // portably just call the function under a non-variadic type; see
15699     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15700     // However, it turns out that in practice it is generally safe to
15701     // call a function declared as "A foo(B,C,D);" under the prototype
15702     // "A foo(B,C,D,...);".  The only known exception is with the
15703     // Windows ABI, where any variadic function is implicitly cdecl
15704     // regardless of its normal CC.  Therefore we change the parameter
15705     // types to match the types of the arguments.
15706     //
15707     // This is a hack, but it is far superior to moving the
15708     // corresponding target-specific code from IR-gen to Sema/AST.
15709 
15710     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15711     SmallVector<QualType, 8> ArgTypes;
15712     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15713       ArgTypes.reserve(E->getNumArgs());
15714       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15715         Expr *Arg = E->getArg(i);
15716         QualType ArgType = Arg->getType();
15717         if (E->isLValue()) {
15718           ArgType = S.Context.getLValueReferenceType(ArgType);
15719         } else if (E->isXValue()) {
15720           ArgType = S.Context.getRValueReferenceType(ArgType);
15721         }
15722         ArgTypes.push_back(ArgType);
15723       }
15724       ParamTypes = ArgTypes;
15725     }
15726     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15727                                          Proto->getExtProtoInfo());
15728   } else {
15729     DestType = S.Context.getFunctionNoProtoType(DestType,
15730                                                 FnType->getExtInfo());
15731   }
15732 
15733   // Rebuild the appropriate pointer-to-function type.
15734   switch (Kind) {
15735   case FK_MemberFunction:
15736     // Nothing to do.
15737     break;
15738 
15739   case FK_FunctionPointer:
15740     DestType = S.Context.getPointerType(DestType);
15741     break;
15742 
15743   case FK_BlockPointer:
15744     DestType = S.Context.getBlockPointerType(DestType);
15745     break;
15746   }
15747 
15748   // Finally, we can recurse.
15749   ExprResult CalleeResult = Visit(CalleeExpr);
15750   if (!CalleeResult.isUsable()) return ExprError();
15751   E->setCallee(CalleeResult.get());
15752 
15753   // Bind a temporary if necessary.
15754   return S.MaybeBindToTemporary(E);
15755 }
15756 
15757 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15758   // Verify that this is a legal result type of a call.
15759   if (DestType->isArrayType() || DestType->isFunctionType()) {
15760     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15761       << DestType->isFunctionType() << DestType;
15762     return ExprError();
15763   }
15764 
15765   // Rewrite the method result type if available.
15766   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15767     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15768     Method->setReturnType(DestType);
15769   }
15770 
15771   // Change the type of the message.
15772   E->setType(DestType.getNonReferenceType());
15773   E->setValueKind(Expr::getValueKindForType(DestType));
15774 
15775   return S.MaybeBindToTemporary(E);
15776 }
15777 
15778 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15779   // The only case we should ever see here is a function-to-pointer decay.
15780   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15781     assert(E->getValueKind() == VK_RValue);
15782     assert(E->getObjectKind() == OK_Ordinary);
15783 
15784     E->setType(DestType);
15785 
15786     // Rebuild the sub-expression as the pointee (function) type.
15787     DestType = DestType->castAs<PointerType>()->getPointeeType();
15788 
15789     ExprResult Result = Visit(E->getSubExpr());
15790     if (!Result.isUsable()) return ExprError();
15791 
15792     E->setSubExpr(Result.get());
15793     return E;
15794   } else if (E->getCastKind() == CK_LValueToRValue) {
15795     assert(E->getValueKind() == VK_RValue);
15796     assert(E->getObjectKind() == OK_Ordinary);
15797 
15798     assert(isa<BlockPointerType>(E->getType()));
15799 
15800     E->setType(DestType);
15801 
15802     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15803     DestType = S.Context.getLValueReferenceType(DestType);
15804 
15805     ExprResult Result = Visit(E->getSubExpr());
15806     if (!Result.isUsable()) return ExprError();
15807 
15808     E->setSubExpr(Result.get());
15809     return E;
15810   } else {
15811     llvm_unreachable("Unhandled cast type!");
15812   }
15813 }
15814 
15815 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15816   ExprValueKind ValueKind = VK_LValue;
15817   QualType Type = DestType;
15818 
15819   // We know how to make this work for certain kinds of decls:
15820 
15821   //  - functions
15822   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15823     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15824       DestType = Ptr->getPointeeType();
15825       ExprResult Result = resolveDecl(E, VD);
15826       if (Result.isInvalid()) return ExprError();
15827       return S.ImpCastExprToType(Result.get(), Type,
15828                                  CK_FunctionToPointerDecay, VK_RValue);
15829     }
15830 
15831     if (!Type->isFunctionType()) {
15832       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15833         << VD << E->getSourceRange();
15834       return ExprError();
15835     }
15836     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15837       // We must match the FunctionDecl's type to the hack introduced in
15838       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15839       // type. See the lengthy commentary in that routine.
15840       QualType FDT = FD->getType();
15841       const FunctionType *FnType = FDT->castAs<FunctionType>();
15842       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15843       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15844       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15845         SourceLocation Loc = FD->getLocation();
15846         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15847                                       FD->getDeclContext(),
15848                                       Loc, Loc, FD->getNameInfo().getName(),
15849                                       DestType, FD->getTypeSourceInfo(),
15850                                       SC_None, false/*isInlineSpecified*/,
15851                                       FD->hasPrototype(),
15852                                       false/*isConstexprSpecified*/);
15853 
15854         if (FD->getQualifier())
15855           NewFD->setQualifierInfo(FD->getQualifierLoc());
15856 
15857         SmallVector<ParmVarDecl*, 16> Params;
15858         for (const auto &AI : FT->param_types()) {
15859           ParmVarDecl *Param =
15860             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15861           Param->setScopeInfo(0, Params.size());
15862           Params.push_back(Param);
15863         }
15864         NewFD->setParams(Params);
15865         DRE->setDecl(NewFD);
15866         VD = DRE->getDecl();
15867       }
15868     }
15869 
15870     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15871       if (MD->isInstance()) {
15872         ValueKind = VK_RValue;
15873         Type = S.Context.BoundMemberTy;
15874       }
15875 
15876     // Function references aren't l-values in C.
15877     if (!S.getLangOpts().CPlusPlus)
15878       ValueKind = VK_RValue;
15879 
15880   //  - variables
15881   } else if (isa<VarDecl>(VD)) {
15882     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15883       Type = RefTy->getPointeeType();
15884     } else if (Type->isFunctionType()) {
15885       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15886         << VD << E->getSourceRange();
15887       return ExprError();
15888     }
15889 
15890   //  - nothing else
15891   } else {
15892     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15893       << VD << E->getSourceRange();
15894     return ExprError();
15895   }
15896 
15897   // Modifying the declaration like this is friendly to IR-gen but
15898   // also really dangerous.
15899   VD->setType(DestType);
15900   E->setType(Type);
15901   E->setValueKind(ValueKind);
15902   return E;
15903 }
15904 
15905 /// Check a cast of an unknown-any type.  We intentionally only
15906 /// trigger this for C-style casts.
15907 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15908                                      Expr *CastExpr, CastKind &CastKind,
15909                                      ExprValueKind &VK, CXXCastPath &Path) {
15910   // The type we're casting to must be either void or complete.
15911   if (!CastType->isVoidType() &&
15912       RequireCompleteType(TypeRange.getBegin(), CastType,
15913                           diag::err_typecheck_cast_to_incomplete))
15914     return ExprError();
15915 
15916   // Rewrite the casted expression from scratch.
15917   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15918   if (!result.isUsable()) return ExprError();
15919 
15920   CastExpr = result.get();
15921   VK = CastExpr->getValueKind();
15922   CastKind = CK_NoOp;
15923 
15924   return CastExpr;
15925 }
15926 
15927 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15928   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15929 }
15930 
15931 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15932                                     Expr *arg, QualType &paramType) {
15933   // If the syntactic form of the argument is not an explicit cast of
15934   // any sort, just do default argument promotion.
15935   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15936   if (!castArg) {
15937     ExprResult result = DefaultArgumentPromotion(arg);
15938     if (result.isInvalid()) return ExprError();
15939     paramType = result.get()->getType();
15940     return result;
15941   }
15942 
15943   // Otherwise, use the type that was written in the explicit cast.
15944   assert(!arg->hasPlaceholderType());
15945   paramType = castArg->getTypeAsWritten();
15946 
15947   // Copy-initialize a parameter of that type.
15948   InitializedEntity entity =
15949     InitializedEntity::InitializeParameter(Context, paramType,
15950                                            /*consumed*/ false);
15951   return PerformCopyInitialization(entity, callLoc, arg);
15952 }
15953 
15954 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15955   Expr *orig = E;
15956   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15957   while (true) {
15958     E = E->IgnoreParenImpCasts();
15959     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15960       E = call->getCallee();
15961       diagID = diag::err_uncasted_call_of_unknown_any;
15962     } else {
15963       break;
15964     }
15965   }
15966 
15967   SourceLocation loc;
15968   NamedDecl *d;
15969   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15970     loc = ref->getLocation();
15971     d = ref->getDecl();
15972   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15973     loc = mem->getMemberLoc();
15974     d = mem->getMemberDecl();
15975   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15976     diagID = diag::err_uncasted_call_of_unknown_any;
15977     loc = msg->getSelectorStartLoc();
15978     d = msg->getMethodDecl();
15979     if (!d) {
15980       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15981         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15982         << orig->getSourceRange();
15983       return ExprError();
15984     }
15985   } else {
15986     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15987       << E->getSourceRange();
15988     return ExprError();
15989   }
15990 
15991   S.Diag(loc, diagID) << d << orig->getSourceRange();
15992 
15993   // Never recoverable.
15994   return ExprError();
15995 }
15996 
15997 /// Check for operands with placeholder types and complain if found.
15998 /// Returns ExprError() if there was an error and no recovery was possible.
15999 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16000   if (!getLangOpts().CPlusPlus) {
16001     // C cannot handle TypoExpr nodes on either side of a binop because it
16002     // doesn't handle dependent types properly, so make sure any TypoExprs have
16003     // been dealt with before checking the operands.
16004     ExprResult Result = CorrectDelayedTyposInExpr(E);
16005     if (!Result.isUsable()) return ExprError();
16006     E = Result.get();
16007   }
16008 
16009   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16010   if (!placeholderType) return E;
16011 
16012   switch (placeholderType->getKind()) {
16013 
16014   // Overloaded expressions.
16015   case BuiltinType::Overload: {
16016     // Try to resolve a single function template specialization.
16017     // This is obligatory.
16018     ExprResult Result = E;
16019     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16020       return Result;
16021 
16022     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16023     // leaves Result unchanged on failure.
16024     Result = E;
16025     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16026       return Result;
16027 
16028     // If that failed, try to recover with a call.
16029     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16030                          /*complain*/ true);
16031     return Result;
16032   }
16033 
16034   // Bound member functions.
16035   case BuiltinType::BoundMember: {
16036     ExprResult result = E;
16037     const Expr *BME = E->IgnoreParens();
16038     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16039     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16040     if (isa<CXXPseudoDestructorExpr>(BME)) {
16041       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16042     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16043       if (ME->getMemberNameInfo().getName().getNameKind() ==
16044           DeclarationName::CXXDestructorName)
16045         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16046     }
16047     tryToRecoverWithCall(result, PD,
16048                          /*complain*/ true);
16049     return result;
16050   }
16051 
16052   // ARC unbridged casts.
16053   case BuiltinType::ARCUnbridgedCast: {
16054     Expr *realCast = stripARCUnbridgedCast(E);
16055     diagnoseARCUnbridgedCast(realCast);
16056     return realCast;
16057   }
16058 
16059   // Expressions of unknown type.
16060   case BuiltinType::UnknownAny:
16061     return diagnoseUnknownAnyExpr(*this, E);
16062 
16063   // Pseudo-objects.
16064   case BuiltinType::PseudoObject:
16065     return checkPseudoObjectRValue(E);
16066 
16067   case BuiltinType::BuiltinFn: {
16068     // Accept __noop without parens by implicitly converting it to a call expr.
16069     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16070     if (DRE) {
16071       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16072       if (FD->getBuiltinID() == Builtin::BI__noop) {
16073         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16074                               CK_BuiltinFnToFnPtr).get();
16075         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16076                                       VK_RValue, SourceLocation());
16077       }
16078     }
16079 
16080     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16081     return ExprError();
16082   }
16083 
16084   // Expressions of unknown type.
16085   case BuiltinType::OMPArraySection:
16086     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16087     return ExprError();
16088 
16089   // Everything else should be impossible.
16090 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16091   case BuiltinType::Id:
16092 #include "clang/Basic/OpenCLImageTypes.def"
16093 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16094 #define PLACEHOLDER_TYPE(Id, SingletonId)
16095 #include "clang/AST/BuiltinTypes.def"
16096     break;
16097   }
16098 
16099   llvm_unreachable("invalid placeholder type!");
16100 }
16101 
16102 bool Sema::CheckCaseExpression(Expr *E) {
16103   if (E->isTypeDependent())
16104     return true;
16105   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16106     return E->getType()->isIntegralOrEnumerationType();
16107   return false;
16108 }
16109 
16110 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16111 ExprResult
16112 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16113   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16114          "Unknown Objective-C Boolean value!");
16115   QualType BoolT = Context.ObjCBuiltinBoolTy;
16116   if (!Context.getBOOLDecl()) {
16117     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16118                         Sema::LookupOrdinaryName);
16119     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16120       NamedDecl *ND = Result.getFoundDecl();
16121       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16122         Context.setBOOLDecl(TD);
16123     }
16124   }
16125   if (Context.getBOOLDecl())
16126     BoolT = Context.getBOOLType();
16127   return new (Context)
16128       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16129 }
16130 
16131 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16132     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16133     SourceLocation RParen) {
16134 
16135   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16136 
16137   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16138                            [&](const AvailabilitySpec &Spec) {
16139                              return Spec.getPlatform() == Platform;
16140                            });
16141 
16142   VersionTuple Version;
16143   if (Spec != AvailSpecs.end())
16144     Version = Spec->getVersion();
16145 
16146   // The use of `@available` in the enclosing function should be analyzed to
16147   // warn when it's used inappropriately (i.e. not if(@available)).
16148   if (getCurFunctionOrMethodDecl())
16149     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16150   else if (getCurBlock() || getCurLambda())
16151     getCurFunction()->HasPotentialAvailabilityViolations = true;
16152 
16153   return new (Context)
16154       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16155 }
16156