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, ArrayRef<SourceLocation> Locs,
205                              const ObjCInterfaceDecl *UnknownObjCClass,
206                              bool ObjCPropertyAccess,
207                              bool AvoidPartialAvailabilityChecks) {
208   SourceLocation Loc = Locs.front();
209   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
210     // If there were any diagnostics suppressed by template argument deduction,
211     // emit them now.
212     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
213     if (Pos != SuppressedDiagnostics.end()) {
214       for (const PartialDiagnosticAt &Suppressed : Pos->second)
215         Diag(Suppressed.first, Suppressed.second);
216 
217       // Clear out the list of suppressed diagnostics, so that we don't emit
218       // them again for this specialization. However, we don't obsolete this
219       // entry from the table, because we want to avoid ever emitting these
220       // diagnostics again.
221       Pos->second.clear();
222     }
223 
224     // C++ [basic.start.main]p3:
225     //   The function 'main' shall not be used within a program.
226     if (cast<FunctionDecl>(D)->isMain())
227       Diag(Loc, diag::ext_main_used);
228   }
229 
230   // See if this is an auto-typed variable whose initializer we are parsing.
231   if (ParsingInitForAutoVars.count(D)) {
232     if (isa<BindingDecl>(D)) {
233       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
234         << D->getDeclName();
235     } else {
236       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
237         << D->getDeclName() << cast<VarDecl>(D)->getType();
238     }
239     return true;
240   }
241 
242   // See if this is a deleted function.
243   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244     if (FD->isDeleted()) {
245       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
246       if (Ctor && Ctor->isInheritingConstructor())
247         Diag(Loc, diag::err_deleted_inherited_ctor_use)
248             << Ctor->getParent()
249             << Ctor->getInheritedConstructor().getConstructor()->getParent();
250       else
251         Diag(Loc, diag::err_deleted_function_use);
252       NoteDeletedFunction(FD);
253       return true;
254     }
255 
256     // If the function has a deduced return type, and we can't deduce it,
257     // then we can't use it either.
258     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
259         DeduceReturnType(FD, Loc))
260       return true;
261 
262     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
263       return true;
264   }
265 
266   auto getReferencedObjCProp = [](const NamedDecl *D) ->
267                                       const ObjCPropertyDecl * {
268     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
269       return MD->findPropertyDecl();
270     return nullptr;
271   };
272   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
273     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
274       return true;
275   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
276       return true;
277   }
278 
279   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
280   // Only the variables omp_in and omp_out are allowed in the combiner.
281   // Only the variables omp_priv and omp_orig are allowed in the
282   // initializer-clause.
283   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
284   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
285       isa<VarDecl>(D)) {
286     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
287         << getCurFunction()->HasOMPDeclareReductionCombiner;
288     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
289     return true;
290   }
291 
292   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
293                              AvoidPartialAvailabilityChecks);
294 
295   DiagnoseUnusedOfDecl(*this, D, Loc);
296 
297   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
298 
299   return false;
300 }
301 
302 /// \brief Retrieve the message suffix that should be added to a
303 /// diagnostic complaining about the given function being deleted or
304 /// unavailable.
305 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
306   std::string Message;
307   if (FD->getAvailability(&Message))
308     return ": " + Message;
309 
310   return std::string();
311 }
312 
313 /// DiagnoseSentinelCalls - This routine checks whether a call or
314 /// message-send is to a declaration with the sentinel attribute, and
315 /// if so, it checks that the requirements of the sentinel are
316 /// satisfied.
317 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
318                                  ArrayRef<Expr *> Args) {
319   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
320   if (!attr)
321     return;
322 
323   // The number of formal parameters of the declaration.
324   unsigned numFormalParams;
325 
326   // The kind of declaration.  This is also an index into a %select in
327   // the diagnostic.
328   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
329 
330   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
331     numFormalParams = MD->param_size();
332     calleeType = CT_Method;
333   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
334     numFormalParams = FD->param_size();
335     calleeType = CT_Function;
336   } else if (isa<VarDecl>(D)) {
337     QualType type = cast<ValueDecl>(D)->getType();
338     const FunctionType *fn = nullptr;
339     if (const PointerType *ptr = type->getAs<PointerType>()) {
340       fn = ptr->getPointeeType()->getAs<FunctionType>();
341       if (!fn) return;
342       calleeType = CT_Function;
343     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
344       fn = ptr->getPointeeType()->castAs<FunctionType>();
345       calleeType = CT_Block;
346     } else {
347       return;
348     }
349 
350     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
351       numFormalParams = proto->getNumParams();
352     } else {
353       numFormalParams = 0;
354     }
355   } else {
356     return;
357   }
358 
359   // "nullPos" is the number of formal parameters at the end which
360   // effectively count as part of the variadic arguments.  This is
361   // useful if you would prefer to not have *any* formal parameters,
362   // but the language forces you to have at least one.
363   unsigned nullPos = attr->getNullPos();
364   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
365   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
366 
367   // The number of arguments which should follow the sentinel.
368   unsigned numArgsAfterSentinel = attr->getSentinel();
369 
370   // If there aren't enough arguments for all the formal parameters,
371   // the sentinel, and the args after the sentinel, complain.
372   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
373     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
374     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
375     return;
376   }
377 
378   // Otherwise, find the sentinel expression.
379   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
380   if (!sentinelExpr) return;
381   if (sentinelExpr->isValueDependent()) return;
382   if (Context.isSentinelNullExpr(sentinelExpr)) return;
383 
384   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
385   // or 'NULL' if those are actually defined in the context.  Only use
386   // 'nil' for ObjC methods, where it's much more likely that the
387   // variadic arguments form a list of object pointers.
388   SourceLocation MissingNilLoc
389     = getLocForEndOfToken(sentinelExpr->getLocEnd());
390   std::string NullValue;
391   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
392     NullValue = "nil";
393   else if (getLangOpts().CPlusPlus11)
394     NullValue = "nullptr";
395   else if (PP.isMacroDefined("NULL"))
396     NullValue = "NULL";
397   else
398     NullValue = "(void*) 0";
399 
400   if (MissingNilLoc.isInvalid())
401     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
402   else
403     Diag(MissingNilLoc, diag::warn_missing_sentinel)
404       << int(calleeType)
405       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
406   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
407 }
408 
409 SourceRange Sema::getExprRange(Expr *E) const {
410   return E ? E->getSourceRange() : SourceRange();
411 }
412 
413 //===----------------------------------------------------------------------===//
414 //  Standard Promotions and Conversions
415 //===----------------------------------------------------------------------===//
416 
417 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
418 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
419   // Handle any placeholder expressions which made it here.
420   if (E->getType()->isPlaceholderType()) {
421     ExprResult result = CheckPlaceholderExpr(E);
422     if (result.isInvalid()) return ExprError();
423     E = result.get();
424   }
425 
426   QualType Ty = E->getType();
427   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
428 
429   if (Ty->isFunctionType()) {
430     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
431       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
432         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
433           return ExprError();
434 
435     E = ImpCastExprToType(E, Context.getPointerType(Ty),
436                           CK_FunctionToPointerDecay).get();
437   } else if (Ty->isArrayType()) {
438     // In C90 mode, arrays only promote to pointers if the array expression is
439     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
440     // type 'array of type' is converted to an expression that has type 'pointer
441     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
442     // that has type 'array of type' ...".  The relevant change is "an lvalue"
443     // (C90) to "an expression" (C99).
444     //
445     // C++ 4.2p1:
446     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
447     // T" can be converted to an rvalue of type "pointer to T".
448     //
449     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
450       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
451                             CK_ArrayToPointerDecay).get();
452   }
453   return E;
454 }
455 
456 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
457   // Check to see if we are dereferencing a null pointer.  If so,
458   // and if not volatile-qualified, this is undefined behavior that the
459   // optimizer will delete, so warn about it.  People sometimes try to use this
460   // to get a deterministic trap and are surprised by clang's behavior.  This
461   // only handles the pattern "*null", which is a very syntactic check.
462   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
463     if (UO->getOpcode() == UO_Deref &&
464         UO->getSubExpr()->IgnoreParenCasts()->
465           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
466         !UO->getType().isVolatileQualified()) {
467     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
468                           S.PDiag(diag::warn_indirection_through_null)
469                             << UO->getSubExpr()->getSourceRange());
470     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
471                         S.PDiag(diag::note_indirection_through_null));
472   }
473 }
474 
475 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
476                                     SourceLocation AssignLoc,
477                                     const Expr* RHS) {
478   const ObjCIvarDecl *IV = OIRE->getDecl();
479   if (!IV)
480     return;
481 
482   DeclarationName MemberName = IV->getDeclName();
483   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
484   if (!Member || !Member->isStr("isa"))
485     return;
486 
487   const Expr *Base = OIRE->getBase();
488   QualType BaseType = Base->getType();
489   if (OIRE->isArrow())
490     BaseType = BaseType->getPointeeType();
491   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
492     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
493       ObjCInterfaceDecl *ClassDeclared = nullptr;
494       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
495       if (!ClassDeclared->getSuperClass()
496           && (*ClassDeclared->ivar_begin()) == IV) {
497         if (RHS) {
498           NamedDecl *ObjectSetClass =
499             S.LookupSingleName(S.TUScope,
500                                &S.Context.Idents.get("object_setClass"),
501                                SourceLocation(), S.LookupOrdinaryName);
502           if (ObjectSetClass) {
503             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
504             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
505             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
506             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
507                                                      AssignLoc), ",") <<
508             FixItHint::CreateInsertion(RHSLocEnd, ")");
509           }
510           else
511             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
512         } else {
513           NamedDecl *ObjectGetClass =
514             S.LookupSingleName(S.TUScope,
515                                &S.Context.Idents.get("object_getClass"),
516                                SourceLocation(), S.LookupOrdinaryName);
517           if (ObjectGetClass)
518             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
519             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
520             FixItHint::CreateReplacement(
521                                          SourceRange(OIRE->getOpLoc(),
522                                                      OIRE->getLocEnd()), ")");
523           else
524             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
525         }
526         S.Diag(IV->getLocation(), diag::note_ivar_decl);
527       }
528     }
529 }
530 
531 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
532   // Handle any placeholder expressions which made it here.
533   if (E->getType()->isPlaceholderType()) {
534     ExprResult result = CheckPlaceholderExpr(E);
535     if (result.isInvalid()) return ExprError();
536     E = result.get();
537   }
538 
539   // C++ [conv.lval]p1:
540   //   A glvalue of a non-function, non-array type T can be
541   //   converted to a prvalue.
542   if (!E->isGLValue()) return E;
543 
544   QualType T = E->getType();
545   assert(!T.isNull() && "r-value conversion on typeless expression?");
546 
547   // We don't want to throw lvalue-to-rvalue casts on top of
548   // expressions of certain types in C++.
549   if (getLangOpts().CPlusPlus &&
550       (E->getType() == Context.OverloadTy ||
551        T->isDependentType() ||
552        T->isRecordType()))
553     return E;
554 
555   // The C standard is actually really unclear on this point, and
556   // DR106 tells us what the result should be but not why.  It's
557   // generally best to say that void types just doesn't undergo
558   // lvalue-to-rvalue at all.  Note that expressions of unqualified
559   // 'void' type are never l-values, but qualified void can be.
560   if (T->isVoidType())
561     return E;
562 
563   // OpenCL usually rejects direct accesses to values of 'half' type.
564   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
565       T->isHalfType()) {
566     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
567       << 0 << T;
568     return ExprError();
569   }
570 
571   CheckForNullPointerDereference(*this, E);
572   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
573     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
574                                      &Context.Idents.get("object_getClass"),
575                                      SourceLocation(), LookupOrdinaryName);
576     if (ObjectGetClass)
577       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
578         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
579         FixItHint::CreateReplacement(
580                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
581     else
582       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
583   }
584   else if (const ObjCIvarRefExpr *OIRE =
585             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
586     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
587 
588   // C++ [conv.lval]p1:
589   //   [...] If T is a non-class type, the type of the prvalue is the
590   //   cv-unqualified version of T. Otherwise, the type of the
591   //   rvalue is T.
592   //
593   // C99 6.3.2.1p2:
594   //   If the lvalue has qualified type, the value has the unqualified
595   //   version of the type of the lvalue; otherwise, the value has the
596   //   type of the lvalue.
597   if (T.hasQualifiers())
598     T = T.getUnqualifiedType();
599 
600   // Under the MS ABI, lock down the inheritance model now.
601   if (T->isMemberPointerType() &&
602       Context.getTargetInfo().getCXXABI().isMicrosoft())
603     (void)isCompleteType(E->getExprLoc(), T);
604 
605   UpdateMarkingForLValueToRValue(E);
606 
607   // Loading a __weak object implicitly retains the value, so we need a cleanup to
608   // balance that.
609   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
610     Cleanup.setExprNeedsCleanups(true);
611 
612   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
613                                             nullptr, VK_RValue);
614 
615   // C11 6.3.2.1p2:
616   //   ... if the lvalue has atomic type, the value has the non-atomic version
617   //   of the type of the lvalue ...
618   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
619     T = Atomic->getValueType().getUnqualifiedType();
620     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
621                                    nullptr, VK_RValue);
622   }
623 
624   return Res;
625 }
626 
627 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
628   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
629   if (Res.isInvalid())
630     return ExprError();
631   Res = DefaultLvalueConversion(Res.get());
632   if (Res.isInvalid())
633     return ExprError();
634   return Res;
635 }
636 
637 /// CallExprUnaryConversions - a special case of an unary conversion
638 /// performed on a function designator of a call expression.
639 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
640   QualType Ty = E->getType();
641   ExprResult Res = E;
642   // Only do implicit cast for a function type, but not for a pointer
643   // to function type.
644   if (Ty->isFunctionType()) {
645     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
646                             CK_FunctionToPointerDecay).get();
647     if (Res.isInvalid())
648       return ExprError();
649   }
650   Res = DefaultLvalueConversion(Res.get());
651   if (Res.isInvalid())
652     return ExprError();
653   return Res.get();
654 }
655 
656 /// UsualUnaryConversions - Performs various conversions that are common to most
657 /// operators (C99 6.3). The conversions of array and function types are
658 /// sometimes suppressed. For example, the array->pointer conversion doesn't
659 /// apply if the array is an argument to the sizeof or address (&) operators.
660 /// In these instances, this routine should *not* be called.
661 ExprResult Sema::UsualUnaryConversions(Expr *E) {
662   // First, convert to an r-value.
663   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
664   if (Res.isInvalid())
665     return ExprError();
666   E = Res.get();
667 
668   QualType Ty = E->getType();
669   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
670 
671   // Half FP have to be promoted to float unless it is natively supported
672   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
673     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
674 
675   // Try to perform integral promotions if the object has a theoretically
676   // promotable type.
677   if (Ty->isIntegralOrUnscopedEnumerationType()) {
678     // C99 6.3.1.1p2:
679     //
680     //   The following may be used in an expression wherever an int or
681     //   unsigned int may be used:
682     //     - an object or expression with an integer type whose integer
683     //       conversion rank is less than or equal to the rank of int
684     //       and unsigned int.
685     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
686     //
687     //   If an int can represent all values of the original type, the
688     //   value is converted to an int; otherwise, it is converted to an
689     //   unsigned int. These are called the integer promotions. All
690     //   other types are unchanged by the integer promotions.
691 
692     QualType PTy = Context.isPromotableBitField(E);
693     if (!PTy.isNull()) {
694       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
695       return E;
696     }
697     if (Ty->isPromotableIntegerType()) {
698       QualType PT = Context.getPromotedIntegerType(Ty);
699       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
700       return E;
701     }
702   }
703   return E;
704 }
705 
706 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
707 /// do not have a prototype. Arguments that have type float or __fp16
708 /// are promoted to double. All other argument types are converted by
709 /// UsualUnaryConversions().
710 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
711   QualType Ty = E->getType();
712   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
713 
714   ExprResult Res = UsualUnaryConversions(E);
715   if (Res.isInvalid())
716     return ExprError();
717   E = Res.get();
718 
719   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
720   // promote to double.
721   // Note that default argument promotion applies only to float (and
722   // half/fp16); it does not apply to _Float16.
723   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
724   if (BTy && (BTy->getKind() == BuiltinType::Half ||
725               BTy->getKind() == BuiltinType::Float)) {
726     if (getLangOpts().OpenCL &&
727         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
728         if (BTy->getKind() == BuiltinType::Half) {
729             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
730         }
731     } else {
732       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
733     }
734   }
735 
736   // C++ performs lvalue-to-rvalue conversion as a default argument
737   // promotion, even on class types, but note:
738   //   C++11 [conv.lval]p2:
739   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
740   //     operand or a subexpression thereof the value contained in the
741   //     referenced object is not accessed. Otherwise, if the glvalue
742   //     has a class type, the conversion copy-initializes a temporary
743   //     of type T from the glvalue and the result of the conversion
744   //     is a prvalue for the temporary.
745   // FIXME: add some way to gate this entire thing for correctness in
746   // potentially potentially evaluated contexts.
747   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
748     ExprResult Temp = PerformCopyInitialization(
749                        InitializedEntity::InitializeTemporary(E->getType()),
750                                                 E->getExprLoc(), E);
751     if (Temp.isInvalid())
752       return ExprError();
753     E = Temp.get();
754   }
755 
756   return E;
757 }
758 
759 /// Determine the degree of POD-ness for an expression.
760 /// Incomplete types are considered POD, since this check can be performed
761 /// when we're in an unevaluated context.
762 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
763   if (Ty->isIncompleteType()) {
764     // C++11 [expr.call]p7:
765     //   After these conversions, if the argument does not have arithmetic,
766     //   enumeration, pointer, pointer to member, or class type, the program
767     //   is ill-formed.
768     //
769     // Since we've already performed array-to-pointer and function-to-pointer
770     // decay, the only such type in C++ is cv void. This also handles
771     // initializer lists as variadic arguments.
772     if (Ty->isVoidType())
773       return VAK_Invalid;
774 
775     if (Ty->isObjCObjectType())
776       return VAK_Invalid;
777     return VAK_Valid;
778   }
779 
780   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
781     return VAK_Invalid;
782 
783   if (Ty.isCXX98PODType(Context))
784     return VAK_Valid;
785 
786   // C++11 [expr.call]p7:
787   //   Passing a potentially-evaluated argument of class type (Clause 9)
788   //   having a non-trivial copy constructor, a non-trivial move constructor,
789   //   or a non-trivial destructor, with no corresponding parameter,
790   //   is conditionally-supported with implementation-defined semantics.
791   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
792     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
793       if (!Record->hasNonTrivialCopyConstructor() &&
794           !Record->hasNonTrivialMoveConstructor() &&
795           !Record->hasNonTrivialDestructor())
796         return VAK_ValidInCXX11;
797 
798   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
799     return VAK_Valid;
800 
801   if (Ty->isObjCObjectType())
802     return VAK_Invalid;
803 
804   if (getLangOpts().MSVCCompat)
805     return VAK_MSVCUndefined;
806 
807   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
808   // permitted to reject them. We should consider doing so.
809   return VAK_Undefined;
810 }
811 
812 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
813   // Don't allow one to pass an Objective-C interface to a vararg.
814   const QualType &Ty = E->getType();
815   VarArgKind VAK = isValidVarArgType(Ty);
816 
817   // Complain about passing non-POD types through varargs.
818   switch (VAK) {
819   case VAK_ValidInCXX11:
820     DiagRuntimeBehavior(
821         E->getLocStart(), nullptr,
822         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
823           << Ty << CT);
824     LLVM_FALLTHROUGH;
825   case VAK_Valid:
826     if (Ty->isRecordType()) {
827       // This is unlikely to be what the user intended. If the class has a
828       // 'c_str' member function, the user probably meant to call that.
829       DiagRuntimeBehavior(E->getLocStart(), nullptr,
830                           PDiag(diag::warn_pass_class_arg_to_vararg)
831                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
832     }
833     break;
834 
835   case VAK_Undefined:
836   case VAK_MSVCUndefined:
837     DiagRuntimeBehavior(
838         E->getLocStart(), nullptr,
839         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
840           << getLangOpts().CPlusPlus11 << Ty << CT);
841     break;
842 
843   case VAK_Invalid:
844     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
845       Diag(E->getLocStart(),
846            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
847     else if (Ty->isObjCObjectType())
848       DiagRuntimeBehavior(
849           E->getLocStart(), nullptr,
850           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
851             << Ty << CT);
852     else
853       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
854         << isa<InitListExpr>(E) << Ty << CT;
855     break;
856   }
857 }
858 
859 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
860 /// will create a trap if the resulting type is not a POD type.
861 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
862                                                   FunctionDecl *FDecl) {
863   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
864     // Strip the unbridged-cast placeholder expression off, if applicable.
865     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
866         (CT == VariadicMethod ||
867          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
868       E = stripARCUnbridgedCast(E);
869 
870     // Otherwise, do normal placeholder checking.
871     } else {
872       ExprResult ExprRes = CheckPlaceholderExpr(E);
873       if (ExprRes.isInvalid())
874         return ExprError();
875       E = ExprRes.get();
876     }
877   }
878 
879   ExprResult ExprRes = DefaultArgumentPromotion(E);
880   if (ExprRes.isInvalid())
881     return ExprError();
882   E = ExprRes.get();
883 
884   // Diagnostics regarding non-POD argument types are
885   // emitted along with format string checking in Sema::CheckFunctionCall().
886   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
887     // Turn this into a trap.
888     CXXScopeSpec SS;
889     SourceLocation TemplateKWLoc;
890     UnqualifiedId Name;
891     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
892                        E->getLocStart());
893     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
894                                           Name, true, false);
895     if (TrapFn.isInvalid())
896       return ExprError();
897 
898     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
899                                     E->getLocStart(), None,
900                                     E->getLocEnd());
901     if (Call.isInvalid())
902       return ExprError();
903 
904     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
905                                   Call.get(), E);
906     if (Comma.isInvalid())
907       return ExprError();
908     return Comma.get();
909   }
910 
911   if (!getLangOpts().CPlusPlus &&
912       RequireCompleteType(E->getExprLoc(), E->getType(),
913                           diag::err_call_incomplete_argument))
914     return ExprError();
915 
916   return E;
917 }
918 
919 /// \brief Converts an integer to complex float type.  Helper function of
920 /// UsualArithmeticConversions()
921 ///
922 /// \return false if the integer expression is an integer type and is
923 /// successfully converted to the complex type.
924 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
925                                                   ExprResult &ComplexExpr,
926                                                   QualType IntTy,
927                                                   QualType ComplexTy,
928                                                   bool SkipCast) {
929   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
930   if (SkipCast) return false;
931   if (IntTy->isIntegerType()) {
932     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
933     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
934     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
935                                   CK_FloatingRealToComplex);
936   } else {
937     assert(IntTy->isComplexIntegerType());
938     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
939                                   CK_IntegralComplexToFloatingComplex);
940   }
941   return false;
942 }
943 
944 /// \brief Handle arithmetic conversion with complex types.  Helper function of
945 /// UsualArithmeticConversions()
946 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
947                                              ExprResult &RHS, QualType LHSType,
948                                              QualType RHSType,
949                                              bool IsCompAssign) {
950   // if we have an integer operand, the result is the complex type.
951   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
952                                              /*skipCast*/false))
953     return LHSType;
954   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
955                                              /*skipCast*/IsCompAssign))
956     return RHSType;
957 
958   // This handles complex/complex, complex/float, or float/complex.
959   // When both operands are complex, the shorter operand is converted to the
960   // type of the longer, and that is the type of the result. This corresponds
961   // to what is done when combining two real floating-point operands.
962   // The fun begins when size promotion occur across type domains.
963   // From H&S 6.3.4: When one operand is complex and the other is a real
964   // floating-point type, the less precise type is converted, within it's
965   // real or complex domain, to the precision of the other type. For example,
966   // when combining a "long double" with a "double _Complex", the
967   // "double _Complex" is promoted to "long double _Complex".
968 
969   // Compute the rank of the two types, regardless of whether they are complex.
970   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
971 
972   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
973   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
974   QualType LHSElementType =
975       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
976   QualType RHSElementType =
977       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
978 
979   QualType ResultType = S.Context.getComplexType(LHSElementType);
980   if (Order < 0) {
981     // Promote the precision of the LHS if not an assignment.
982     ResultType = S.Context.getComplexType(RHSElementType);
983     if (!IsCompAssign) {
984       if (LHSComplexType)
985         LHS =
986             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
987       else
988         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
989     }
990   } else if (Order > 0) {
991     // Promote the precision of the RHS.
992     if (RHSComplexType)
993       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
994     else
995       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
996   }
997   return ResultType;
998 }
999 
1000 /// \brief Handle arithmetic conversion from integer to float.  Helper function
1001 /// of UsualArithmeticConversions()
1002 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1003                                            ExprResult &IntExpr,
1004                                            QualType FloatTy, QualType IntTy,
1005                                            bool ConvertFloat, bool ConvertInt) {
1006   if (IntTy->isIntegerType()) {
1007     if (ConvertInt)
1008       // Convert intExpr to the lhs floating point type.
1009       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1010                                     CK_IntegralToFloating);
1011     return FloatTy;
1012   }
1013 
1014   // Convert both sides to the appropriate complex float.
1015   assert(IntTy->isComplexIntegerType());
1016   QualType result = S.Context.getComplexType(FloatTy);
1017 
1018   // _Complex int -> _Complex float
1019   if (ConvertInt)
1020     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1021                                   CK_IntegralComplexToFloatingComplex);
1022 
1023   // float -> _Complex float
1024   if (ConvertFloat)
1025     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1026                                     CK_FloatingRealToComplex);
1027 
1028   return result;
1029 }
1030 
1031 /// \brief Handle arithmethic conversion with floating point types.  Helper
1032 /// function of UsualArithmeticConversions()
1033 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1034                                       ExprResult &RHS, QualType LHSType,
1035                                       QualType RHSType, bool IsCompAssign) {
1036   bool LHSFloat = LHSType->isRealFloatingType();
1037   bool RHSFloat = RHSType->isRealFloatingType();
1038 
1039   // If we have two real floating types, convert the smaller operand
1040   // to the bigger result.
1041   if (LHSFloat && RHSFloat) {
1042     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1043     if (order > 0) {
1044       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1045       return LHSType;
1046     }
1047 
1048     assert(order < 0 && "illegal float comparison");
1049     if (!IsCompAssign)
1050       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1051     return RHSType;
1052   }
1053 
1054   if (LHSFloat) {
1055     // Half FP has to be promoted to float unless it is natively supported
1056     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1057       LHSType = S.Context.FloatTy;
1058 
1059     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1060                                       /*convertFloat=*/!IsCompAssign,
1061                                       /*convertInt=*/ true);
1062   }
1063   assert(RHSFloat);
1064   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1065                                     /*convertInt=*/ true,
1066                                     /*convertFloat=*/!IsCompAssign);
1067 }
1068 
1069 /// \brief Diagnose attempts to convert between __float128 and long double if
1070 /// there is no support for such conversion. Helper function of
1071 /// UsualArithmeticConversions().
1072 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1073                                       QualType RHSType) {
1074   /*  No issue converting if at least one of the types is not a floating point
1075       type or the two types have the same rank.
1076   */
1077   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1078       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1079     return false;
1080 
1081   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1082          "The remaining types must be floating point types.");
1083 
1084   auto *LHSComplex = LHSType->getAs<ComplexType>();
1085   auto *RHSComplex = RHSType->getAs<ComplexType>();
1086 
1087   QualType LHSElemType = LHSComplex ?
1088     LHSComplex->getElementType() : LHSType;
1089   QualType RHSElemType = RHSComplex ?
1090     RHSComplex->getElementType() : RHSType;
1091 
1092   // No issue if the two types have the same representation
1093   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1094       &S.Context.getFloatTypeSemantics(RHSElemType))
1095     return false;
1096 
1097   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1098                                 RHSElemType == S.Context.LongDoubleTy);
1099   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1100                             RHSElemType == S.Context.Float128Ty);
1101 
1102   // We've handled the situation where __float128 and long double have the same
1103   // representation. We allow all conversions for all possible long double types
1104   // except PPC's double double.
1105   return Float128AndLongDouble &&
1106     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1107      &llvm::APFloat::PPCDoubleDouble());
1108 }
1109 
1110 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1111 
1112 namespace {
1113 /// These helper callbacks are placed in an anonymous namespace to
1114 /// permit their use as function template parameters.
1115 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1116   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1117 }
1118 
1119 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1120   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1121                              CK_IntegralComplexCast);
1122 }
1123 }
1124 
1125 /// \brief Handle integer arithmetic conversions.  Helper function of
1126 /// UsualArithmeticConversions()
1127 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1128 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1129                                         ExprResult &RHS, QualType LHSType,
1130                                         QualType RHSType, bool IsCompAssign) {
1131   // The rules for this case are in C99 6.3.1.8
1132   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1133   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1134   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1135   if (LHSSigned == RHSSigned) {
1136     // Same signedness; use the higher-ranked type
1137     if (order >= 0) {
1138       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1139       return LHSType;
1140     } else if (!IsCompAssign)
1141       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1142     return RHSType;
1143   } else if (order != (LHSSigned ? 1 : -1)) {
1144     // The unsigned type has greater than or equal rank to the
1145     // signed type, so use the unsigned type
1146     if (RHSSigned) {
1147       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1148       return LHSType;
1149     } else if (!IsCompAssign)
1150       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1151     return RHSType;
1152   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1153     // The two types are different widths; if we are here, that
1154     // means the signed type is larger than the unsigned type, so
1155     // use the signed type.
1156     if (LHSSigned) {
1157       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1158       return LHSType;
1159     } else if (!IsCompAssign)
1160       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1161     return RHSType;
1162   } else {
1163     // The signed type is higher-ranked than the unsigned type,
1164     // but isn't actually any bigger (like unsigned int and long
1165     // on most 32-bit systems).  Use the unsigned type corresponding
1166     // to the signed type.
1167     QualType result =
1168       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1169     RHS = (*doRHSCast)(S, RHS.get(), result);
1170     if (!IsCompAssign)
1171       LHS = (*doLHSCast)(S, LHS.get(), result);
1172     return result;
1173   }
1174 }
1175 
1176 /// \brief Handle conversions with GCC complex int extension.  Helper function
1177 /// of UsualArithmeticConversions()
1178 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1179                                            ExprResult &RHS, QualType LHSType,
1180                                            QualType RHSType,
1181                                            bool IsCompAssign) {
1182   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1183   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1184 
1185   if (LHSComplexInt && RHSComplexInt) {
1186     QualType LHSEltType = LHSComplexInt->getElementType();
1187     QualType RHSEltType = RHSComplexInt->getElementType();
1188     QualType ScalarType =
1189       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1190         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1191 
1192     return S.Context.getComplexType(ScalarType);
1193   }
1194 
1195   if (LHSComplexInt) {
1196     QualType LHSEltType = LHSComplexInt->getElementType();
1197     QualType ScalarType =
1198       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1199         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1200     QualType ComplexType = S.Context.getComplexType(ScalarType);
1201     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1202                               CK_IntegralRealToComplex);
1203 
1204     return ComplexType;
1205   }
1206 
1207   assert(RHSComplexInt);
1208 
1209   QualType RHSEltType = RHSComplexInt->getElementType();
1210   QualType ScalarType =
1211     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1212       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1213   QualType ComplexType = S.Context.getComplexType(ScalarType);
1214 
1215   if (!IsCompAssign)
1216     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1217                               CK_IntegralRealToComplex);
1218   return ComplexType;
1219 }
1220 
1221 /// UsualArithmeticConversions - Performs various conversions that are common to
1222 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1223 /// routine returns the first non-arithmetic type found. The client is
1224 /// responsible for emitting appropriate error diagnostics.
1225 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1226                                           bool IsCompAssign) {
1227   if (!IsCompAssign) {
1228     LHS = UsualUnaryConversions(LHS.get());
1229     if (LHS.isInvalid())
1230       return QualType();
1231   }
1232 
1233   RHS = UsualUnaryConversions(RHS.get());
1234   if (RHS.isInvalid())
1235     return QualType();
1236 
1237   // For conversion purposes, we ignore any qualifiers.
1238   // For example, "const float" and "float" are equivalent.
1239   QualType LHSType =
1240     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1241   QualType RHSType =
1242     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1243 
1244   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1245   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1246     LHSType = AtomicLHS->getValueType();
1247 
1248   // If both types are identical, no conversion is needed.
1249   if (LHSType == RHSType)
1250     return LHSType;
1251 
1252   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1253   // The caller can deal with this (e.g. pointer + int).
1254   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1255     return QualType();
1256 
1257   // Apply unary and bitfield promotions to the LHS's type.
1258   QualType LHSUnpromotedType = LHSType;
1259   if (LHSType->isPromotableIntegerType())
1260     LHSType = Context.getPromotedIntegerType(LHSType);
1261   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1262   if (!LHSBitfieldPromoteTy.isNull())
1263     LHSType = LHSBitfieldPromoteTy;
1264   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1265     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1266 
1267   // If both types are identical, no conversion is needed.
1268   if (LHSType == RHSType)
1269     return LHSType;
1270 
1271   // At this point, we have two different arithmetic types.
1272 
1273   // Diagnose attempts to convert between __float128 and long double where
1274   // such conversions currently can't be handled.
1275   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1276     return QualType();
1277 
1278   // Handle complex types first (C99 6.3.1.8p1).
1279   if (LHSType->isComplexType() || RHSType->isComplexType())
1280     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1281                                         IsCompAssign);
1282 
1283   // Now handle "real" floating types (i.e. float, double, long double).
1284   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1285     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1286                                  IsCompAssign);
1287 
1288   // Handle GCC complex int extension.
1289   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1290     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1291                                       IsCompAssign);
1292 
1293   // Finally, we have two differing integer types.
1294   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1295            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1296 }
1297 
1298 
1299 //===----------------------------------------------------------------------===//
1300 //  Semantic Analysis for various Expression Types
1301 //===----------------------------------------------------------------------===//
1302 
1303 
1304 ExprResult
1305 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1306                                 SourceLocation DefaultLoc,
1307                                 SourceLocation RParenLoc,
1308                                 Expr *ControllingExpr,
1309                                 ArrayRef<ParsedType> ArgTypes,
1310                                 ArrayRef<Expr *> ArgExprs) {
1311   unsigned NumAssocs = ArgTypes.size();
1312   assert(NumAssocs == ArgExprs.size());
1313 
1314   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1315   for (unsigned i = 0; i < NumAssocs; ++i) {
1316     if (ArgTypes[i])
1317       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1318     else
1319       Types[i] = nullptr;
1320   }
1321 
1322   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1323                                              ControllingExpr,
1324                                              llvm::makeArrayRef(Types, NumAssocs),
1325                                              ArgExprs);
1326   delete [] Types;
1327   return ER;
1328 }
1329 
1330 ExprResult
1331 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1332                                  SourceLocation DefaultLoc,
1333                                  SourceLocation RParenLoc,
1334                                  Expr *ControllingExpr,
1335                                  ArrayRef<TypeSourceInfo *> Types,
1336                                  ArrayRef<Expr *> Exprs) {
1337   unsigned NumAssocs = Types.size();
1338   assert(NumAssocs == Exprs.size());
1339 
1340   // Decay and strip qualifiers for the controlling expression type, and handle
1341   // placeholder type replacement. See committee discussion from WG14 DR423.
1342   {
1343     EnterExpressionEvaluationContext Unevaluated(
1344         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1345     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1346     if (R.isInvalid())
1347       return ExprError();
1348     ControllingExpr = R.get();
1349   }
1350 
1351   // The controlling expression is an unevaluated operand, so side effects are
1352   // likely unintended.
1353   if (!inTemplateInstantiation() &&
1354       ControllingExpr->HasSideEffects(Context, false))
1355     Diag(ControllingExpr->getExprLoc(),
1356          diag::warn_side_effects_unevaluated_context);
1357 
1358   bool TypeErrorFound = false,
1359        IsResultDependent = ControllingExpr->isTypeDependent(),
1360        ContainsUnexpandedParameterPack
1361          = ControllingExpr->containsUnexpandedParameterPack();
1362 
1363   for (unsigned i = 0; i < NumAssocs; ++i) {
1364     if (Exprs[i]->containsUnexpandedParameterPack())
1365       ContainsUnexpandedParameterPack = true;
1366 
1367     if (Types[i]) {
1368       if (Types[i]->getType()->containsUnexpandedParameterPack())
1369         ContainsUnexpandedParameterPack = true;
1370 
1371       if (Types[i]->getType()->isDependentType()) {
1372         IsResultDependent = true;
1373       } else {
1374         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1375         // complete object type other than a variably modified type."
1376         unsigned D = 0;
1377         if (Types[i]->getType()->isIncompleteType())
1378           D = diag::err_assoc_type_incomplete;
1379         else if (!Types[i]->getType()->isObjectType())
1380           D = diag::err_assoc_type_nonobject;
1381         else if (Types[i]->getType()->isVariablyModifiedType())
1382           D = diag::err_assoc_type_variably_modified;
1383 
1384         if (D != 0) {
1385           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1386             << Types[i]->getTypeLoc().getSourceRange()
1387             << Types[i]->getType();
1388           TypeErrorFound = true;
1389         }
1390 
1391         // C11 6.5.1.1p2 "No two generic associations in the same generic
1392         // selection shall specify compatible types."
1393         for (unsigned j = i+1; j < NumAssocs; ++j)
1394           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1395               Context.typesAreCompatible(Types[i]->getType(),
1396                                          Types[j]->getType())) {
1397             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1398                  diag::err_assoc_compatible_types)
1399               << Types[j]->getTypeLoc().getSourceRange()
1400               << Types[j]->getType()
1401               << Types[i]->getType();
1402             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1403                  diag::note_compat_assoc)
1404               << Types[i]->getTypeLoc().getSourceRange()
1405               << Types[i]->getType();
1406             TypeErrorFound = true;
1407           }
1408       }
1409     }
1410   }
1411   if (TypeErrorFound)
1412     return ExprError();
1413 
1414   // If we determined that the generic selection is result-dependent, don't
1415   // try to compute the result expression.
1416   if (IsResultDependent)
1417     return new (Context) GenericSelectionExpr(
1418         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1419         ContainsUnexpandedParameterPack);
1420 
1421   SmallVector<unsigned, 1> CompatIndices;
1422   unsigned DefaultIndex = -1U;
1423   for (unsigned i = 0; i < NumAssocs; ++i) {
1424     if (!Types[i])
1425       DefaultIndex = i;
1426     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1427                                         Types[i]->getType()))
1428       CompatIndices.push_back(i);
1429   }
1430 
1431   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1432   // type compatible with at most one of the types named in its generic
1433   // association list."
1434   if (CompatIndices.size() > 1) {
1435     // We strip parens here because the controlling expression is typically
1436     // parenthesized in macro definitions.
1437     ControllingExpr = ControllingExpr->IgnoreParens();
1438     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1439       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1440       << (unsigned) CompatIndices.size();
1441     for (unsigned I : CompatIndices) {
1442       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1443            diag::note_compat_assoc)
1444         << Types[I]->getTypeLoc().getSourceRange()
1445         << Types[I]->getType();
1446     }
1447     return ExprError();
1448   }
1449 
1450   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1451   // its controlling expression shall have type compatible with exactly one of
1452   // the types named in its generic association list."
1453   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1454     // We strip parens here because the controlling expression is typically
1455     // parenthesized in macro definitions.
1456     ControllingExpr = ControllingExpr->IgnoreParens();
1457     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1458       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1459     return ExprError();
1460   }
1461 
1462   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1463   // type name that is compatible with the type of the controlling expression,
1464   // then the result expression of the generic selection is the expression
1465   // in that generic association. Otherwise, the result expression of the
1466   // generic selection is the expression in the default generic association."
1467   unsigned ResultIndex =
1468     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1469 
1470   return new (Context) GenericSelectionExpr(
1471       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1472       ContainsUnexpandedParameterPack, ResultIndex);
1473 }
1474 
1475 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1476 /// location of the token and the offset of the ud-suffix within it.
1477 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1478                                      unsigned Offset) {
1479   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1480                                         S.getLangOpts());
1481 }
1482 
1483 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1484 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1485 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1486                                                  IdentifierInfo *UDSuffix,
1487                                                  SourceLocation UDSuffixLoc,
1488                                                  ArrayRef<Expr*> Args,
1489                                                  SourceLocation LitEndLoc) {
1490   assert(Args.size() <= 2 && "too many arguments for literal operator");
1491 
1492   QualType ArgTy[2];
1493   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1494     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1495     if (ArgTy[ArgIdx]->isArrayType())
1496       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1497   }
1498 
1499   DeclarationName OpName =
1500     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1501   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1502   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1503 
1504   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1505   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1506                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1507                               /*AllowStringTemplate*/ false,
1508                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1509     return ExprError();
1510 
1511   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1512 }
1513 
1514 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1515 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1516 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1517 /// multiple tokens.  However, the common case is that StringToks points to one
1518 /// string.
1519 ///
1520 ExprResult
1521 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1522   assert(!StringToks.empty() && "Must have at least one string!");
1523 
1524   StringLiteralParser Literal(StringToks, PP);
1525   if (Literal.hadError)
1526     return ExprError();
1527 
1528   SmallVector<SourceLocation, 4> StringTokLocs;
1529   for (const Token &Tok : StringToks)
1530     StringTokLocs.push_back(Tok.getLocation());
1531 
1532   QualType CharTy = Context.CharTy;
1533   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1534   if (Literal.isWide()) {
1535     CharTy = Context.getWideCharType();
1536     Kind = StringLiteral::Wide;
1537   } else if (Literal.isUTF8()) {
1538     Kind = StringLiteral::UTF8;
1539   } else if (Literal.isUTF16()) {
1540     CharTy = Context.Char16Ty;
1541     Kind = StringLiteral::UTF16;
1542   } else if (Literal.isUTF32()) {
1543     CharTy = Context.Char32Ty;
1544     Kind = StringLiteral::UTF32;
1545   } else if (Literal.isPascal()) {
1546     CharTy = Context.UnsignedCharTy;
1547   }
1548 
1549   QualType CharTyConst = CharTy;
1550   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1551   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1552     CharTyConst.addConst();
1553 
1554   // Get an array type for the string, according to C99 6.4.5.  This includes
1555   // the nul terminator character as well as the string length for pascal
1556   // strings.
1557   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1558                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1559                                  ArrayType::Normal, 0);
1560 
1561   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1562   if (getLangOpts().OpenCL) {
1563     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1564   }
1565 
1566   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1567   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1568                                              Kind, Literal.Pascal, StrTy,
1569                                              &StringTokLocs[0],
1570                                              StringTokLocs.size());
1571   if (Literal.getUDSuffix().empty())
1572     return Lit;
1573 
1574   // We're building a user-defined literal.
1575   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1576   SourceLocation UDSuffixLoc =
1577     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1578                    Literal.getUDSuffixOffset());
1579 
1580   // Make sure we're allowed user-defined literals here.
1581   if (!UDLScope)
1582     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1583 
1584   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1585   //   operator "" X (str, len)
1586   QualType SizeType = Context.getSizeType();
1587 
1588   DeclarationName OpName =
1589     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   QualType ArgTy[] = {
1594     Context.getArrayDecayedType(StrTy), SizeType
1595   };
1596 
1597   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1598   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1599                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1600                                 /*AllowStringTemplate*/ true,
1601                                 /*DiagnoseMissing*/ true)) {
1602 
1603   case LOLR_Cooked: {
1604     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1605     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1606                                                     StringTokLocs[0]);
1607     Expr *Args[] = { Lit, LenArg };
1608 
1609     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1610   }
1611 
1612   case LOLR_StringTemplate: {
1613     TemplateArgumentListInfo ExplicitArgs;
1614 
1615     unsigned CharBits = Context.getIntWidth(CharTy);
1616     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1617     llvm::APSInt Value(CharBits, CharIsUnsigned);
1618 
1619     TemplateArgument TypeArg(CharTy);
1620     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1621     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1622 
1623     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1624       Value = Lit->getCodeUnit(I);
1625       TemplateArgument Arg(Context, Value, CharTy);
1626       TemplateArgumentLocInfo ArgInfo;
1627       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1628     }
1629     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1630                                     &ExplicitArgs);
1631   }
1632   case LOLR_Raw:
1633   case LOLR_Template:
1634   case LOLR_ErrorNoDiagnostic:
1635     llvm_unreachable("unexpected literal operator lookup result");
1636   case LOLR_Error:
1637     return ExprError();
1638   }
1639   llvm_unreachable("unexpected literal operator lookup result");
1640 }
1641 
1642 ExprResult
1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1644                        SourceLocation Loc,
1645                        const CXXScopeSpec *SS) {
1646   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1647   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1648 }
1649 
1650 /// BuildDeclRefExpr - Build an expression that references a
1651 /// declaration that does not require a closure capture.
1652 ExprResult
1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1654                        const DeclarationNameInfo &NameInfo,
1655                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1656                        const TemplateArgumentListInfo *TemplateArgs) {
1657   bool RefersToCapturedVariable =
1658       isa<VarDecl>(D) &&
1659       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1660 
1661   DeclRefExpr *E;
1662   if (isa<VarTemplateSpecializationDecl>(D)) {
1663     VarTemplateSpecializationDecl *VarSpec =
1664         cast<VarTemplateSpecializationDecl>(D);
1665 
1666     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1667                                         : NestedNameSpecifierLoc(),
1668                             VarSpec->getTemplateKeywordLoc(), D,
1669                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1670                             FoundD, TemplateArgs);
1671   } else {
1672     assert(!TemplateArgs && "No template arguments for non-variable"
1673                             " template specialization references");
1674     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1675                                         : NestedNameSpecifierLoc(),
1676                             SourceLocation(), D, RefersToCapturedVariable,
1677                             NameInfo, Ty, VK, FoundD);
1678   }
1679 
1680   MarkDeclRefReferenced(E);
1681 
1682   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1683       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1684       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1685     getCurFunction()->recordUseOfWeak(E);
1686 
1687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1689     FD = IFD->getAnonField();
1690   if (FD) {
1691     UnusedPrivateFields.remove(FD);
1692     // Just in case we're building an illegal pointer-to-member.
1693     if (FD->isBitField())
1694       E->setObjectKind(OK_BitField);
1695   }
1696 
1697   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1698   // designates a bit-field.
1699   if (auto *BD = dyn_cast<BindingDecl>(D))
1700     if (auto *BE = BD->getBinding())
1701       E->setObjectKind(BE->getObjectKind());
1702 
1703   return E;
1704 }
1705 
1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1707 /// possibly a list of template arguments.
1708 ///
1709 /// If this produces template arguments, it is permitted to call
1710 /// DecomposeTemplateName.
1711 ///
1712 /// This actually loses a lot of source location information for
1713 /// non-standard name kinds; we should consider preserving that in
1714 /// some way.
1715 void
1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1717                              TemplateArgumentListInfo &Buffer,
1718                              DeclarationNameInfo &NameInfo,
1719                              const TemplateArgumentListInfo *&TemplateArgs) {
1720   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1721     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1722     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1723 
1724     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1725                                        Id.TemplateId->NumArgs);
1726     translateTemplateArguments(TemplateArgsPtr, Buffer);
1727 
1728     TemplateName TName = Id.TemplateId->Template.get();
1729     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1730     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1731     TemplateArgs = &Buffer;
1732   } else {
1733     NameInfo = GetNameFromUnqualifiedId(Id);
1734     TemplateArgs = nullptr;
1735   }
1736 }
1737 
1738 static void emitEmptyLookupTypoDiagnostic(
1739     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1740     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1741     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1742   DeclContext *Ctx =
1743       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1744   if (!TC) {
1745     // Emit a special diagnostic for failed member lookups.
1746     // FIXME: computing the declaration context might fail here (?)
1747     if (Ctx)
1748       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1749                                                  << SS.getRange();
1750     else
1751       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1752     return;
1753   }
1754 
1755   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1756   bool DroppedSpecifier =
1757       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1758   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1759                         ? diag::note_implicit_param_decl
1760                         : diag::note_previous_decl;
1761   if (!Ctx)
1762     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1763                          SemaRef.PDiag(NoteID));
1764   else
1765     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1766                                  << Typo << Ctx << DroppedSpecifier
1767                                  << SS.getRange(),
1768                          SemaRef.PDiag(NoteID));
1769 }
1770 
1771 /// Diagnose an empty lookup.
1772 ///
1773 /// \return false if new lookup candidates were found
1774 bool
1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1776                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1777                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1778                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1779   DeclarationName Name = R.getLookupName();
1780 
1781   unsigned diagnostic = diag::err_undeclared_var_use;
1782   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1783   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1784       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1785       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1786     diagnostic = diag::err_undeclared_use;
1787     diagnostic_suggest = diag::err_undeclared_use_suggest;
1788   }
1789 
1790   // If the original lookup was an unqualified lookup, fake an
1791   // unqualified lookup.  This is useful when (for example) the
1792   // original lookup would not have found something because it was a
1793   // dependent name.
1794   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1795   while (DC) {
1796     if (isa<CXXRecordDecl>(DC)) {
1797       LookupQualifiedName(R, DC);
1798 
1799       if (!R.empty()) {
1800         // Don't give errors about ambiguities in this lookup.
1801         R.suppressDiagnostics();
1802 
1803         // During a default argument instantiation the CurContext points
1804         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1805         // function parameter list, hence add an explicit check.
1806         bool isDefaultArgument =
1807             !CodeSynthesisContexts.empty() &&
1808             CodeSynthesisContexts.back().Kind ==
1809                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1810         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1811         bool isInstance = CurMethod &&
1812                           CurMethod->isInstance() &&
1813                           DC == CurMethod->getParent() && !isDefaultArgument;
1814 
1815         // Give a code modification hint to insert 'this->'.
1816         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1817         // Actually quite difficult!
1818         if (getLangOpts().MSVCCompat)
1819           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1820         if (isInstance) {
1821           Diag(R.getNameLoc(), diagnostic) << Name
1822             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1823           CheckCXXThisCapture(R.getNameLoc());
1824         } else {
1825           Diag(R.getNameLoc(), diagnostic) << Name;
1826         }
1827 
1828         // Do we really want to note all of these?
1829         for (NamedDecl *D : R)
1830           Diag(D->getLocation(), diag::note_dependent_var_use);
1831 
1832         // Return true if we are inside a default argument instantiation
1833         // and the found name refers to an instance member function, otherwise
1834         // the function calling DiagnoseEmptyLookup will try to create an
1835         // implicit member call and this is wrong for default argument.
1836         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1837           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1838           return true;
1839         }
1840 
1841         // Tell the callee to try to recover.
1842         return false;
1843       }
1844 
1845       R.clear();
1846     }
1847 
1848     // In Microsoft mode, if we are performing lookup from within a friend
1849     // function definition declared at class scope then we must set
1850     // DC to the lexical parent to be able to search into the parent
1851     // class.
1852     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1853         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1854         DC->getLexicalParent()->isRecord())
1855       DC = DC->getLexicalParent();
1856     else
1857       DC = DC->getParent();
1858   }
1859 
1860   // We didn't find anything, so try to correct for a typo.
1861   TypoCorrection Corrected;
1862   if (S && Out) {
1863     SourceLocation TypoLoc = R.getNameLoc();
1864     assert(!ExplicitTemplateArgs &&
1865            "Diagnosing an empty lookup with explicit template args!");
1866     *Out = CorrectTypoDelayed(
1867         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1868         [=](const TypoCorrection &TC) {
1869           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1870                                         diagnostic, diagnostic_suggest);
1871         },
1872         nullptr, CTK_ErrorRecovery);
1873     if (*Out)
1874       return true;
1875   } else if (S && (Corrected =
1876                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1877                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1878     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1879     bool DroppedSpecifier =
1880         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1881     R.setLookupName(Corrected.getCorrection());
1882 
1883     bool AcceptableWithRecovery = false;
1884     bool AcceptableWithoutRecovery = false;
1885     NamedDecl *ND = Corrected.getFoundDecl();
1886     if (ND) {
1887       if (Corrected.isOverloaded()) {
1888         OverloadCandidateSet OCS(R.getNameLoc(),
1889                                  OverloadCandidateSet::CSK_Normal);
1890         OverloadCandidateSet::iterator Best;
1891         for (NamedDecl *CD : Corrected) {
1892           if (FunctionTemplateDecl *FTD =
1893                    dyn_cast<FunctionTemplateDecl>(CD))
1894             AddTemplateOverloadCandidate(
1895                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1896                 Args, OCS);
1897           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1898             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1899               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1900                                    Args, OCS);
1901         }
1902         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1903         case OR_Success:
1904           ND = Best->FoundDecl;
1905           Corrected.setCorrectionDecl(ND);
1906           break;
1907         default:
1908           // FIXME: Arbitrarily pick the first declaration for the note.
1909           Corrected.setCorrectionDecl(ND);
1910           break;
1911         }
1912       }
1913       R.addDecl(ND);
1914       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1915         CXXRecordDecl *Record = nullptr;
1916         if (Corrected.getCorrectionSpecifier()) {
1917           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1918           Record = Ty->getAsCXXRecordDecl();
1919         }
1920         if (!Record)
1921           Record = cast<CXXRecordDecl>(
1922               ND->getDeclContext()->getRedeclContext());
1923         R.setNamingClass(Record);
1924       }
1925 
1926       auto *UnderlyingND = ND->getUnderlyingDecl();
1927       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1928                                isa<FunctionTemplateDecl>(UnderlyingND);
1929       // FIXME: If we ended up with a typo for a type name or
1930       // Objective-C class name, we're in trouble because the parser
1931       // is in the wrong place to recover. Suggest the typo
1932       // correction, but don't make it a fix-it since we're not going
1933       // to recover well anyway.
1934       AcceptableWithoutRecovery =
1935           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1936     } else {
1937       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1938       // because we aren't able to recover.
1939       AcceptableWithoutRecovery = true;
1940     }
1941 
1942     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1943       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1944                             ? diag::note_implicit_param_decl
1945                             : diag::note_previous_decl;
1946       if (SS.isEmpty())
1947         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1948                      PDiag(NoteID), AcceptableWithRecovery);
1949       else
1950         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1951                                   << Name << computeDeclContext(SS, false)
1952                                   << DroppedSpecifier << SS.getRange(),
1953                      PDiag(NoteID), AcceptableWithRecovery);
1954 
1955       // Tell the callee whether to try to recover.
1956       return !AcceptableWithRecovery;
1957     }
1958   }
1959   R.clear();
1960 
1961   // Emit a special diagnostic for failed member lookups.
1962   // FIXME: computing the declaration context might fail here (?)
1963   if (!SS.isEmpty()) {
1964     Diag(R.getNameLoc(), diag::err_no_member)
1965       << Name << computeDeclContext(SS, false)
1966       << SS.getRange();
1967     return true;
1968   }
1969 
1970   // Give up, we can't recover.
1971   Diag(R.getNameLoc(), diagnostic) << Name;
1972   return true;
1973 }
1974 
1975 /// In Microsoft mode, if we are inside a template class whose parent class has
1976 /// dependent base classes, and we can't resolve an unqualified identifier, then
1977 /// assume the identifier is a member of a dependent base class.  We can only
1978 /// recover successfully in static methods, instance methods, and other contexts
1979 /// where 'this' is available.  This doesn't precisely match MSVC's
1980 /// instantiation model, but it's close enough.
1981 static Expr *
1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1983                                DeclarationNameInfo &NameInfo,
1984                                SourceLocation TemplateKWLoc,
1985                                const TemplateArgumentListInfo *TemplateArgs) {
1986   // Only try to recover from lookup into dependent bases in static methods or
1987   // contexts where 'this' is available.
1988   QualType ThisType = S.getCurrentThisType();
1989   const CXXRecordDecl *RD = nullptr;
1990   if (!ThisType.isNull())
1991     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1992   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1993     RD = MD->getParent();
1994   if (!RD || !RD->hasAnyDependentBases())
1995     return nullptr;
1996 
1997   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1998   // is available, suggest inserting 'this->' as a fixit.
1999   SourceLocation Loc = NameInfo.getLoc();
2000   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2001   DB << NameInfo.getName() << RD;
2002 
2003   if (!ThisType.isNull()) {
2004     DB << FixItHint::CreateInsertion(Loc, "this->");
2005     return CXXDependentScopeMemberExpr::Create(
2006         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2007         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2008         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2009   }
2010 
2011   // Synthesize a fake NNS that points to the derived class.  This will
2012   // perform name lookup during template instantiation.
2013   CXXScopeSpec SS;
2014   auto *NNS =
2015       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2016   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2017   return DependentScopeDeclRefExpr::Create(
2018       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2019       TemplateArgs);
2020 }
2021 
2022 ExprResult
2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2024                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2025                         bool HasTrailingLParen, bool IsAddressOfOperand,
2026                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2027                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2028   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2029          "cannot be direct & operand and have a trailing lparen");
2030   if (SS.isInvalid())
2031     return ExprError();
2032 
2033   TemplateArgumentListInfo TemplateArgsBuffer;
2034 
2035   // Decompose the UnqualifiedId into the following data.
2036   DeclarationNameInfo NameInfo;
2037   const TemplateArgumentListInfo *TemplateArgs;
2038   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2039 
2040   DeclarationName Name = NameInfo.getName();
2041   IdentifierInfo *II = Name.getAsIdentifierInfo();
2042   SourceLocation NameLoc = NameInfo.getLoc();
2043 
2044   if (II && II->isEditorPlaceholder()) {
2045     // FIXME: When typed placeholders are supported we can create a typed
2046     // placeholder expression node.
2047     return ExprError();
2048   }
2049 
2050   // C++ [temp.dep.expr]p3:
2051   //   An id-expression is type-dependent if it contains:
2052   //     -- an identifier that was declared with a dependent type,
2053   //        (note: handled after lookup)
2054   //     -- a template-id that is dependent,
2055   //        (note: handled in BuildTemplateIdExpr)
2056   //     -- a conversion-function-id that specifies a dependent type,
2057   //     -- a nested-name-specifier that contains a class-name that
2058   //        names a dependent type.
2059   // Determine whether this is a member of an unknown specialization;
2060   // we need to handle these differently.
2061   bool DependentID = false;
2062   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2063       Name.getCXXNameType()->isDependentType()) {
2064     DependentID = true;
2065   } else if (SS.isSet()) {
2066     if (DeclContext *DC = computeDeclContext(SS, false)) {
2067       if (RequireCompleteDeclContext(SS, DC))
2068         return ExprError();
2069     } else {
2070       DependentID = true;
2071     }
2072   }
2073 
2074   if (DependentID)
2075     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2076                                       IsAddressOfOperand, TemplateArgs);
2077 
2078   // Perform the required lookup.
2079   LookupResult R(*this, NameInfo,
2080                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2081                      ? LookupObjCImplicitSelfParam
2082                      : LookupOrdinaryName);
2083   if (TemplateArgs) {
2084     // Lookup the template name again to correctly establish the context in
2085     // which it was found. This is really unfortunate as we already did the
2086     // lookup to determine that it was a template name in the first place. If
2087     // this becomes a performance hit, we can work harder to preserve those
2088     // results until we get here but it's likely not worth it.
2089     bool MemberOfUnknownSpecialization;
2090     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091                        MemberOfUnknownSpecialization);
2092 
2093     if (MemberOfUnknownSpecialization ||
2094         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2095       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2096                                         IsAddressOfOperand, TemplateArgs);
2097   } else {
2098     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2099     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2100 
2101     // If the result might be in a dependent base class, this is a dependent
2102     // id-expression.
2103     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2104       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2105                                         IsAddressOfOperand, TemplateArgs);
2106 
2107     // If this reference is in an Objective-C method, then we need to do
2108     // some special Objective-C lookup, too.
2109     if (IvarLookupFollowUp) {
2110       ExprResult E(LookupInObjCMethod(R, S, II, true));
2111       if (E.isInvalid())
2112         return ExprError();
2113 
2114       if (Expr *Ex = E.getAs<Expr>())
2115         return Ex;
2116     }
2117   }
2118 
2119   if (R.isAmbiguous())
2120     return ExprError();
2121 
2122   // This could be an implicitly declared function reference (legal in C90,
2123   // extension in C99, forbidden in C++).
2124   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2125     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2126     if (D) R.addDecl(D);
2127   }
2128 
2129   // Determine whether this name might be a candidate for
2130   // argument-dependent lookup.
2131   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2132 
2133   if (R.empty() && !ADL) {
2134     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2135       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2136                                                    TemplateKWLoc, TemplateArgs))
2137         return E;
2138     }
2139 
2140     // Don't diagnose an empty lookup for inline assembly.
2141     if (IsInlineAsmIdentifier)
2142       return ExprError();
2143 
2144     // If this name wasn't predeclared and if this is not a function
2145     // call, diagnose the problem.
2146     TypoExpr *TE = nullptr;
2147     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2148         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2149     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2150     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2151            "Typo correction callback misconfigured");
2152     if (CCC) {
2153       // Make sure the callback knows what the typo being diagnosed is.
2154       CCC->setTypoName(II);
2155       if (SS.isValid())
2156         CCC->setTypoNNS(SS.getScopeRep());
2157     }
2158     if (DiagnoseEmptyLookup(S, SS, R,
2159                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2160                             nullptr, None, &TE)) {
2161       if (TE && KeywordReplacement) {
2162         auto &State = getTypoExprState(TE);
2163         auto BestTC = State.Consumer->getNextCorrection();
2164         if (BestTC.isKeyword()) {
2165           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2166           if (State.DiagHandler)
2167             State.DiagHandler(BestTC);
2168           KeywordReplacement->startToken();
2169           KeywordReplacement->setKind(II->getTokenID());
2170           KeywordReplacement->setIdentifierInfo(II);
2171           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2172           // Clean up the state associated with the TypoExpr, since it has
2173           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2174           clearDelayedTypo(TE);
2175           // Signal that a correction to a keyword was performed by returning a
2176           // valid-but-null ExprResult.
2177           return (Expr*)nullptr;
2178         }
2179         State.Consumer->resetCorrectionStream();
2180       }
2181       return TE ? TE : ExprError();
2182     }
2183 
2184     assert(!R.empty() &&
2185            "DiagnoseEmptyLookup returned false but added no results");
2186 
2187     // If we found an Objective-C instance variable, let
2188     // LookupInObjCMethod build the appropriate expression to
2189     // reference the ivar.
2190     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2191       R.clear();
2192       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2193       // In a hopelessly buggy code, Objective-C instance variable
2194       // lookup fails and no expression will be built to reference it.
2195       if (!E.isInvalid() && !E.get())
2196         return ExprError();
2197       return E;
2198     }
2199   }
2200 
2201   // This is guaranteed from this point on.
2202   assert(!R.empty() || ADL);
2203 
2204   // Check whether this might be a C++ implicit instance member access.
2205   // C++ [class.mfct.non-static]p3:
2206   //   When an id-expression that is not part of a class member access
2207   //   syntax and not used to form a pointer to member is used in the
2208   //   body of a non-static member function of class X, if name lookup
2209   //   resolves the name in the id-expression to a non-static non-type
2210   //   member of some class C, the id-expression is transformed into a
2211   //   class member access expression using (*this) as the
2212   //   postfix-expression to the left of the . operator.
2213   //
2214   // But we don't actually need to do this for '&' operands if R
2215   // resolved to a function or overloaded function set, because the
2216   // expression is ill-formed if it actually works out to be a
2217   // non-static member function:
2218   //
2219   // C++ [expr.ref]p4:
2220   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2221   //   [t]he expression can be used only as the left-hand operand of a
2222   //   member function call.
2223   //
2224   // There are other safeguards against such uses, but it's important
2225   // to get this right here so that we don't end up making a
2226   // spuriously dependent expression if we're inside a dependent
2227   // instance method.
2228   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2229     bool MightBeImplicitMember;
2230     if (!IsAddressOfOperand)
2231       MightBeImplicitMember = true;
2232     else if (!SS.isEmpty())
2233       MightBeImplicitMember = false;
2234     else if (R.isOverloadedResult())
2235       MightBeImplicitMember = false;
2236     else if (R.isUnresolvableResult())
2237       MightBeImplicitMember = true;
2238     else
2239       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2240                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2241                               isa<MSPropertyDecl>(R.getFoundDecl());
2242 
2243     if (MightBeImplicitMember)
2244       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2245                                              R, TemplateArgs, S);
2246   }
2247 
2248   if (TemplateArgs || TemplateKWLoc.isValid()) {
2249 
2250     // In C++1y, if this is a variable template id, then check it
2251     // in BuildTemplateIdExpr().
2252     // The single lookup result must be a variable template declaration.
2253     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2254         Id.TemplateId->Kind == TNK_Var_template) {
2255       assert(R.getAsSingle<VarTemplateDecl>() &&
2256              "There should only be one declaration found.");
2257     }
2258 
2259     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2260   }
2261 
2262   return BuildDeclarationNameExpr(SS, R, ADL);
2263 }
2264 
2265 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2266 /// declaration name, generally during template instantiation.
2267 /// There's a large number of things which don't need to be done along
2268 /// this path.
2269 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2270     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2271     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2272   DeclContext *DC = computeDeclContext(SS, false);
2273   if (!DC)
2274     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2275                                      NameInfo, /*TemplateArgs=*/nullptr);
2276 
2277   if (RequireCompleteDeclContext(SS, DC))
2278     return ExprError();
2279 
2280   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2281   LookupQualifiedName(R, DC);
2282 
2283   if (R.isAmbiguous())
2284     return ExprError();
2285 
2286   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2287     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2288                                      NameInfo, /*TemplateArgs=*/nullptr);
2289 
2290   if (R.empty()) {
2291     Diag(NameInfo.getLoc(), diag::err_no_member)
2292       << NameInfo.getName() << DC << SS.getRange();
2293     return ExprError();
2294   }
2295 
2296   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2297     // Diagnose a missing typename if this resolved unambiguously to a type in
2298     // a dependent context.  If we can recover with a type, downgrade this to
2299     // a warning in Microsoft compatibility mode.
2300     unsigned DiagID = diag::err_typename_missing;
2301     if (RecoveryTSI && getLangOpts().MSVCCompat)
2302       DiagID = diag::ext_typename_missing;
2303     SourceLocation Loc = SS.getBeginLoc();
2304     auto D = Diag(Loc, DiagID);
2305     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2306       << SourceRange(Loc, NameInfo.getEndLoc());
2307 
2308     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2309     // context.
2310     if (!RecoveryTSI)
2311       return ExprError();
2312 
2313     // Only issue the fixit if we're prepared to recover.
2314     D << FixItHint::CreateInsertion(Loc, "typename ");
2315 
2316     // Recover by pretending this was an elaborated type.
2317     QualType Ty = Context.getTypeDeclType(TD);
2318     TypeLocBuilder TLB;
2319     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2320 
2321     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2322     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2323     QTL.setElaboratedKeywordLoc(SourceLocation());
2324     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2325 
2326     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2327 
2328     return ExprEmpty();
2329   }
2330 
2331   // Defend against this resolving to an implicit member access. We usually
2332   // won't get here if this might be a legitimate a class member (we end up in
2333   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2334   // a pointer-to-member or in an unevaluated context in C++11.
2335   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2336     return BuildPossibleImplicitMemberExpr(SS,
2337                                            /*TemplateKWLoc=*/SourceLocation(),
2338                                            R, /*TemplateArgs=*/nullptr, S);
2339 
2340   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2341 }
2342 
2343 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2344 /// detected that we're currently inside an ObjC method.  Perform some
2345 /// additional lookup.
2346 ///
2347 /// Ideally, most of this would be done by lookup, but there's
2348 /// actually quite a lot of extra work involved.
2349 ///
2350 /// Returns a null sentinel to indicate trivial success.
2351 ExprResult
2352 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2353                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2354   SourceLocation Loc = Lookup.getNameLoc();
2355   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2356 
2357   // Check for error condition which is already reported.
2358   if (!CurMethod)
2359     return ExprError();
2360 
2361   // There are two cases to handle here.  1) scoped lookup could have failed,
2362   // in which case we should look for an ivar.  2) scoped lookup could have
2363   // found a decl, but that decl is outside the current instance method (i.e.
2364   // a global variable).  In these two cases, we do a lookup for an ivar with
2365   // this name, if the lookup sucedes, we replace it our current decl.
2366 
2367   // If we're in a class method, we don't normally want to look for
2368   // ivars.  But if we don't find anything else, and there's an
2369   // ivar, that's an error.
2370   bool IsClassMethod = CurMethod->isClassMethod();
2371 
2372   bool LookForIvars;
2373   if (Lookup.empty())
2374     LookForIvars = true;
2375   else if (IsClassMethod)
2376     LookForIvars = false;
2377   else
2378     LookForIvars = (Lookup.isSingleResult() &&
2379                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2380   ObjCInterfaceDecl *IFace = nullptr;
2381   if (LookForIvars) {
2382     IFace = CurMethod->getClassInterface();
2383     ObjCInterfaceDecl *ClassDeclared;
2384     ObjCIvarDecl *IV = nullptr;
2385     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2386       // Diagnose using an ivar in a class method.
2387       if (IsClassMethod)
2388         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2389                          << IV->getDeclName());
2390 
2391       // If we're referencing an invalid decl, just return this as a silent
2392       // error node.  The error diagnostic was already emitted on the decl.
2393       if (IV->isInvalidDecl())
2394         return ExprError();
2395 
2396       // Check if referencing a field with __attribute__((deprecated)).
2397       if (DiagnoseUseOfDecl(IV, Loc))
2398         return ExprError();
2399 
2400       // Diagnose the use of an ivar outside of the declaring class.
2401       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2402           !declaresSameEntity(ClassDeclared, IFace) &&
2403           !getLangOpts().DebuggerSupport)
2404         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2405 
2406       // FIXME: This should use a new expr for a direct reference, don't
2407       // turn this into Self->ivar, just return a BareIVarExpr or something.
2408       IdentifierInfo &II = Context.Idents.get("self");
2409       UnqualifiedId SelfName;
2410       SelfName.setIdentifier(&II, SourceLocation());
2411       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2412       CXXScopeSpec SelfScopeSpec;
2413       SourceLocation TemplateKWLoc;
2414       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2415                                               SelfName, false, false);
2416       if (SelfExpr.isInvalid())
2417         return ExprError();
2418 
2419       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2420       if (SelfExpr.isInvalid())
2421         return ExprError();
2422 
2423       MarkAnyDeclReferenced(Loc, IV, true);
2424 
2425       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2426       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2427           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2428         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2429 
2430       ObjCIvarRefExpr *Result = new (Context)
2431           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2432                           IV->getLocation(), SelfExpr.get(), true, true);
2433 
2434       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2435         if (!isUnevaluatedContext() &&
2436             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2437           getCurFunction()->recordUseOfWeak(Result);
2438       }
2439       if (getLangOpts().ObjCAutoRefCount) {
2440         if (CurContext->isClosure())
2441           Diag(Loc, diag::warn_implicitly_retains_self)
2442             << FixItHint::CreateInsertion(Loc, "self->");
2443       }
2444 
2445       return Result;
2446     }
2447   } else if (CurMethod->isInstanceMethod()) {
2448     // We should warn if a local variable hides an ivar.
2449     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2450       ObjCInterfaceDecl *ClassDeclared;
2451       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2452         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2453             declaresSameEntity(IFace, ClassDeclared))
2454           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2455       }
2456     }
2457   } else if (Lookup.isSingleResult() &&
2458              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2459     // If accessing a stand-alone ivar in a class method, this is an error.
2460     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2461       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2462                        << IV->getDeclName());
2463   }
2464 
2465   if (Lookup.empty() && II && AllowBuiltinCreation) {
2466     // FIXME. Consolidate this with similar code in LookupName.
2467     if (unsigned BuiltinID = II->getBuiltinID()) {
2468       if (!(getLangOpts().CPlusPlus &&
2469             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2470         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2471                                            S, Lookup.isForRedeclaration(),
2472                                            Lookup.getNameLoc());
2473         if (D) Lookup.addDecl(D);
2474       }
2475     }
2476   }
2477   // Sentinel value saying that we didn't do anything special.
2478   return ExprResult((Expr *)nullptr);
2479 }
2480 
2481 /// \brief Cast a base object to a member's actual type.
2482 ///
2483 /// Logically this happens in three phases:
2484 ///
2485 /// * First we cast from the base type to the naming class.
2486 ///   The naming class is the class into which we were looking
2487 ///   when we found the member;  it's the qualifier type if a
2488 ///   qualifier was provided, and otherwise it's the base type.
2489 ///
2490 /// * Next we cast from the naming class to the declaring class.
2491 ///   If the member we found was brought into a class's scope by
2492 ///   a using declaration, this is that class;  otherwise it's
2493 ///   the class declaring the member.
2494 ///
2495 /// * Finally we cast from the declaring class to the "true"
2496 ///   declaring class of the member.  This conversion does not
2497 ///   obey access control.
2498 ExprResult
2499 Sema::PerformObjectMemberConversion(Expr *From,
2500                                     NestedNameSpecifier *Qualifier,
2501                                     NamedDecl *FoundDecl,
2502                                     NamedDecl *Member) {
2503   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2504   if (!RD)
2505     return From;
2506 
2507   QualType DestRecordType;
2508   QualType DestType;
2509   QualType FromRecordType;
2510   QualType FromType = From->getType();
2511   bool PointerConversions = false;
2512   if (isa<FieldDecl>(Member)) {
2513     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2514 
2515     if (FromType->getAs<PointerType>()) {
2516       DestType = Context.getPointerType(DestRecordType);
2517       FromRecordType = FromType->getPointeeType();
2518       PointerConversions = true;
2519     } else {
2520       DestType = DestRecordType;
2521       FromRecordType = FromType;
2522     }
2523   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2524     if (Method->isStatic())
2525       return From;
2526 
2527     DestType = Method->getThisType(Context);
2528     DestRecordType = DestType->getPointeeType();
2529 
2530     if (FromType->getAs<PointerType>()) {
2531       FromRecordType = FromType->getPointeeType();
2532       PointerConversions = true;
2533     } else {
2534       FromRecordType = FromType;
2535       DestType = DestRecordType;
2536     }
2537   } else {
2538     // No conversion necessary.
2539     return From;
2540   }
2541 
2542   if (DestType->isDependentType() || FromType->isDependentType())
2543     return From;
2544 
2545   // If the unqualified types are the same, no conversion is necessary.
2546   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2547     return From;
2548 
2549   SourceRange FromRange = From->getSourceRange();
2550   SourceLocation FromLoc = FromRange.getBegin();
2551 
2552   ExprValueKind VK = From->getValueKind();
2553 
2554   // C++ [class.member.lookup]p8:
2555   //   [...] Ambiguities can often be resolved by qualifying a name with its
2556   //   class name.
2557   //
2558   // If the member was a qualified name and the qualified referred to a
2559   // specific base subobject type, we'll cast to that intermediate type
2560   // first and then to the object in which the member is declared. That allows
2561   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2562   //
2563   //   class Base { public: int x; };
2564   //   class Derived1 : public Base { };
2565   //   class Derived2 : public Base { };
2566   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2567   //
2568   //   void VeryDerived::f() {
2569   //     x = 17; // error: ambiguous base subobjects
2570   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2571   //   }
2572   if (Qualifier && Qualifier->getAsType()) {
2573     QualType QType = QualType(Qualifier->getAsType(), 0);
2574     assert(QType->isRecordType() && "lookup done with non-record type");
2575 
2576     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2577 
2578     // In C++98, the qualifier type doesn't actually have to be a base
2579     // type of the object type, in which case we just ignore it.
2580     // Otherwise build the appropriate casts.
2581     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2582       CXXCastPath BasePath;
2583       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2584                                        FromLoc, FromRange, &BasePath))
2585         return ExprError();
2586 
2587       if (PointerConversions)
2588         QType = Context.getPointerType(QType);
2589       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2590                                VK, &BasePath).get();
2591 
2592       FromType = QType;
2593       FromRecordType = QRecordType;
2594 
2595       // If the qualifier type was the same as the destination type,
2596       // we're done.
2597       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2598         return From;
2599     }
2600   }
2601 
2602   bool IgnoreAccess = false;
2603 
2604   // If we actually found the member through a using declaration, cast
2605   // down to the using declaration's type.
2606   //
2607   // Pointer equality is fine here because only one declaration of a
2608   // class ever has member declarations.
2609   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2610     assert(isa<UsingShadowDecl>(FoundDecl));
2611     QualType URecordType = Context.getTypeDeclType(
2612                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2613 
2614     // We only need to do this if the naming-class to declaring-class
2615     // conversion is non-trivial.
2616     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2617       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2618       CXXCastPath BasePath;
2619       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2620                                        FromLoc, FromRange, &BasePath))
2621         return ExprError();
2622 
2623       QualType UType = URecordType;
2624       if (PointerConversions)
2625         UType = Context.getPointerType(UType);
2626       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2627                                VK, &BasePath).get();
2628       FromType = UType;
2629       FromRecordType = URecordType;
2630     }
2631 
2632     // We don't do access control for the conversion from the
2633     // declaring class to the true declaring class.
2634     IgnoreAccess = true;
2635   }
2636 
2637   CXXCastPath BasePath;
2638   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2639                                    FromLoc, FromRange, &BasePath,
2640                                    IgnoreAccess))
2641     return ExprError();
2642 
2643   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2644                            VK, &BasePath);
2645 }
2646 
2647 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2648                                       const LookupResult &R,
2649                                       bool HasTrailingLParen) {
2650   // Only when used directly as the postfix-expression of a call.
2651   if (!HasTrailingLParen)
2652     return false;
2653 
2654   // Never if a scope specifier was provided.
2655   if (SS.isSet())
2656     return false;
2657 
2658   // Only in C++ or ObjC++.
2659   if (!getLangOpts().CPlusPlus)
2660     return false;
2661 
2662   // Turn off ADL when we find certain kinds of declarations during
2663   // normal lookup:
2664   for (NamedDecl *D : R) {
2665     // C++0x [basic.lookup.argdep]p3:
2666     //     -- a declaration of a class member
2667     // Since using decls preserve this property, we check this on the
2668     // original decl.
2669     if (D->isCXXClassMember())
2670       return false;
2671 
2672     // C++0x [basic.lookup.argdep]p3:
2673     //     -- a block-scope function declaration that is not a
2674     //        using-declaration
2675     // NOTE: we also trigger this for function templates (in fact, we
2676     // don't check the decl type at all, since all other decl types
2677     // turn off ADL anyway).
2678     if (isa<UsingShadowDecl>(D))
2679       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2680     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2681       return false;
2682 
2683     // C++0x [basic.lookup.argdep]p3:
2684     //     -- a declaration that is neither a function or a function
2685     //        template
2686     // And also for builtin functions.
2687     if (isa<FunctionDecl>(D)) {
2688       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2689 
2690       // But also builtin functions.
2691       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2692         return false;
2693     } else if (!isa<FunctionTemplateDecl>(D))
2694       return false;
2695   }
2696 
2697   return true;
2698 }
2699 
2700 
2701 /// Diagnoses obvious problems with the use of the given declaration
2702 /// as an expression.  This is only actually called for lookups that
2703 /// were not overloaded, and it doesn't promise that the declaration
2704 /// will in fact be used.
2705 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2706   if (D->isInvalidDecl())
2707     return true;
2708 
2709   if (isa<TypedefNameDecl>(D)) {
2710     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2711     return true;
2712   }
2713 
2714   if (isa<ObjCInterfaceDecl>(D)) {
2715     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2716     return true;
2717   }
2718 
2719   if (isa<NamespaceDecl>(D)) {
2720     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2721     return true;
2722   }
2723 
2724   return false;
2725 }
2726 
2727 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2728                                           LookupResult &R, bool NeedsADL,
2729                                           bool AcceptInvalidDecl) {
2730   // If this is a single, fully-resolved result and we don't need ADL,
2731   // just build an ordinary singleton decl ref.
2732   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2733     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2734                                     R.getRepresentativeDecl(), nullptr,
2735                                     AcceptInvalidDecl);
2736 
2737   // We only need to check the declaration if there's exactly one
2738   // result, because in the overloaded case the results can only be
2739   // functions and function templates.
2740   if (R.isSingleResult() &&
2741       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2742     return ExprError();
2743 
2744   // Otherwise, just build an unresolved lookup expression.  Suppress
2745   // any lookup-related diagnostics; we'll hash these out later, when
2746   // we've picked a target.
2747   R.suppressDiagnostics();
2748 
2749   UnresolvedLookupExpr *ULE
2750     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2751                                    SS.getWithLocInContext(Context),
2752                                    R.getLookupNameInfo(),
2753                                    NeedsADL, R.isOverloadedResult(),
2754                                    R.begin(), R.end());
2755 
2756   return ULE;
2757 }
2758 
2759 static void
2760 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2761                                    ValueDecl *var, DeclContext *DC);
2762 
2763 /// \brief Complete semantic analysis for a reference to the given declaration.
2764 ExprResult Sema::BuildDeclarationNameExpr(
2765     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2766     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2767     bool AcceptInvalidDecl) {
2768   assert(D && "Cannot refer to a NULL declaration");
2769   assert(!isa<FunctionTemplateDecl>(D) &&
2770          "Cannot refer unambiguously to a function template");
2771 
2772   SourceLocation Loc = NameInfo.getLoc();
2773   if (CheckDeclInExpr(*this, Loc, D))
2774     return ExprError();
2775 
2776   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2777     // Specifically diagnose references to class templates that are missing
2778     // a template argument list.
2779     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2780                                            << Template << SS.getRange();
2781     Diag(Template->getLocation(), diag::note_template_decl_here);
2782     return ExprError();
2783   }
2784 
2785   // Make sure that we're referring to a value.
2786   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2787   if (!VD) {
2788     Diag(Loc, diag::err_ref_non_value)
2789       << D << SS.getRange();
2790     Diag(D->getLocation(), diag::note_declared_at);
2791     return ExprError();
2792   }
2793 
2794   // Check whether this declaration can be used. Note that we suppress
2795   // this check when we're going to perform argument-dependent lookup
2796   // on this function name, because this might not be the function
2797   // that overload resolution actually selects.
2798   if (DiagnoseUseOfDecl(VD, Loc))
2799     return ExprError();
2800 
2801   // Only create DeclRefExpr's for valid Decl's.
2802   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2803     return ExprError();
2804 
2805   // Handle members of anonymous structs and unions.  If we got here,
2806   // and the reference is to a class member indirect field, then this
2807   // must be the subject of a pointer-to-member expression.
2808   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2809     if (!indirectField->isCXXClassMember())
2810       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2811                                                       indirectField);
2812 
2813   {
2814     QualType type = VD->getType();
2815     if (type.isNull())
2816       return ExprError();
2817     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2818       // C++ [except.spec]p17:
2819       //   An exception-specification is considered to be needed when:
2820       //   - in an expression, the function is the unique lookup result or
2821       //     the selected member of a set of overloaded functions.
2822       ResolveExceptionSpec(Loc, FPT);
2823       type = VD->getType();
2824     }
2825     ExprValueKind valueKind = VK_RValue;
2826 
2827     switch (D->getKind()) {
2828     // Ignore all the non-ValueDecl kinds.
2829 #define ABSTRACT_DECL(kind)
2830 #define VALUE(type, base)
2831 #define DECL(type, base) \
2832     case Decl::type:
2833 #include "clang/AST/DeclNodes.inc"
2834       llvm_unreachable("invalid value decl kind");
2835 
2836     // These shouldn't make it here.
2837     case Decl::ObjCAtDefsField:
2838     case Decl::ObjCIvar:
2839       llvm_unreachable("forming non-member reference to ivar?");
2840 
2841     // Enum constants are always r-values and never references.
2842     // Unresolved using declarations are dependent.
2843     case Decl::EnumConstant:
2844     case Decl::UnresolvedUsingValue:
2845     case Decl::OMPDeclareReduction:
2846       valueKind = VK_RValue;
2847       break;
2848 
2849     // Fields and indirect fields that got here must be for
2850     // pointer-to-member expressions; we just call them l-values for
2851     // internal consistency, because this subexpression doesn't really
2852     // exist in the high-level semantics.
2853     case Decl::Field:
2854     case Decl::IndirectField:
2855       assert(getLangOpts().CPlusPlus &&
2856              "building reference to field in C?");
2857 
2858       // These can't have reference type in well-formed programs, but
2859       // for internal consistency we do this anyway.
2860       type = type.getNonReferenceType();
2861       valueKind = VK_LValue;
2862       break;
2863 
2864     // Non-type template parameters are either l-values or r-values
2865     // depending on the type.
2866     case Decl::NonTypeTemplateParm: {
2867       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2868         type = reftype->getPointeeType();
2869         valueKind = VK_LValue; // even if the parameter is an r-value reference
2870         break;
2871       }
2872 
2873       // For non-references, we need to strip qualifiers just in case
2874       // the template parameter was declared as 'const int' or whatever.
2875       valueKind = VK_RValue;
2876       type = type.getUnqualifiedType();
2877       break;
2878     }
2879 
2880     case Decl::Var:
2881     case Decl::VarTemplateSpecialization:
2882     case Decl::VarTemplatePartialSpecialization:
2883     case Decl::Decomposition:
2884     case Decl::OMPCapturedExpr:
2885       // In C, "extern void blah;" is valid and is an r-value.
2886       if (!getLangOpts().CPlusPlus &&
2887           !type.hasQualifiers() &&
2888           type->isVoidType()) {
2889         valueKind = VK_RValue;
2890         break;
2891       }
2892       LLVM_FALLTHROUGH;
2893 
2894     case Decl::ImplicitParam:
2895     case Decl::ParmVar: {
2896       // These are always l-values.
2897       valueKind = VK_LValue;
2898       type = type.getNonReferenceType();
2899 
2900       // FIXME: Does the addition of const really only apply in
2901       // potentially-evaluated contexts? Since the variable isn't actually
2902       // captured in an unevaluated context, it seems that the answer is no.
2903       if (!isUnevaluatedContext()) {
2904         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2905         if (!CapturedType.isNull())
2906           type = CapturedType;
2907       }
2908 
2909       break;
2910     }
2911 
2912     case Decl::Binding: {
2913       // These are always lvalues.
2914       valueKind = VK_LValue;
2915       type = type.getNonReferenceType();
2916       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2917       // decides how that's supposed to work.
2918       auto *BD = cast<BindingDecl>(VD);
2919       if (BD->getDeclContext()->isFunctionOrMethod() &&
2920           BD->getDeclContext() != CurContext)
2921         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2922       break;
2923     }
2924 
2925     case Decl::Function: {
2926       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2927         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2928           type = Context.BuiltinFnTy;
2929           valueKind = VK_RValue;
2930           break;
2931         }
2932       }
2933 
2934       const FunctionType *fty = type->castAs<FunctionType>();
2935 
2936       // If we're referring to a function with an __unknown_anytype
2937       // result type, make the entire expression __unknown_anytype.
2938       if (fty->getReturnType() == Context.UnknownAnyTy) {
2939         type = Context.UnknownAnyTy;
2940         valueKind = VK_RValue;
2941         break;
2942       }
2943 
2944       // Functions are l-values in C++.
2945       if (getLangOpts().CPlusPlus) {
2946         valueKind = VK_LValue;
2947         break;
2948       }
2949 
2950       // C99 DR 316 says that, if a function type comes from a
2951       // function definition (without a prototype), that type is only
2952       // used for checking compatibility. Therefore, when referencing
2953       // the function, we pretend that we don't have the full function
2954       // type.
2955       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2956           isa<FunctionProtoType>(fty))
2957         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2958                                               fty->getExtInfo());
2959 
2960       // Functions are r-values in C.
2961       valueKind = VK_RValue;
2962       break;
2963     }
2964 
2965     case Decl::CXXDeductionGuide:
2966       llvm_unreachable("building reference to deduction guide");
2967 
2968     case Decl::MSProperty:
2969       valueKind = VK_LValue;
2970       break;
2971 
2972     case Decl::CXXMethod:
2973       // If we're referring to a method with an __unknown_anytype
2974       // result type, make the entire expression __unknown_anytype.
2975       // This should only be possible with a type written directly.
2976       if (const FunctionProtoType *proto
2977             = dyn_cast<FunctionProtoType>(VD->getType()))
2978         if (proto->getReturnType() == Context.UnknownAnyTy) {
2979           type = Context.UnknownAnyTy;
2980           valueKind = VK_RValue;
2981           break;
2982         }
2983 
2984       // C++ methods are l-values if static, r-values if non-static.
2985       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2986         valueKind = VK_LValue;
2987         break;
2988       }
2989       LLVM_FALLTHROUGH;
2990 
2991     case Decl::CXXConversion:
2992     case Decl::CXXDestructor:
2993     case Decl::CXXConstructor:
2994       valueKind = VK_RValue;
2995       break;
2996     }
2997 
2998     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2999                             TemplateArgs);
3000   }
3001 }
3002 
3003 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3004                                     SmallString<32> &Target) {
3005   Target.resize(CharByteWidth * (Source.size() + 1));
3006   char *ResultPtr = &Target[0];
3007   const llvm::UTF8 *ErrorPtr;
3008   bool success =
3009       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3010   (void)success;
3011   assert(success);
3012   Target.resize(ResultPtr - &Target[0]);
3013 }
3014 
3015 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3016                                      PredefinedExpr::IdentType IT) {
3017   // Pick the current block, lambda, captured statement or function.
3018   Decl *currentDecl = nullptr;
3019   if (const BlockScopeInfo *BSI = getCurBlock())
3020     currentDecl = BSI->TheDecl;
3021   else if (const LambdaScopeInfo *LSI = getCurLambda())
3022     currentDecl = LSI->CallOperator;
3023   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3024     currentDecl = CSI->TheCapturedDecl;
3025   else
3026     currentDecl = getCurFunctionOrMethodDecl();
3027 
3028   if (!currentDecl) {
3029     Diag(Loc, diag::ext_predef_outside_function);
3030     currentDecl = Context.getTranslationUnitDecl();
3031   }
3032 
3033   QualType ResTy;
3034   StringLiteral *SL = nullptr;
3035   if (cast<DeclContext>(currentDecl)->isDependentContext())
3036     ResTy = Context.DependentTy;
3037   else {
3038     // Pre-defined identifiers are of type char[x], where x is the length of
3039     // the string.
3040     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3041     unsigned Length = Str.length();
3042 
3043     llvm::APInt LengthI(32, Length + 1);
3044     if (IT == PredefinedExpr::LFunction) {
3045       ResTy = Context.WideCharTy.withConst();
3046       SmallString<32> RawChars;
3047       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3048                               Str, RawChars);
3049       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3050                                            /*IndexTypeQuals*/ 0);
3051       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3052                                  /*Pascal*/ false, ResTy, Loc);
3053     } else {
3054       ResTy = Context.CharTy.withConst();
3055       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3056                                            /*IndexTypeQuals*/ 0);
3057       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3058                                  /*Pascal*/ false, ResTy, Loc);
3059     }
3060   }
3061 
3062   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3063 }
3064 
3065 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3066   PredefinedExpr::IdentType IT;
3067 
3068   switch (Kind) {
3069   default: llvm_unreachable("Unknown simple primary expr!");
3070   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3071   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3072   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3073   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3074   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3075   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3076   }
3077 
3078   return BuildPredefinedExpr(Loc, IT);
3079 }
3080 
3081 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3082   SmallString<16> CharBuffer;
3083   bool Invalid = false;
3084   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3085   if (Invalid)
3086     return ExprError();
3087 
3088   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3089                             PP, Tok.getKind());
3090   if (Literal.hadError())
3091     return ExprError();
3092 
3093   QualType Ty;
3094   if (Literal.isWide())
3095     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3096   else if (Literal.isUTF16())
3097     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3098   else if (Literal.isUTF32())
3099     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3100   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3101     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3102   else
3103     Ty = Context.CharTy;  // 'x' -> char in C++
3104 
3105   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3106   if (Literal.isWide())
3107     Kind = CharacterLiteral::Wide;
3108   else if (Literal.isUTF16())
3109     Kind = CharacterLiteral::UTF16;
3110   else if (Literal.isUTF32())
3111     Kind = CharacterLiteral::UTF32;
3112   else if (Literal.isUTF8())
3113     Kind = CharacterLiteral::UTF8;
3114 
3115   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3116                                              Tok.getLocation());
3117 
3118   if (Literal.getUDSuffix().empty())
3119     return Lit;
3120 
3121   // We're building a user-defined literal.
3122   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3123   SourceLocation UDSuffixLoc =
3124     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3125 
3126   // Make sure we're allowed user-defined literals here.
3127   if (!UDLScope)
3128     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3129 
3130   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3131   //   operator "" X (ch)
3132   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3133                                         Lit, Tok.getLocation());
3134 }
3135 
3136 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3137   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3138   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3139                                 Context.IntTy, Loc);
3140 }
3141 
3142 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3143                                   QualType Ty, SourceLocation Loc) {
3144   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3145 
3146   using llvm::APFloat;
3147   APFloat Val(Format);
3148 
3149   APFloat::opStatus result = Literal.GetFloatValue(Val);
3150 
3151   // Overflow is always an error, but underflow is only an error if
3152   // we underflowed to zero (APFloat reports denormals as underflow).
3153   if ((result & APFloat::opOverflow) ||
3154       ((result & APFloat::opUnderflow) && Val.isZero())) {
3155     unsigned diagnostic;
3156     SmallString<20> buffer;
3157     if (result & APFloat::opOverflow) {
3158       diagnostic = diag::warn_float_overflow;
3159       APFloat::getLargest(Format).toString(buffer);
3160     } else {
3161       diagnostic = diag::warn_float_underflow;
3162       APFloat::getSmallest(Format).toString(buffer);
3163     }
3164 
3165     S.Diag(Loc, diagnostic)
3166       << Ty
3167       << StringRef(buffer.data(), buffer.size());
3168   }
3169 
3170   bool isExact = (result == APFloat::opOK);
3171   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3172 }
3173 
3174 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3175   assert(E && "Invalid expression");
3176 
3177   if (E->isValueDependent())
3178     return false;
3179 
3180   QualType QT = E->getType();
3181   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3182     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3183     return true;
3184   }
3185 
3186   llvm::APSInt ValueAPS;
3187   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3188 
3189   if (R.isInvalid())
3190     return true;
3191 
3192   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3193   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3194     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3195         << ValueAPS.toString(10) << ValueIsPositive;
3196     return true;
3197   }
3198 
3199   return false;
3200 }
3201 
3202 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3203   // Fast path for a single digit (which is quite common).  A single digit
3204   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3205   if (Tok.getLength() == 1) {
3206     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3207     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3208   }
3209 
3210   SmallString<128> SpellingBuffer;
3211   // NumericLiteralParser wants to overread by one character.  Add padding to
3212   // the buffer in case the token is copied to the buffer.  If getSpelling()
3213   // returns a StringRef to the memory buffer, it should have a null char at
3214   // the EOF, so it is also safe.
3215   SpellingBuffer.resize(Tok.getLength() + 1);
3216 
3217   // Get the spelling of the token, which eliminates trigraphs, etc.
3218   bool Invalid = false;
3219   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3220   if (Invalid)
3221     return ExprError();
3222 
3223   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3224   if (Literal.hadError)
3225     return ExprError();
3226 
3227   if (Literal.hasUDSuffix()) {
3228     // We're building a user-defined literal.
3229     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3230     SourceLocation UDSuffixLoc =
3231       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3232 
3233     // Make sure we're allowed user-defined literals here.
3234     if (!UDLScope)
3235       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3236 
3237     QualType CookedTy;
3238     if (Literal.isFloatingLiteral()) {
3239       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3240       // long double, the literal is treated as a call of the form
3241       //   operator "" X (f L)
3242       CookedTy = Context.LongDoubleTy;
3243     } else {
3244       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3245       // unsigned long long, the literal is treated as a call of the form
3246       //   operator "" X (n ULL)
3247       CookedTy = Context.UnsignedLongLongTy;
3248     }
3249 
3250     DeclarationName OpName =
3251       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3252     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3253     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3254 
3255     SourceLocation TokLoc = Tok.getLocation();
3256 
3257     // Perform literal operator lookup to determine if we're building a raw
3258     // literal or a cooked one.
3259     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3260     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3261                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3262                                   /*AllowStringTemplate*/ false,
3263                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3264     case LOLR_ErrorNoDiagnostic:
3265       // Lookup failure for imaginary constants isn't fatal, there's still the
3266       // GNU extension producing _Complex types.
3267       break;
3268     case LOLR_Error:
3269       return ExprError();
3270     case LOLR_Cooked: {
3271       Expr *Lit;
3272       if (Literal.isFloatingLiteral()) {
3273         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3274       } else {
3275         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3276         if (Literal.GetIntegerValue(ResultVal))
3277           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3278               << /* Unsigned */ 1;
3279         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3280                                      Tok.getLocation());
3281       }
3282       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3283     }
3284 
3285     case LOLR_Raw: {
3286       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3287       // literal is treated as a call of the form
3288       //   operator "" X ("n")
3289       unsigned Length = Literal.getUDSuffixOffset();
3290       QualType StrTy = Context.getConstantArrayType(
3291           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3292           ArrayType::Normal, 0);
3293       Expr *Lit = StringLiteral::Create(
3294           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3295           /*Pascal*/false, StrTy, &TokLoc, 1);
3296       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3297     }
3298 
3299     case LOLR_Template: {
3300       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3301       // template), L is treated as a call fo the form
3302       //   operator "" X <'c1', 'c2', ... 'ck'>()
3303       // where n is the source character sequence c1 c2 ... ck.
3304       TemplateArgumentListInfo ExplicitArgs;
3305       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3306       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3307       llvm::APSInt Value(CharBits, CharIsUnsigned);
3308       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3309         Value = TokSpelling[I];
3310         TemplateArgument Arg(Context, Value, Context.CharTy);
3311         TemplateArgumentLocInfo ArgInfo;
3312         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3313       }
3314       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3315                                       &ExplicitArgs);
3316     }
3317     case LOLR_StringTemplate:
3318       llvm_unreachable("unexpected literal operator lookup result");
3319     }
3320   }
3321 
3322   Expr *Res;
3323 
3324   if (Literal.isFloatingLiteral()) {
3325     QualType Ty;
3326     if (Literal.isHalf){
3327       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3328         Ty = Context.HalfTy;
3329       else {
3330         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3331         return ExprError();
3332       }
3333     } else if (Literal.isFloat)
3334       Ty = Context.FloatTy;
3335     else if (Literal.isLong)
3336       Ty = Context.LongDoubleTy;
3337     else if (Literal.isFloat16)
3338       Ty = Context.Float16Ty;
3339     else if (Literal.isFloat128)
3340       Ty = Context.Float128Ty;
3341     else
3342       Ty = Context.DoubleTy;
3343 
3344     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3345 
3346     if (Ty == Context.DoubleTy) {
3347       if (getLangOpts().SinglePrecisionConstants) {
3348         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3349         if (BTy->getKind() != BuiltinType::Float) {
3350           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3351         }
3352       } else if (getLangOpts().OpenCL &&
3353                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3354         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3355         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3356         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3357       }
3358     }
3359   } else if (!Literal.isIntegerLiteral()) {
3360     return ExprError();
3361   } else {
3362     QualType Ty;
3363 
3364     // 'long long' is a C99 or C++11 feature.
3365     if (!getLangOpts().C99 && Literal.isLongLong) {
3366       if (getLangOpts().CPlusPlus)
3367         Diag(Tok.getLocation(),
3368              getLangOpts().CPlusPlus11 ?
3369              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3370       else
3371         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3372     }
3373 
3374     // Get the value in the widest-possible width.
3375     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3376     llvm::APInt ResultVal(MaxWidth, 0);
3377 
3378     if (Literal.GetIntegerValue(ResultVal)) {
3379       // If this value didn't fit into uintmax_t, error and force to ull.
3380       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3381           << /* Unsigned */ 1;
3382       Ty = Context.UnsignedLongLongTy;
3383       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3384              "long long is not intmax_t?");
3385     } else {
3386       // If this value fits into a ULL, try to figure out what else it fits into
3387       // according to the rules of C99 6.4.4.1p5.
3388 
3389       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3390       // be an unsigned int.
3391       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3392 
3393       // Check from smallest to largest, picking the smallest type we can.
3394       unsigned Width = 0;
3395 
3396       // Microsoft specific integer suffixes are explicitly sized.
3397       if (Literal.MicrosoftInteger) {
3398         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3399           Width = 8;
3400           Ty = Context.CharTy;
3401         } else {
3402           Width = Literal.MicrosoftInteger;
3403           Ty = Context.getIntTypeForBitwidth(Width,
3404                                              /*Signed=*/!Literal.isUnsigned);
3405         }
3406       }
3407 
3408       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3409         // Are int/unsigned possibilities?
3410         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3411 
3412         // Does it fit in a unsigned int?
3413         if (ResultVal.isIntN(IntSize)) {
3414           // Does it fit in a signed int?
3415           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3416             Ty = Context.IntTy;
3417           else if (AllowUnsigned)
3418             Ty = Context.UnsignedIntTy;
3419           Width = IntSize;
3420         }
3421       }
3422 
3423       // Are long/unsigned long possibilities?
3424       if (Ty.isNull() && !Literal.isLongLong) {
3425         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3426 
3427         // Does it fit in a unsigned long?
3428         if (ResultVal.isIntN(LongSize)) {
3429           // Does it fit in a signed long?
3430           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3431             Ty = Context.LongTy;
3432           else if (AllowUnsigned)
3433             Ty = Context.UnsignedLongTy;
3434           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3435           // is compatible.
3436           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3437             const unsigned LongLongSize =
3438                 Context.getTargetInfo().getLongLongWidth();
3439             Diag(Tok.getLocation(),
3440                  getLangOpts().CPlusPlus
3441                      ? Literal.isLong
3442                            ? diag::warn_old_implicitly_unsigned_long_cxx
3443                            : /*C++98 UB*/ diag::
3444                                  ext_old_implicitly_unsigned_long_cxx
3445                      : diag::warn_old_implicitly_unsigned_long)
3446                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3447                                             : /*will be ill-formed*/ 1);
3448             Ty = Context.UnsignedLongTy;
3449           }
3450           Width = LongSize;
3451         }
3452       }
3453 
3454       // Check long long if needed.
3455       if (Ty.isNull()) {
3456         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3457 
3458         // Does it fit in a unsigned long long?
3459         if (ResultVal.isIntN(LongLongSize)) {
3460           // Does it fit in a signed long long?
3461           // To be compatible with MSVC, hex integer literals ending with the
3462           // LL or i64 suffix are always signed in Microsoft mode.
3463           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3464               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3465             Ty = Context.LongLongTy;
3466           else if (AllowUnsigned)
3467             Ty = Context.UnsignedLongLongTy;
3468           Width = LongLongSize;
3469         }
3470       }
3471 
3472       // If we still couldn't decide a type, we probably have something that
3473       // does not fit in a signed long long, but has no U suffix.
3474       if (Ty.isNull()) {
3475         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3476         Ty = Context.UnsignedLongLongTy;
3477         Width = Context.getTargetInfo().getLongLongWidth();
3478       }
3479 
3480       if (ResultVal.getBitWidth() != Width)
3481         ResultVal = ResultVal.trunc(Width);
3482     }
3483     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3484   }
3485 
3486   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3487   if (Literal.isImaginary) {
3488     Res = new (Context) ImaginaryLiteral(Res,
3489                                         Context.getComplexType(Res->getType()));
3490 
3491     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3492   }
3493   return Res;
3494 }
3495 
3496 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3497   assert(E && "ActOnParenExpr() missing expr");
3498   return new (Context) ParenExpr(L, R, E);
3499 }
3500 
3501 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3502                                          SourceLocation Loc,
3503                                          SourceRange ArgRange) {
3504   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3505   // scalar or vector data type argument..."
3506   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3507   // type (C99 6.2.5p18) or void.
3508   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3509     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3510       << T << ArgRange;
3511     return true;
3512   }
3513 
3514   assert((T->isVoidType() || !T->isIncompleteType()) &&
3515          "Scalar types should always be complete");
3516   return false;
3517 }
3518 
3519 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3520                                            SourceLocation Loc,
3521                                            SourceRange ArgRange,
3522                                            UnaryExprOrTypeTrait TraitKind) {
3523   // Invalid types must be hard errors for SFINAE in C++.
3524   if (S.LangOpts.CPlusPlus)
3525     return true;
3526 
3527   // C99 6.5.3.4p1:
3528   if (T->isFunctionType() &&
3529       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3530     // sizeof(function)/alignof(function) is allowed as an extension.
3531     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3532       << TraitKind << ArgRange;
3533     return false;
3534   }
3535 
3536   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3537   // this is an error (OpenCL v1.1 s6.3.k)
3538   if (T->isVoidType()) {
3539     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3540                                         : diag::ext_sizeof_alignof_void_type;
3541     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3542     return false;
3543   }
3544 
3545   return true;
3546 }
3547 
3548 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3549                                              SourceLocation Loc,
3550                                              SourceRange ArgRange,
3551                                              UnaryExprOrTypeTrait TraitKind) {
3552   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3553   // runtime doesn't allow it.
3554   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3555     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3556       << T << (TraitKind == UETT_SizeOf)
3557       << ArgRange;
3558     return true;
3559   }
3560 
3561   return false;
3562 }
3563 
3564 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3565 /// pointer type is equal to T) and emit a warning if it is.
3566 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3567                                      Expr *E) {
3568   // Don't warn if the operation changed the type.
3569   if (T != E->getType())
3570     return;
3571 
3572   // Now look for array decays.
3573   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3574   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3575     return;
3576 
3577   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3578                                              << ICE->getType()
3579                                              << ICE->getSubExpr()->getType();
3580 }
3581 
3582 /// \brief Check the constraints on expression operands to unary type expression
3583 /// and type traits.
3584 ///
3585 /// Completes any types necessary and validates the constraints on the operand
3586 /// expression. The logic mostly mirrors the type-based overload, but may modify
3587 /// the expression as it completes the type for that expression through template
3588 /// instantiation, etc.
3589 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3590                                             UnaryExprOrTypeTrait ExprKind) {
3591   QualType ExprTy = E->getType();
3592   assert(!ExprTy->isReferenceType());
3593 
3594   if (ExprKind == UETT_VecStep)
3595     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3596                                         E->getSourceRange());
3597 
3598   // Whitelist some types as extensions
3599   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3600                                       E->getSourceRange(), ExprKind))
3601     return false;
3602 
3603   // 'alignof' applied to an expression only requires the base element type of
3604   // the expression to be complete. 'sizeof' requires the expression's type to
3605   // be complete (and will attempt to complete it if it's an array of unknown
3606   // bound).
3607   if (ExprKind == UETT_AlignOf) {
3608     if (RequireCompleteType(E->getExprLoc(),
3609                             Context.getBaseElementType(E->getType()),
3610                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3611                             E->getSourceRange()))
3612       return true;
3613   } else {
3614     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3615                                 ExprKind, E->getSourceRange()))
3616       return true;
3617   }
3618 
3619   // Completing the expression's type may have changed it.
3620   ExprTy = E->getType();
3621   assert(!ExprTy->isReferenceType());
3622 
3623   if (ExprTy->isFunctionType()) {
3624     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3625       << ExprKind << E->getSourceRange();
3626     return true;
3627   }
3628 
3629   // The operand for sizeof and alignof is in an unevaluated expression context,
3630   // so side effects could result in unintended consequences.
3631   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3632       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3633     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3634 
3635   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3636                                        E->getSourceRange(), ExprKind))
3637     return true;
3638 
3639   if (ExprKind == UETT_SizeOf) {
3640     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3641       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3642         QualType OType = PVD->getOriginalType();
3643         QualType Type = PVD->getType();
3644         if (Type->isPointerType() && OType->isArrayType()) {
3645           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3646             << Type << OType;
3647           Diag(PVD->getLocation(), diag::note_declared_at);
3648         }
3649       }
3650     }
3651 
3652     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3653     // decays into a pointer and returns an unintended result. This is most
3654     // likely a typo for "sizeof(array) op x".
3655     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3656       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3657                                BO->getLHS());
3658       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3659                                BO->getRHS());
3660     }
3661   }
3662 
3663   return false;
3664 }
3665 
3666 /// \brief Check the constraints on operands to unary expression and type
3667 /// traits.
3668 ///
3669 /// This will complete any types necessary, and validate the various constraints
3670 /// on those operands.
3671 ///
3672 /// The UsualUnaryConversions() function is *not* called by this routine.
3673 /// C99 6.3.2.1p[2-4] all state:
3674 ///   Except when it is the operand of the sizeof operator ...
3675 ///
3676 /// C++ [expr.sizeof]p4
3677 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3678 ///   standard conversions are not applied to the operand of sizeof.
3679 ///
3680 /// This policy is followed for all of the unary trait expressions.
3681 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3682                                             SourceLocation OpLoc,
3683                                             SourceRange ExprRange,
3684                                             UnaryExprOrTypeTrait ExprKind) {
3685   if (ExprType->isDependentType())
3686     return false;
3687 
3688   // C++ [expr.sizeof]p2:
3689   //     When applied to a reference or a reference type, the result
3690   //     is the size of the referenced type.
3691   // C++11 [expr.alignof]p3:
3692   //     When alignof is applied to a reference type, the result
3693   //     shall be the alignment of the referenced type.
3694   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3695     ExprType = Ref->getPointeeType();
3696 
3697   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3698   //   When alignof or _Alignof is applied to an array type, the result
3699   //   is the alignment of the element type.
3700   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3701     ExprType = Context.getBaseElementType(ExprType);
3702 
3703   if (ExprKind == UETT_VecStep)
3704     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3705 
3706   // Whitelist some types as extensions
3707   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3708                                       ExprKind))
3709     return false;
3710 
3711   if (RequireCompleteType(OpLoc, ExprType,
3712                           diag::err_sizeof_alignof_incomplete_type,
3713                           ExprKind, ExprRange))
3714     return true;
3715 
3716   if (ExprType->isFunctionType()) {
3717     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3718       << ExprKind << ExprRange;
3719     return true;
3720   }
3721 
3722   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3723                                        ExprKind))
3724     return true;
3725 
3726   return false;
3727 }
3728 
3729 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3730   E = E->IgnoreParens();
3731 
3732   // Cannot know anything else if the expression is dependent.
3733   if (E->isTypeDependent())
3734     return false;
3735 
3736   if (E->getObjectKind() == OK_BitField) {
3737     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3738        << 1 << E->getSourceRange();
3739     return true;
3740   }
3741 
3742   ValueDecl *D = nullptr;
3743   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3744     D = DRE->getDecl();
3745   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3746     D = ME->getMemberDecl();
3747   }
3748 
3749   // If it's a field, require the containing struct to have a
3750   // complete definition so that we can compute the layout.
3751   //
3752   // This can happen in C++11 onwards, either by naming the member
3753   // in a way that is not transformed into a member access expression
3754   // (in an unevaluated operand, for instance), or by naming the member
3755   // in a trailing-return-type.
3756   //
3757   // For the record, since __alignof__ on expressions is a GCC
3758   // extension, GCC seems to permit this but always gives the
3759   // nonsensical answer 0.
3760   //
3761   // We don't really need the layout here --- we could instead just
3762   // directly check for all the appropriate alignment-lowing
3763   // attributes --- but that would require duplicating a lot of
3764   // logic that just isn't worth duplicating for such a marginal
3765   // use-case.
3766   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3767     // Fast path this check, since we at least know the record has a
3768     // definition if we can find a member of it.
3769     if (!FD->getParent()->isCompleteDefinition()) {
3770       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3771         << E->getSourceRange();
3772       return true;
3773     }
3774 
3775     // Otherwise, if it's a field, and the field doesn't have
3776     // reference type, then it must have a complete type (or be a
3777     // flexible array member, which we explicitly want to
3778     // white-list anyway), which makes the following checks trivial.
3779     if (!FD->getType()->isReferenceType())
3780       return false;
3781   }
3782 
3783   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3784 }
3785 
3786 bool Sema::CheckVecStepExpr(Expr *E) {
3787   E = E->IgnoreParens();
3788 
3789   // Cannot know anything else if the expression is dependent.
3790   if (E->isTypeDependent())
3791     return false;
3792 
3793   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3794 }
3795 
3796 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3797                                         CapturingScopeInfo *CSI) {
3798   assert(T->isVariablyModifiedType());
3799   assert(CSI != nullptr);
3800 
3801   // We're going to walk down into the type and look for VLA expressions.
3802   do {
3803     const Type *Ty = T.getTypePtr();
3804     switch (Ty->getTypeClass()) {
3805 #define TYPE(Class, Base)
3806 #define ABSTRACT_TYPE(Class, Base)
3807 #define NON_CANONICAL_TYPE(Class, Base)
3808 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3809 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3810 #include "clang/AST/TypeNodes.def"
3811       T = QualType();
3812       break;
3813     // These types are never variably-modified.
3814     case Type::Builtin:
3815     case Type::Complex:
3816     case Type::Vector:
3817     case Type::ExtVector:
3818     case Type::Record:
3819     case Type::Enum:
3820     case Type::Elaborated:
3821     case Type::TemplateSpecialization:
3822     case Type::ObjCObject:
3823     case Type::ObjCInterface:
3824     case Type::ObjCObjectPointer:
3825     case Type::ObjCTypeParam:
3826     case Type::Pipe:
3827       llvm_unreachable("type class is never variably-modified!");
3828     case Type::Adjusted:
3829       T = cast<AdjustedType>(Ty)->getOriginalType();
3830       break;
3831     case Type::Decayed:
3832       T = cast<DecayedType>(Ty)->getPointeeType();
3833       break;
3834     case Type::Pointer:
3835       T = cast<PointerType>(Ty)->getPointeeType();
3836       break;
3837     case Type::BlockPointer:
3838       T = cast<BlockPointerType>(Ty)->getPointeeType();
3839       break;
3840     case Type::LValueReference:
3841     case Type::RValueReference:
3842       T = cast<ReferenceType>(Ty)->getPointeeType();
3843       break;
3844     case Type::MemberPointer:
3845       T = cast<MemberPointerType>(Ty)->getPointeeType();
3846       break;
3847     case Type::ConstantArray:
3848     case Type::IncompleteArray:
3849       // Losing element qualification here is fine.
3850       T = cast<ArrayType>(Ty)->getElementType();
3851       break;
3852     case Type::VariableArray: {
3853       // Losing element qualification here is fine.
3854       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3855 
3856       // Unknown size indication requires no size computation.
3857       // Otherwise, evaluate and record it.
3858       if (auto Size = VAT->getSizeExpr()) {
3859         if (!CSI->isVLATypeCaptured(VAT)) {
3860           RecordDecl *CapRecord = nullptr;
3861           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3862             CapRecord = LSI->Lambda;
3863           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3864             CapRecord = CRSI->TheRecordDecl;
3865           }
3866           if (CapRecord) {
3867             auto ExprLoc = Size->getExprLoc();
3868             auto SizeType = Context.getSizeType();
3869             // Build the non-static data member.
3870             auto Field =
3871                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3872                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3873                                   /*BW*/ nullptr, /*Mutable*/ false,
3874                                   /*InitStyle*/ ICIS_NoInit);
3875             Field->setImplicit(true);
3876             Field->setAccess(AS_private);
3877             Field->setCapturedVLAType(VAT);
3878             CapRecord->addDecl(Field);
3879 
3880             CSI->addVLATypeCapture(ExprLoc, SizeType);
3881           }
3882         }
3883       }
3884       T = VAT->getElementType();
3885       break;
3886     }
3887     case Type::FunctionProto:
3888     case Type::FunctionNoProto:
3889       T = cast<FunctionType>(Ty)->getReturnType();
3890       break;
3891     case Type::Paren:
3892     case Type::TypeOf:
3893     case Type::UnaryTransform:
3894     case Type::Attributed:
3895     case Type::SubstTemplateTypeParm:
3896     case Type::PackExpansion:
3897       // Keep walking after single level desugaring.
3898       T = T.getSingleStepDesugaredType(Context);
3899       break;
3900     case Type::Typedef:
3901       T = cast<TypedefType>(Ty)->desugar();
3902       break;
3903     case Type::Decltype:
3904       T = cast<DecltypeType>(Ty)->desugar();
3905       break;
3906     case Type::Auto:
3907     case Type::DeducedTemplateSpecialization:
3908       T = cast<DeducedType>(Ty)->getDeducedType();
3909       break;
3910     case Type::TypeOfExpr:
3911       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3912       break;
3913     case Type::Atomic:
3914       T = cast<AtomicType>(Ty)->getValueType();
3915       break;
3916     }
3917   } while (!T.isNull() && T->isVariablyModifiedType());
3918 }
3919 
3920 /// \brief Build a sizeof or alignof expression given a type operand.
3921 ExprResult
3922 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3923                                      SourceLocation OpLoc,
3924                                      UnaryExprOrTypeTrait ExprKind,
3925                                      SourceRange R) {
3926   if (!TInfo)
3927     return ExprError();
3928 
3929   QualType T = TInfo->getType();
3930 
3931   if (!T->isDependentType() &&
3932       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3933     return ExprError();
3934 
3935   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3936     if (auto *TT = T->getAs<TypedefType>()) {
3937       for (auto I = FunctionScopes.rbegin(),
3938                 E = std::prev(FunctionScopes.rend());
3939            I != E; ++I) {
3940         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3941         if (CSI == nullptr)
3942           break;
3943         DeclContext *DC = nullptr;
3944         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3945           DC = LSI->CallOperator;
3946         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3947           DC = CRSI->TheCapturedDecl;
3948         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3949           DC = BSI->TheDecl;
3950         if (DC) {
3951           if (DC->containsDecl(TT->getDecl()))
3952             break;
3953           captureVariablyModifiedType(Context, T, CSI);
3954         }
3955       }
3956     }
3957   }
3958 
3959   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3960   return new (Context) UnaryExprOrTypeTraitExpr(
3961       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3962 }
3963 
3964 /// \brief Build a sizeof or alignof expression given an expression
3965 /// operand.
3966 ExprResult
3967 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3968                                      UnaryExprOrTypeTrait ExprKind) {
3969   ExprResult PE = CheckPlaceholderExpr(E);
3970   if (PE.isInvalid())
3971     return ExprError();
3972 
3973   E = PE.get();
3974 
3975   // Verify that the operand is valid.
3976   bool isInvalid = false;
3977   if (E->isTypeDependent()) {
3978     // Delay type-checking for type-dependent expressions.
3979   } else if (ExprKind == UETT_AlignOf) {
3980     isInvalid = CheckAlignOfExpr(*this, E);
3981   } else if (ExprKind == UETT_VecStep) {
3982     isInvalid = CheckVecStepExpr(E);
3983   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3984       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3985       isInvalid = true;
3986   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3987     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3988     isInvalid = true;
3989   } else {
3990     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3991   }
3992 
3993   if (isInvalid)
3994     return ExprError();
3995 
3996   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3997     PE = TransformToPotentiallyEvaluated(E);
3998     if (PE.isInvalid()) return ExprError();
3999     E = PE.get();
4000   }
4001 
4002   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4003   return new (Context) UnaryExprOrTypeTraitExpr(
4004       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4005 }
4006 
4007 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4008 /// expr and the same for @c alignof and @c __alignof
4009 /// Note that the ArgRange is invalid if isType is false.
4010 ExprResult
4011 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4012                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4013                                     void *TyOrEx, SourceRange ArgRange) {
4014   // If error parsing type, ignore.
4015   if (!TyOrEx) return ExprError();
4016 
4017   if (IsType) {
4018     TypeSourceInfo *TInfo;
4019     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4020     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4021   }
4022 
4023   Expr *ArgEx = (Expr *)TyOrEx;
4024   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4025   return Result;
4026 }
4027 
4028 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4029                                      bool IsReal) {
4030   if (V.get()->isTypeDependent())
4031     return S.Context.DependentTy;
4032 
4033   // _Real and _Imag are only l-values for normal l-values.
4034   if (V.get()->getObjectKind() != OK_Ordinary) {
4035     V = S.DefaultLvalueConversion(V.get());
4036     if (V.isInvalid())
4037       return QualType();
4038   }
4039 
4040   // These operators return the element type of a complex type.
4041   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4042     return CT->getElementType();
4043 
4044   // Otherwise they pass through real integer and floating point types here.
4045   if (V.get()->getType()->isArithmeticType())
4046     return V.get()->getType();
4047 
4048   // Test for placeholders.
4049   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4050   if (PR.isInvalid()) return QualType();
4051   if (PR.get() != V.get()) {
4052     V = PR;
4053     return CheckRealImagOperand(S, V, Loc, IsReal);
4054   }
4055 
4056   // Reject anything else.
4057   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4058     << (IsReal ? "__real" : "__imag");
4059   return QualType();
4060 }
4061 
4062 
4063 
4064 ExprResult
4065 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4066                           tok::TokenKind Kind, Expr *Input) {
4067   UnaryOperatorKind Opc;
4068   switch (Kind) {
4069   default: llvm_unreachable("Unknown unary op!");
4070   case tok::plusplus:   Opc = UO_PostInc; break;
4071   case tok::minusminus: Opc = UO_PostDec; break;
4072   }
4073 
4074   // Since this might is a postfix expression, get rid of ParenListExprs.
4075   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4076   if (Result.isInvalid()) return ExprError();
4077   Input = Result.get();
4078 
4079   return BuildUnaryOp(S, OpLoc, Opc, Input);
4080 }
4081 
4082 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4083 ///
4084 /// \return true on error
4085 static bool checkArithmeticOnObjCPointer(Sema &S,
4086                                          SourceLocation opLoc,
4087                                          Expr *op) {
4088   assert(op->getType()->isObjCObjectPointerType());
4089   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4090       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4091     return false;
4092 
4093   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4094     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4095     << op->getSourceRange();
4096   return true;
4097 }
4098 
4099 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4100   auto *BaseNoParens = Base->IgnoreParens();
4101   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4102     return MSProp->getPropertyDecl()->getType()->isArrayType();
4103   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4104 }
4105 
4106 ExprResult
4107 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4108                               Expr *idx, SourceLocation rbLoc) {
4109   if (base && !base->getType().isNull() &&
4110       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4111     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4112                                     /*Length=*/nullptr, rbLoc);
4113 
4114   // Since this might be a postfix expression, get rid of ParenListExprs.
4115   if (isa<ParenListExpr>(base)) {
4116     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4117     if (result.isInvalid()) return ExprError();
4118     base = result.get();
4119   }
4120 
4121   // Handle any non-overload placeholder types in the base and index
4122   // expressions.  We can't handle overloads here because the other
4123   // operand might be an overloadable type, in which case the overload
4124   // resolution for the operator overload should get the first crack
4125   // at the overload.
4126   bool IsMSPropertySubscript = false;
4127   if (base->getType()->isNonOverloadPlaceholderType()) {
4128     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4129     if (!IsMSPropertySubscript) {
4130       ExprResult result = CheckPlaceholderExpr(base);
4131       if (result.isInvalid())
4132         return ExprError();
4133       base = result.get();
4134     }
4135   }
4136   if (idx->getType()->isNonOverloadPlaceholderType()) {
4137     ExprResult result = CheckPlaceholderExpr(idx);
4138     if (result.isInvalid()) return ExprError();
4139     idx = result.get();
4140   }
4141 
4142   // Build an unanalyzed expression if either operand is type-dependent.
4143   if (getLangOpts().CPlusPlus &&
4144       (base->isTypeDependent() || idx->isTypeDependent())) {
4145     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4146                                             VK_LValue, OK_Ordinary, rbLoc);
4147   }
4148 
4149   // MSDN, property (C++)
4150   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4151   // This attribute can also be used in the declaration of an empty array in a
4152   // class or structure definition. For example:
4153   // __declspec(property(get=GetX, put=PutX)) int x[];
4154   // The above statement indicates that x[] can be used with one or more array
4155   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4156   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4157   if (IsMSPropertySubscript) {
4158     // Build MS property subscript expression if base is MS property reference
4159     // or MS property subscript.
4160     return new (Context) MSPropertySubscriptExpr(
4161         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4162   }
4163 
4164   // Use C++ overloaded-operator rules if either operand has record
4165   // type.  The spec says to do this if either type is *overloadable*,
4166   // but enum types can't declare subscript operators or conversion
4167   // operators, so there's nothing interesting for overload resolution
4168   // to do if there aren't any record types involved.
4169   //
4170   // ObjC pointers have their own subscripting logic that is not tied
4171   // to overload resolution and so should not take this path.
4172   if (getLangOpts().CPlusPlus &&
4173       (base->getType()->isRecordType() ||
4174        (!base->getType()->isObjCObjectPointerType() &&
4175         idx->getType()->isRecordType()))) {
4176     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4177   }
4178 
4179   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4180 }
4181 
4182 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4183                                           Expr *LowerBound,
4184                                           SourceLocation ColonLoc, Expr *Length,
4185                                           SourceLocation RBLoc) {
4186   if (Base->getType()->isPlaceholderType() &&
4187       !Base->getType()->isSpecificPlaceholderType(
4188           BuiltinType::OMPArraySection)) {
4189     ExprResult Result = CheckPlaceholderExpr(Base);
4190     if (Result.isInvalid())
4191       return ExprError();
4192     Base = Result.get();
4193   }
4194   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4195     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4196     if (Result.isInvalid())
4197       return ExprError();
4198     Result = DefaultLvalueConversion(Result.get());
4199     if (Result.isInvalid())
4200       return ExprError();
4201     LowerBound = Result.get();
4202   }
4203   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4204     ExprResult Result = CheckPlaceholderExpr(Length);
4205     if (Result.isInvalid())
4206       return ExprError();
4207     Result = DefaultLvalueConversion(Result.get());
4208     if (Result.isInvalid())
4209       return ExprError();
4210     Length = Result.get();
4211   }
4212 
4213   // Build an unanalyzed expression if either operand is type-dependent.
4214   if (Base->isTypeDependent() ||
4215       (LowerBound &&
4216        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4217       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4218     return new (Context)
4219         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4220                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4221   }
4222 
4223   // Perform default conversions.
4224   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4225   QualType ResultTy;
4226   if (OriginalTy->isAnyPointerType()) {
4227     ResultTy = OriginalTy->getPointeeType();
4228   } else if (OriginalTy->isArrayType()) {
4229     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4230   } else {
4231     return ExprError(
4232         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4233         << Base->getSourceRange());
4234   }
4235   // C99 6.5.2.1p1
4236   if (LowerBound) {
4237     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4238                                                       LowerBound);
4239     if (Res.isInvalid())
4240       return ExprError(Diag(LowerBound->getExprLoc(),
4241                             diag::err_omp_typecheck_section_not_integer)
4242                        << 0 << LowerBound->getSourceRange());
4243     LowerBound = Res.get();
4244 
4245     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4246         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4247       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4248           << 0 << LowerBound->getSourceRange();
4249   }
4250   if (Length) {
4251     auto Res =
4252         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4253     if (Res.isInvalid())
4254       return ExprError(Diag(Length->getExprLoc(),
4255                             diag::err_omp_typecheck_section_not_integer)
4256                        << 1 << Length->getSourceRange());
4257     Length = Res.get();
4258 
4259     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4260         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4261       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4262           << 1 << Length->getSourceRange();
4263   }
4264 
4265   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4266   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4267   // type. Note that functions are not objects, and that (in C99 parlance)
4268   // incomplete types are not object types.
4269   if (ResultTy->isFunctionType()) {
4270     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4271         << ResultTy << Base->getSourceRange();
4272     return ExprError();
4273   }
4274 
4275   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4276                           diag::err_omp_section_incomplete_type, Base))
4277     return ExprError();
4278 
4279   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4280     llvm::APSInt LowerBoundValue;
4281     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4282       // OpenMP 4.5, [2.4 Array Sections]
4283       // The array section must be a subset of the original array.
4284       if (LowerBoundValue.isNegative()) {
4285         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4286             << LowerBound->getSourceRange();
4287         return ExprError();
4288       }
4289     }
4290   }
4291 
4292   if (Length) {
4293     llvm::APSInt LengthValue;
4294     if (Length->EvaluateAsInt(LengthValue, Context)) {
4295       // OpenMP 4.5, [2.4 Array Sections]
4296       // The length must evaluate to non-negative integers.
4297       if (LengthValue.isNegative()) {
4298         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4299             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4300             << Length->getSourceRange();
4301         return ExprError();
4302       }
4303     }
4304   } else if (ColonLoc.isValid() &&
4305              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4306                                       !OriginalTy->isVariableArrayType()))) {
4307     // OpenMP 4.5, [2.4 Array Sections]
4308     // When the size of the array dimension is not known, the length must be
4309     // specified explicitly.
4310     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4311         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4312     return ExprError();
4313   }
4314 
4315   if (!Base->getType()->isSpecificPlaceholderType(
4316           BuiltinType::OMPArraySection)) {
4317     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4318     if (Result.isInvalid())
4319       return ExprError();
4320     Base = Result.get();
4321   }
4322   return new (Context)
4323       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4324                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4325 }
4326 
4327 ExprResult
4328 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4329                                       Expr *Idx, SourceLocation RLoc) {
4330   Expr *LHSExp = Base;
4331   Expr *RHSExp = Idx;
4332 
4333   ExprValueKind VK = VK_LValue;
4334   ExprObjectKind OK = OK_Ordinary;
4335 
4336   // Per C++ core issue 1213, the result is an xvalue if either operand is
4337   // a non-lvalue array, and an lvalue otherwise.
4338   if (getLangOpts().CPlusPlus11 &&
4339       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4340        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4341     VK = VK_XValue;
4342 
4343   // Perform default conversions.
4344   if (!LHSExp->getType()->getAs<VectorType>()) {
4345     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4346     if (Result.isInvalid())
4347       return ExprError();
4348     LHSExp = Result.get();
4349   }
4350   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4351   if (Result.isInvalid())
4352     return ExprError();
4353   RHSExp = Result.get();
4354 
4355   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4356 
4357   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4358   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4359   // in the subscript position. As a result, we need to derive the array base
4360   // and index from the expression types.
4361   Expr *BaseExpr, *IndexExpr;
4362   QualType ResultType;
4363   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4364     BaseExpr = LHSExp;
4365     IndexExpr = RHSExp;
4366     ResultType = Context.DependentTy;
4367   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4368     BaseExpr = LHSExp;
4369     IndexExpr = RHSExp;
4370     ResultType = PTy->getPointeeType();
4371   } else if (const ObjCObjectPointerType *PTy =
4372                LHSTy->getAs<ObjCObjectPointerType>()) {
4373     BaseExpr = LHSExp;
4374     IndexExpr = RHSExp;
4375 
4376     // Use custom logic if this should be the pseudo-object subscript
4377     // expression.
4378     if (!LangOpts.isSubscriptPointerArithmetic())
4379       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4380                                           nullptr);
4381 
4382     ResultType = PTy->getPointeeType();
4383   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4384      // Handle the uncommon case of "123[Ptr]".
4385     BaseExpr = RHSExp;
4386     IndexExpr = LHSExp;
4387     ResultType = PTy->getPointeeType();
4388   } else if (const ObjCObjectPointerType *PTy =
4389                RHSTy->getAs<ObjCObjectPointerType>()) {
4390      // Handle the uncommon case of "123[Ptr]".
4391     BaseExpr = RHSExp;
4392     IndexExpr = LHSExp;
4393     ResultType = PTy->getPointeeType();
4394     if (!LangOpts.isSubscriptPointerArithmetic()) {
4395       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4396         << ResultType << BaseExpr->getSourceRange();
4397       return ExprError();
4398     }
4399   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4400     BaseExpr = LHSExp;    // vectors: V[123]
4401     IndexExpr = RHSExp;
4402     VK = LHSExp->getValueKind();
4403     if (VK != VK_RValue)
4404       OK = OK_VectorComponent;
4405 
4406     ResultType = VTy->getElementType();
4407     QualType BaseType = BaseExpr->getType();
4408     Qualifiers BaseQuals = BaseType.getQualifiers();
4409     Qualifiers MemberQuals = ResultType.getQualifiers();
4410     Qualifiers Combined = BaseQuals + MemberQuals;
4411     if (Combined != MemberQuals)
4412       ResultType = Context.getQualifiedType(ResultType, Combined);
4413   } else if (LHSTy->isArrayType()) {
4414     // If we see an array that wasn't promoted by
4415     // DefaultFunctionArrayLvalueConversion, it must be an array that
4416     // wasn't promoted because of the C90 rule that doesn't
4417     // allow promoting non-lvalue arrays.  Warn, then
4418     // force the promotion here.
4419     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4420         LHSExp->getSourceRange();
4421     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4422                                CK_ArrayToPointerDecay).get();
4423     LHSTy = LHSExp->getType();
4424 
4425     BaseExpr = LHSExp;
4426     IndexExpr = RHSExp;
4427     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4428   } else if (RHSTy->isArrayType()) {
4429     // Same as previous, except for 123[f().a] case
4430     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4431         RHSExp->getSourceRange();
4432     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4433                                CK_ArrayToPointerDecay).get();
4434     RHSTy = RHSExp->getType();
4435 
4436     BaseExpr = RHSExp;
4437     IndexExpr = LHSExp;
4438     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4439   } else {
4440     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4441        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4442   }
4443   // C99 6.5.2.1p1
4444   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4445     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4446                      << IndexExpr->getSourceRange());
4447 
4448   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4449        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4450          && !IndexExpr->isTypeDependent())
4451     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4452 
4453   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4454   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4455   // type. Note that Functions are not objects, and that (in C99 parlance)
4456   // incomplete types are not object types.
4457   if (ResultType->isFunctionType()) {
4458     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4459       << ResultType << BaseExpr->getSourceRange();
4460     return ExprError();
4461   }
4462 
4463   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4464     // GNU extension: subscripting on pointer to void
4465     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4466       << BaseExpr->getSourceRange();
4467 
4468     // C forbids expressions of unqualified void type from being l-values.
4469     // See IsCForbiddenLValueType.
4470     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4471   } else if (!ResultType->isDependentType() &&
4472       RequireCompleteType(LLoc, ResultType,
4473                           diag::err_subscript_incomplete_type, BaseExpr))
4474     return ExprError();
4475 
4476   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4477          !ResultType.isCForbiddenLValueType());
4478 
4479   return new (Context)
4480       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4481 }
4482 
4483 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4484                                   ParmVarDecl *Param) {
4485   if (Param->hasUnparsedDefaultArg()) {
4486     Diag(CallLoc,
4487          diag::err_use_of_default_argument_to_function_declared_later) <<
4488       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4489     Diag(UnparsedDefaultArgLocs[Param],
4490          diag::note_default_argument_declared_here);
4491     return true;
4492   }
4493 
4494   if (Param->hasUninstantiatedDefaultArg()) {
4495     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4496 
4497     EnterExpressionEvaluationContext EvalContext(
4498         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4499 
4500     // Instantiate the expression.
4501     //
4502     // FIXME: Pass in a correct Pattern argument, otherwise
4503     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4504     //
4505     // template<typename T>
4506     // struct A {
4507     //   static int FooImpl();
4508     //
4509     //   template<typename Tp>
4510     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4511     //   // template argument list [[T], [Tp]], should be [[Tp]].
4512     //   friend A<Tp> Foo(int a);
4513     // };
4514     //
4515     // template<typename T>
4516     // A<T> Foo(int a = A<T>::FooImpl());
4517     MultiLevelTemplateArgumentList MutiLevelArgList
4518       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4519 
4520     InstantiatingTemplate Inst(*this, CallLoc, Param,
4521                                MutiLevelArgList.getInnermost());
4522     if (Inst.isInvalid())
4523       return true;
4524     if (Inst.isAlreadyInstantiating()) {
4525       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4526       Param->setInvalidDecl();
4527       return true;
4528     }
4529 
4530     ExprResult Result;
4531     {
4532       // C++ [dcl.fct.default]p5:
4533       //   The names in the [default argument] expression are bound, and
4534       //   the semantic constraints are checked, at the point where the
4535       //   default argument expression appears.
4536       ContextRAII SavedContext(*this, FD);
4537       LocalInstantiationScope Local(*this);
4538       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4539                                 /*DirectInit*/false);
4540     }
4541     if (Result.isInvalid())
4542       return true;
4543 
4544     // Check the expression as an initializer for the parameter.
4545     InitializedEntity Entity
4546       = InitializedEntity::InitializeParameter(Context, Param);
4547     InitializationKind Kind
4548       = InitializationKind::CreateCopy(Param->getLocation(),
4549              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4550     Expr *ResultE = Result.getAs<Expr>();
4551 
4552     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4553     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4554     if (Result.isInvalid())
4555       return true;
4556 
4557     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4558                                  Param->getOuterLocStart());
4559     if (Result.isInvalid())
4560       return true;
4561 
4562     // Remember the instantiated default argument.
4563     Param->setDefaultArg(Result.getAs<Expr>());
4564     if (ASTMutationListener *L = getASTMutationListener()) {
4565       L->DefaultArgumentInstantiated(Param);
4566     }
4567   }
4568 
4569   // If the default argument expression is not set yet, we are building it now.
4570   if (!Param->hasInit()) {
4571     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4572     Param->setInvalidDecl();
4573     return true;
4574   }
4575 
4576   // If the default expression creates temporaries, we need to
4577   // push them to the current stack of expression temporaries so they'll
4578   // be properly destroyed.
4579   // FIXME: We should really be rebuilding the default argument with new
4580   // bound temporaries; see the comment in PR5810.
4581   // We don't need to do that with block decls, though, because
4582   // blocks in default argument expression can never capture anything.
4583   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4584     // Set the "needs cleanups" bit regardless of whether there are
4585     // any explicit objects.
4586     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4587 
4588     // Append all the objects to the cleanup list.  Right now, this
4589     // should always be a no-op, because blocks in default argument
4590     // expressions should never be able to capture anything.
4591     assert(!Init->getNumObjects() &&
4592            "default argument expression has capturing blocks?");
4593   }
4594 
4595   // We already type-checked the argument, so we know it works.
4596   // Just mark all of the declarations in this potentially-evaluated expression
4597   // as being "referenced".
4598   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4599                                    /*SkipLocalVariables=*/true);
4600   return false;
4601 }
4602 
4603 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4604                                         FunctionDecl *FD, ParmVarDecl *Param) {
4605   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4606     return ExprError();
4607   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4608 }
4609 
4610 Sema::VariadicCallType
4611 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4612                           Expr *Fn) {
4613   if (Proto && Proto->isVariadic()) {
4614     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4615       return VariadicConstructor;
4616     else if (Fn && Fn->getType()->isBlockPointerType())
4617       return VariadicBlock;
4618     else if (FDecl) {
4619       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4620         if (Method->isInstance())
4621           return VariadicMethod;
4622     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4623       return VariadicMethod;
4624     return VariadicFunction;
4625   }
4626   return VariadicDoesNotApply;
4627 }
4628 
4629 namespace {
4630 class FunctionCallCCC : public FunctionCallFilterCCC {
4631 public:
4632   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4633                   unsigned NumArgs, MemberExpr *ME)
4634       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4635         FunctionName(FuncName) {}
4636 
4637   bool ValidateCandidate(const TypoCorrection &candidate) override {
4638     if (!candidate.getCorrectionSpecifier() ||
4639         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4640       return false;
4641     }
4642 
4643     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4644   }
4645 
4646 private:
4647   const IdentifierInfo *const FunctionName;
4648 };
4649 }
4650 
4651 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4652                                                FunctionDecl *FDecl,
4653                                                ArrayRef<Expr *> Args) {
4654   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4655   DeclarationName FuncName = FDecl->getDeclName();
4656   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4657 
4658   if (TypoCorrection Corrected = S.CorrectTypo(
4659           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4660           S.getScopeForContext(S.CurContext), nullptr,
4661           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4662                                              Args.size(), ME),
4663           Sema::CTK_ErrorRecovery)) {
4664     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4665       if (Corrected.isOverloaded()) {
4666         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4667         OverloadCandidateSet::iterator Best;
4668         for (NamedDecl *CD : Corrected) {
4669           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4670             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4671                                    OCS);
4672         }
4673         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4674         case OR_Success:
4675           ND = Best->FoundDecl;
4676           Corrected.setCorrectionDecl(ND);
4677           break;
4678         default:
4679           break;
4680         }
4681       }
4682       ND = ND->getUnderlyingDecl();
4683       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4684         return Corrected;
4685     }
4686   }
4687   return TypoCorrection();
4688 }
4689 
4690 /// ConvertArgumentsForCall - Converts the arguments specified in
4691 /// Args/NumArgs to the parameter types of the function FDecl with
4692 /// function prototype Proto. Call is the call expression itself, and
4693 /// Fn is the function expression. For a C++ member function, this
4694 /// routine does not attempt to convert the object argument. Returns
4695 /// true if the call is ill-formed.
4696 bool
4697 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4698                               FunctionDecl *FDecl,
4699                               const FunctionProtoType *Proto,
4700                               ArrayRef<Expr *> Args,
4701                               SourceLocation RParenLoc,
4702                               bool IsExecConfig) {
4703   // Bail out early if calling a builtin with custom typechecking.
4704   if (FDecl)
4705     if (unsigned ID = FDecl->getBuiltinID())
4706       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4707         return false;
4708 
4709   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4710   // assignment, to the types of the corresponding parameter, ...
4711   unsigned NumParams = Proto->getNumParams();
4712   bool Invalid = false;
4713   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4714   unsigned FnKind = Fn->getType()->isBlockPointerType()
4715                        ? 1 /* block */
4716                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4717                                        : 0 /* function */);
4718 
4719   // If too few arguments are available (and we don't have default
4720   // arguments for the remaining parameters), don't make the call.
4721   if (Args.size() < NumParams) {
4722     if (Args.size() < MinArgs) {
4723       TypoCorrection TC;
4724       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4725         unsigned diag_id =
4726             MinArgs == NumParams && !Proto->isVariadic()
4727                 ? diag::err_typecheck_call_too_few_args_suggest
4728                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4729         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4730                                         << static_cast<unsigned>(Args.size())
4731                                         << TC.getCorrectionRange());
4732       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4733         Diag(RParenLoc,
4734              MinArgs == NumParams && !Proto->isVariadic()
4735                  ? diag::err_typecheck_call_too_few_args_one
4736                  : diag::err_typecheck_call_too_few_args_at_least_one)
4737             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4738       else
4739         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4740                             ? diag::err_typecheck_call_too_few_args
4741                             : diag::err_typecheck_call_too_few_args_at_least)
4742             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4743             << Fn->getSourceRange();
4744 
4745       // Emit the location of the prototype.
4746       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4747         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4748           << FDecl;
4749 
4750       return true;
4751     }
4752     Call->setNumArgs(Context, NumParams);
4753   }
4754 
4755   // If too many are passed and not variadic, error on the extras and drop
4756   // them.
4757   if (Args.size() > NumParams) {
4758     if (!Proto->isVariadic()) {
4759       TypoCorrection TC;
4760       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4761         unsigned diag_id =
4762             MinArgs == NumParams && !Proto->isVariadic()
4763                 ? diag::err_typecheck_call_too_many_args_suggest
4764                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4765         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4766                                         << static_cast<unsigned>(Args.size())
4767                                         << TC.getCorrectionRange());
4768       } else if (NumParams == 1 && FDecl &&
4769                  FDecl->getParamDecl(0)->getDeclName())
4770         Diag(Args[NumParams]->getLocStart(),
4771              MinArgs == NumParams
4772                  ? diag::err_typecheck_call_too_many_args_one
4773                  : diag::err_typecheck_call_too_many_args_at_most_one)
4774             << FnKind << FDecl->getParamDecl(0)
4775             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4776             << SourceRange(Args[NumParams]->getLocStart(),
4777                            Args.back()->getLocEnd());
4778       else
4779         Diag(Args[NumParams]->getLocStart(),
4780              MinArgs == NumParams
4781                  ? diag::err_typecheck_call_too_many_args
4782                  : diag::err_typecheck_call_too_many_args_at_most)
4783             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4784             << Fn->getSourceRange()
4785             << SourceRange(Args[NumParams]->getLocStart(),
4786                            Args.back()->getLocEnd());
4787 
4788       // Emit the location of the prototype.
4789       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4790         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4791           << FDecl;
4792 
4793       // This deletes the extra arguments.
4794       Call->setNumArgs(Context, NumParams);
4795       return true;
4796     }
4797   }
4798   SmallVector<Expr *, 8> AllArgs;
4799   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4800 
4801   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4802                                    Proto, 0, Args, AllArgs, CallType);
4803   if (Invalid)
4804     return true;
4805   unsigned TotalNumArgs = AllArgs.size();
4806   for (unsigned i = 0; i < TotalNumArgs; ++i)
4807     Call->setArg(i, AllArgs[i]);
4808 
4809   return false;
4810 }
4811 
4812 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4813                                   const FunctionProtoType *Proto,
4814                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4815                                   SmallVectorImpl<Expr *> &AllArgs,
4816                                   VariadicCallType CallType, bool AllowExplicit,
4817                                   bool IsListInitialization) {
4818   unsigned NumParams = Proto->getNumParams();
4819   bool Invalid = false;
4820   size_t ArgIx = 0;
4821   // Continue to check argument types (even if we have too few/many args).
4822   for (unsigned i = FirstParam; i < NumParams; i++) {
4823     QualType ProtoArgType = Proto->getParamType(i);
4824 
4825     Expr *Arg;
4826     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4827     if (ArgIx < Args.size()) {
4828       Arg = Args[ArgIx++];
4829 
4830       if (RequireCompleteType(Arg->getLocStart(),
4831                               ProtoArgType,
4832                               diag::err_call_incomplete_argument, Arg))
4833         return true;
4834 
4835       // Strip the unbridged-cast placeholder expression off, if applicable.
4836       bool CFAudited = false;
4837       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4838           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4839           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4840         Arg = stripARCUnbridgedCast(Arg);
4841       else if (getLangOpts().ObjCAutoRefCount &&
4842                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4843                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4844         CFAudited = true;
4845 
4846       if (Proto->getExtParameterInfo(i).isNoEscape())
4847         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4848           BE->getBlockDecl()->setDoesNotEscape();
4849 
4850       InitializedEntity Entity =
4851           Param ? InitializedEntity::InitializeParameter(Context, Param,
4852                                                          ProtoArgType)
4853                 : InitializedEntity::InitializeParameter(
4854                       Context, ProtoArgType, Proto->isParamConsumed(i));
4855 
4856       // Remember that parameter belongs to a CF audited API.
4857       if (CFAudited)
4858         Entity.setParameterCFAudited();
4859 
4860       ExprResult ArgE = PerformCopyInitialization(
4861           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4862       if (ArgE.isInvalid())
4863         return true;
4864 
4865       Arg = ArgE.getAs<Expr>();
4866     } else {
4867       assert(Param && "can't use default arguments without a known callee");
4868 
4869       ExprResult ArgExpr =
4870         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4871       if (ArgExpr.isInvalid())
4872         return true;
4873 
4874       Arg = ArgExpr.getAs<Expr>();
4875     }
4876 
4877     // Check for array bounds violations for each argument to the call. This
4878     // check only triggers warnings when the argument isn't a more complex Expr
4879     // with its own checking, such as a BinaryOperator.
4880     CheckArrayAccess(Arg);
4881 
4882     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4883     CheckStaticArrayArgument(CallLoc, Param, Arg);
4884 
4885     AllArgs.push_back(Arg);
4886   }
4887 
4888   // If this is a variadic call, handle args passed through "...".
4889   if (CallType != VariadicDoesNotApply) {
4890     // Assume that extern "C" functions with variadic arguments that
4891     // return __unknown_anytype aren't *really* variadic.
4892     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4893         FDecl->isExternC()) {
4894       for (Expr *A : Args.slice(ArgIx)) {
4895         QualType paramType; // ignored
4896         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4897         Invalid |= arg.isInvalid();
4898         AllArgs.push_back(arg.get());
4899       }
4900 
4901     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4902     } else {
4903       for (Expr *A : Args.slice(ArgIx)) {
4904         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4905         Invalid |= Arg.isInvalid();
4906         AllArgs.push_back(Arg.get());
4907       }
4908     }
4909 
4910     // Check for array bounds violations.
4911     for (Expr *A : Args.slice(ArgIx))
4912       CheckArrayAccess(A);
4913   }
4914   return Invalid;
4915 }
4916 
4917 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4918   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4919   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4920     TL = DTL.getOriginalLoc();
4921   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4922     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4923       << ATL.getLocalSourceRange();
4924 }
4925 
4926 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4927 /// array parameter, check that it is non-null, and that if it is formed by
4928 /// array-to-pointer decay, the underlying array is sufficiently large.
4929 ///
4930 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4931 /// array type derivation, then for each call to the function, the value of the
4932 /// corresponding actual argument shall provide access to the first element of
4933 /// an array with at least as many elements as specified by the size expression.
4934 void
4935 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4936                                ParmVarDecl *Param,
4937                                const Expr *ArgExpr) {
4938   // Static array parameters are not supported in C++.
4939   if (!Param || getLangOpts().CPlusPlus)
4940     return;
4941 
4942   QualType OrigTy = Param->getOriginalType();
4943 
4944   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4945   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4946     return;
4947 
4948   if (ArgExpr->isNullPointerConstant(Context,
4949                                      Expr::NPC_NeverValueDependent)) {
4950     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4951     DiagnoseCalleeStaticArrayParam(*this, Param);
4952     return;
4953   }
4954 
4955   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4956   if (!CAT)
4957     return;
4958 
4959   const ConstantArrayType *ArgCAT =
4960     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4961   if (!ArgCAT)
4962     return;
4963 
4964   if (ArgCAT->getSize().ult(CAT->getSize())) {
4965     Diag(CallLoc, diag::warn_static_array_too_small)
4966       << ArgExpr->getSourceRange()
4967       << (unsigned) ArgCAT->getSize().getZExtValue()
4968       << (unsigned) CAT->getSize().getZExtValue();
4969     DiagnoseCalleeStaticArrayParam(*this, Param);
4970   }
4971 }
4972 
4973 /// Given a function expression of unknown-any type, try to rebuild it
4974 /// to have a function type.
4975 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4976 
4977 /// Is the given type a placeholder that we need to lower out
4978 /// immediately during argument processing?
4979 static bool isPlaceholderToRemoveAsArg(QualType type) {
4980   // Placeholders are never sugared.
4981   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4982   if (!placeholder) return false;
4983 
4984   switch (placeholder->getKind()) {
4985   // Ignore all the non-placeholder types.
4986 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4987   case BuiltinType::Id:
4988 #include "clang/Basic/OpenCLImageTypes.def"
4989 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4990 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4991 #include "clang/AST/BuiltinTypes.def"
4992     return false;
4993 
4994   // We cannot lower out overload sets; they might validly be resolved
4995   // by the call machinery.
4996   case BuiltinType::Overload:
4997     return false;
4998 
4999   // Unbridged casts in ARC can be handled in some call positions and
5000   // should be left in place.
5001   case BuiltinType::ARCUnbridgedCast:
5002     return false;
5003 
5004   // Pseudo-objects should be converted as soon as possible.
5005   case BuiltinType::PseudoObject:
5006     return true;
5007 
5008   // The debugger mode could theoretically but currently does not try
5009   // to resolve unknown-typed arguments based on known parameter types.
5010   case BuiltinType::UnknownAny:
5011     return true;
5012 
5013   // These are always invalid as call arguments and should be reported.
5014   case BuiltinType::BoundMember:
5015   case BuiltinType::BuiltinFn:
5016   case BuiltinType::OMPArraySection:
5017     return true;
5018 
5019   }
5020   llvm_unreachable("bad builtin type kind");
5021 }
5022 
5023 /// Check an argument list for placeholders that we won't try to
5024 /// handle later.
5025 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5026   // Apply this processing to all the arguments at once instead of
5027   // dying at the first failure.
5028   bool hasInvalid = false;
5029   for (size_t i = 0, e = args.size(); i != e; i++) {
5030     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5031       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5032       if (result.isInvalid()) hasInvalid = true;
5033       else args[i] = result.get();
5034     } else if (hasInvalid) {
5035       (void)S.CorrectDelayedTyposInExpr(args[i]);
5036     }
5037   }
5038   return hasInvalid;
5039 }
5040 
5041 /// If a builtin function has a pointer argument with no explicit address
5042 /// space, then it should be able to accept a pointer to any address
5043 /// space as input.  In order to do this, we need to replace the
5044 /// standard builtin declaration with one that uses the same address space
5045 /// as the call.
5046 ///
5047 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5048 ///                  it does not contain any pointer arguments without
5049 ///                  an address space qualifer.  Otherwise the rewritten
5050 ///                  FunctionDecl is returned.
5051 /// TODO: Handle pointer return types.
5052 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5053                                                 const FunctionDecl *FDecl,
5054                                                 MultiExprArg ArgExprs) {
5055 
5056   QualType DeclType = FDecl->getType();
5057   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5058 
5059   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5060       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5061     return nullptr;
5062 
5063   bool NeedsNewDecl = false;
5064   unsigned i = 0;
5065   SmallVector<QualType, 8> OverloadParams;
5066 
5067   for (QualType ParamType : FT->param_types()) {
5068 
5069     // Convert array arguments to pointer to simplify type lookup.
5070     ExprResult ArgRes =
5071         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5072     if (ArgRes.isInvalid())
5073       return nullptr;
5074     Expr *Arg = ArgRes.get();
5075     QualType ArgType = Arg->getType();
5076     if (!ParamType->isPointerType() ||
5077         ParamType.getQualifiers().hasAddressSpace() ||
5078         !ArgType->isPointerType() ||
5079         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5080       OverloadParams.push_back(ParamType);
5081       continue;
5082     }
5083 
5084     NeedsNewDecl = true;
5085     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5086 
5087     QualType PointeeType = ParamType->getPointeeType();
5088     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5089     OverloadParams.push_back(Context.getPointerType(PointeeType));
5090   }
5091 
5092   if (!NeedsNewDecl)
5093     return nullptr;
5094 
5095   FunctionProtoType::ExtProtoInfo EPI;
5096   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5097                                                 OverloadParams, EPI);
5098   DeclContext *Parent = Context.getTranslationUnitDecl();
5099   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5100                                                     FDecl->getLocation(),
5101                                                     FDecl->getLocation(),
5102                                                     FDecl->getIdentifier(),
5103                                                     OverloadTy,
5104                                                     /*TInfo=*/nullptr,
5105                                                     SC_Extern, false,
5106                                                     /*hasPrototype=*/true);
5107   SmallVector<ParmVarDecl*, 16> Params;
5108   FT = cast<FunctionProtoType>(OverloadTy);
5109   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5110     QualType ParamType = FT->getParamType(i);
5111     ParmVarDecl *Parm =
5112         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5113                                 SourceLocation(), nullptr, ParamType,
5114                                 /*TInfo=*/nullptr, SC_None, nullptr);
5115     Parm->setScopeInfo(0, i);
5116     Params.push_back(Parm);
5117   }
5118   OverloadDecl->setParams(Params);
5119   return OverloadDecl;
5120 }
5121 
5122 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5123                                     FunctionDecl *Callee,
5124                                     MultiExprArg ArgExprs) {
5125   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5126   // similar attributes) really don't like it when functions are called with an
5127   // invalid number of args.
5128   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5129                          /*PartialOverloading=*/false) &&
5130       !Callee->isVariadic())
5131     return;
5132   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5133     return;
5134 
5135   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5136     S.Diag(Fn->getLocStart(),
5137            isa<CXXMethodDecl>(Callee)
5138                ? diag::err_ovl_no_viable_member_function_in_call
5139                : diag::err_ovl_no_viable_function_in_call)
5140         << Callee << Callee->getSourceRange();
5141     S.Diag(Callee->getLocation(),
5142            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5143         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5144     return;
5145   }
5146 }
5147 
5148 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5149     const UnresolvedMemberExpr *const UME, Sema &S) {
5150 
5151   const auto GetFunctionLevelDCIfCXXClass =
5152       [](Sema &S) -> const CXXRecordDecl * {
5153     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5154     if (!DC || !DC->getParent())
5155       return nullptr;
5156 
5157     // If the call to some member function was made from within a member
5158     // function body 'M' return return 'M's parent.
5159     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5160       return MD->getParent()->getCanonicalDecl();
5161     // else the call was made from within a default member initializer of a
5162     // class, so return the class.
5163     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5164       return RD->getCanonicalDecl();
5165     return nullptr;
5166   };
5167   // If our DeclContext is neither a member function nor a class (in the
5168   // case of a lambda in a default member initializer), we can't have an
5169   // enclosing 'this'.
5170 
5171   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5172   if (!CurParentClass)
5173     return false;
5174 
5175   // The naming class for implicit member functions call is the class in which
5176   // name lookup starts.
5177   const CXXRecordDecl *const NamingClass =
5178       UME->getNamingClass()->getCanonicalDecl();
5179   assert(NamingClass && "Must have naming class even for implicit access");
5180 
5181   // If the unresolved member functions were found in a 'naming class' that is
5182   // related (either the same or derived from) to the class that contains the
5183   // member function that itself contained the implicit member access.
5184 
5185   return CurParentClass == NamingClass ||
5186          CurParentClass->isDerivedFrom(NamingClass);
5187 }
5188 
5189 static void
5190 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5191     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5192 
5193   if (!UME)
5194     return;
5195 
5196   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5197   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5198   // already been captured, or if this is an implicit member function call (if
5199   // it isn't, an attempt to capture 'this' should already have been made).
5200   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5201       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5202     return;
5203 
5204   // Check if the naming class in which the unresolved members were found is
5205   // related (same as or is a base of) to the enclosing class.
5206 
5207   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5208     return;
5209 
5210 
5211   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5212   // If the enclosing function is not dependent, then this lambda is
5213   // capture ready, so if we can capture this, do so.
5214   if (!EnclosingFunctionCtx->isDependentContext()) {
5215     // If the current lambda and all enclosing lambdas can capture 'this' -
5216     // then go ahead and capture 'this' (since our unresolved overload set
5217     // contains at least one non-static member function).
5218     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5219       S.CheckCXXThisCapture(CallLoc);
5220   } else if (S.CurContext->isDependentContext()) {
5221     // ... since this is an implicit member reference, that might potentially
5222     // involve a 'this' capture, mark 'this' for potential capture in
5223     // enclosing lambdas.
5224     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5225       CurLSI->addPotentialThisCapture(CallLoc);
5226   }
5227 }
5228 
5229 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5230 /// This provides the location of the left/right parens and a list of comma
5231 /// locations.
5232 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5233                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5234                                Expr *ExecConfig, bool IsExecConfig) {
5235   // Since this might be a postfix expression, get rid of ParenListExprs.
5236   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5237   if (Result.isInvalid()) return ExprError();
5238   Fn = Result.get();
5239 
5240   if (checkArgsForPlaceholders(*this, ArgExprs))
5241     return ExprError();
5242 
5243   if (getLangOpts().CPlusPlus) {
5244     // If this is a pseudo-destructor expression, build the call immediately.
5245     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5246       if (!ArgExprs.empty()) {
5247         // Pseudo-destructor calls should not have any arguments.
5248         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5249             << FixItHint::CreateRemoval(
5250                    SourceRange(ArgExprs.front()->getLocStart(),
5251                                ArgExprs.back()->getLocEnd()));
5252       }
5253 
5254       return new (Context)
5255           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5256     }
5257     if (Fn->getType() == Context.PseudoObjectTy) {
5258       ExprResult result = CheckPlaceholderExpr(Fn);
5259       if (result.isInvalid()) return ExprError();
5260       Fn = result.get();
5261     }
5262 
5263     // Determine whether this is a dependent call inside a C++ template,
5264     // in which case we won't do any semantic analysis now.
5265     bool Dependent = false;
5266     if (Fn->isTypeDependent())
5267       Dependent = true;
5268     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5269       Dependent = true;
5270 
5271     if (Dependent) {
5272       if (ExecConfig) {
5273         return new (Context) CUDAKernelCallExpr(
5274             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5275             Context.DependentTy, VK_RValue, RParenLoc);
5276       } else {
5277 
5278        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5279             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5280             Fn->getLocStart());
5281 
5282         return new (Context) CallExpr(
5283             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5284       }
5285     }
5286 
5287     // Determine whether this is a call to an object (C++ [over.call.object]).
5288     if (Fn->getType()->isRecordType())
5289       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5290                                           RParenLoc);
5291 
5292     if (Fn->getType() == Context.UnknownAnyTy) {
5293       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5294       if (result.isInvalid()) return ExprError();
5295       Fn = result.get();
5296     }
5297 
5298     if (Fn->getType() == Context.BoundMemberTy) {
5299       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5300                                        RParenLoc);
5301     }
5302   }
5303 
5304   // Check for overloaded calls.  This can happen even in C due to extensions.
5305   if (Fn->getType() == Context.OverloadTy) {
5306     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5307 
5308     // We aren't supposed to apply this logic if there's an '&' involved.
5309     if (!find.HasFormOfMemberPointer) {
5310       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5311         return new (Context) CallExpr(
5312             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5313       OverloadExpr *ovl = find.Expression;
5314       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5315         return BuildOverloadedCallExpr(
5316             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5317             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5318       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5319                                        RParenLoc);
5320     }
5321   }
5322 
5323   // If we're directly calling a function, get the appropriate declaration.
5324   if (Fn->getType() == Context.UnknownAnyTy) {
5325     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5326     if (result.isInvalid()) return ExprError();
5327     Fn = result.get();
5328   }
5329 
5330   Expr *NakedFn = Fn->IgnoreParens();
5331 
5332   bool CallingNDeclIndirectly = false;
5333   NamedDecl *NDecl = nullptr;
5334   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5335     if (UnOp->getOpcode() == UO_AddrOf) {
5336       CallingNDeclIndirectly = true;
5337       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5338     }
5339   }
5340 
5341   if (isa<DeclRefExpr>(NakedFn)) {
5342     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5343 
5344     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5345     if (FDecl && FDecl->getBuiltinID()) {
5346       // Rewrite the function decl for this builtin by replacing parameters
5347       // with no explicit address space with the address space of the arguments
5348       // in ArgExprs.
5349       if ((FDecl =
5350                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5351         NDecl = FDecl;
5352         Fn = DeclRefExpr::Create(
5353             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5354             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5355       }
5356     }
5357   } else if (isa<MemberExpr>(NakedFn))
5358     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5359 
5360   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5361     if (CallingNDeclIndirectly &&
5362         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5363                                            Fn->getLocStart()))
5364       return ExprError();
5365 
5366     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5367       return ExprError();
5368 
5369     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5370   }
5371 
5372   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5373                                ExecConfig, IsExecConfig);
5374 }
5375 
5376 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5377 ///
5378 /// __builtin_astype( value, dst type )
5379 ///
5380 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5381                                  SourceLocation BuiltinLoc,
5382                                  SourceLocation RParenLoc) {
5383   ExprValueKind VK = VK_RValue;
5384   ExprObjectKind OK = OK_Ordinary;
5385   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5386   QualType SrcTy = E->getType();
5387   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5388     return ExprError(Diag(BuiltinLoc,
5389                           diag::err_invalid_astype_of_different_size)
5390                      << DstTy
5391                      << SrcTy
5392                      << E->getSourceRange());
5393   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5394 }
5395 
5396 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5397 /// provided arguments.
5398 ///
5399 /// __builtin_convertvector( value, dst type )
5400 ///
5401 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5402                                         SourceLocation BuiltinLoc,
5403                                         SourceLocation RParenLoc) {
5404   TypeSourceInfo *TInfo;
5405   GetTypeFromParser(ParsedDestTy, &TInfo);
5406   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5407 }
5408 
5409 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5410 /// i.e. an expression not of \p OverloadTy.  The expression should
5411 /// unary-convert to an expression of function-pointer or
5412 /// block-pointer type.
5413 ///
5414 /// \param NDecl the declaration being called, if available
5415 ExprResult
5416 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5417                             SourceLocation LParenLoc,
5418                             ArrayRef<Expr *> Args,
5419                             SourceLocation RParenLoc,
5420                             Expr *Config, bool IsExecConfig) {
5421   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5422   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5423 
5424   // Functions with 'interrupt' attribute cannot be called directly.
5425   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5426     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5427     return ExprError();
5428   }
5429 
5430   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5431   // so there's some risk when calling out to non-interrupt handler functions
5432   // that the callee might not preserve them. This is easy to diagnose here,
5433   // but can be very challenging to debug.
5434   if (auto *Caller = getCurFunctionDecl())
5435     if (Caller->hasAttr<ARMInterruptAttr>()) {
5436       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5437       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5438         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5439     }
5440 
5441   // Promote the function operand.
5442   // We special-case function promotion here because we only allow promoting
5443   // builtin functions to function pointers in the callee of a call.
5444   ExprResult Result;
5445   if (BuiltinID &&
5446       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5447     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5448                                CK_BuiltinFnToFnPtr).get();
5449   } else {
5450     Result = CallExprUnaryConversions(Fn);
5451   }
5452   if (Result.isInvalid())
5453     return ExprError();
5454   Fn = Result.get();
5455 
5456   // Make the call expr early, before semantic checks.  This guarantees cleanup
5457   // of arguments and function on error.
5458   CallExpr *TheCall;
5459   if (Config)
5460     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5461                                                cast<CallExpr>(Config), Args,
5462                                                Context.BoolTy, VK_RValue,
5463                                                RParenLoc);
5464   else
5465     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5466                                      VK_RValue, RParenLoc);
5467 
5468   if (!getLangOpts().CPlusPlus) {
5469     // C cannot always handle TypoExpr nodes in builtin calls and direct
5470     // function calls as their argument checking don't necessarily handle
5471     // dependent types properly, so make sure any TypoExprs have been
5472     // dealt with.
5473     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5474     if (!Result.isUsable()) return ExprError();
5475     TheCall = dyn_cast<CallExpr>(Result.get());
5476     if (!TheCall) return Result;
5477     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5478   }
5479 
5480   // Bail out early if calling a builtin with custom typechecking.
5481   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5482     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5483 
5484  retry:
5485   const FunctionType *FuncT;
5486   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5487     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5488     // have type pointer to function".
5489     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5490     if (!FuncT)
5491       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5492                          << Fn->getType() << Fn->getSourceRange());
5493   } else if (const BlockPointerType *BPT =
5494                Fn->getType()->getAs<BlockPointerType>()) {
5495     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5496   } else {
5497     // Handle calls to expressions of unknown-any type.
5498     if (Fn->getType() == Context.UnknownAnyTy) {
5499       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5500       if (rewrite.isInvalid()) return ExprError();
5501       Fn = rewrite.get();
5502       TheCall->setCallee(Fn);
5503       goto retry;
5504     }
5505 
5506     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5507       << Fn->getType() << Fn->getSourceRange());
5508   }
5509 
5510   if (getLangOpts().CUDA) {
5511     if (Config) {
5512       // CUDA: Kernel calls must be to global functions
5513       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5514         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5515             << FDecl << Fn->getSourceRange());
5516 
5517       // CUDA: Kernel function must have 'void' return type
5518       if (!FuncT->getReturnType()->isVoidType())
5519         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5520             << Fn->getType() << Fn->getSourceRange());
5521     } else {
5522       // CUDA: Calls to global functions must be configured
5523       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5524         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5525             << FDecl << Fn->getSourceRange());
5526     }
5527   }
5528 
5529   // Check for a valid return type
5530   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5531                           FDecl))
5532     return ExprError();
5533 
5534   // We know the result type of the call, set it.
5535   TheCall->setType(FuncT->getCallResultType(Context));
5536   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5537 
5538   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5539   if (Proto) {
5540     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5541                                 IsExecConfig))
5542       return ExprError();
5543   } else {
5544     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5545 
5546     if (FDecl) {
5547       // Check if we have too few/too many template arguments, based
5548       // on our knowledge of the function definition.
5549       const FunctionDecl *Def = nullptr;
5550       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5551         Proto = Def->getType()->getAs<FunctionProtoType>();
5552        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5553           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5554           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5555       }
5556 
5557       // If the function we're calling isn't a function prototype, but we have
5558       // a function prototype from a prior declaratiom, use that prototype.
5559       if (!FDecl->hasPrototype())
5560         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5561     }
5562 
5563     // Promote the arguments (C99 6.5.2.2p6).
5564     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5565       Expr *Arg = Args[i];
5566 
5567       if (Proto && i < Proto->getNumParams()) {
5568         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5569             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5570         ExprResult ArgE =
5571             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5572         if (ArgE.isInvalid())
5573           return true;
5574 
5575         Arg = ArgE.getAs<Expr>();
5576 
5577       } else {
5578         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5579 
5580         if (ArgE.isInvalid())
5581           return true;
5582 
5583         Arg = ArgE.getAs<Expr>();
5584       }
5585 
5586       if (RequireCompleteType(Arg->getLocStart(),
5587                               Arg->getType(),
5588                               diag::err_call_incomplete_argument, Arg))
5589         return ExprError();
5590 
5591       TheCall->setArg(i, Arg);
5592     }
5593   }
5594 
5595   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5596     if (!Method->isStatic())
5597       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5598         << Fn->getSourceRange());
5599 
5600   // Check for sentinels
5601   if (NDecl)
5602     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5603 
5604   // Do special checking on direct calls to functions.
5605   if (FDecl) {
5606     if (CheckFunctionCall(FDecl, TheCall, Proto))
5607       return ExprError();
5608 
5609     if (BuiltinID)
5610       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5611   } else if (NDecl) {
5612     if (CheckPointerCall(NDecl, TheCall, Proto))
5613       return ExprError();
5614   } else {
5615     if (CheckOtherCall(TheCall, Proto))
5616       return ExprError();
5617   }
5618 
5619   return MaybeBindToTemporary(TheCall);
5620 }
5621 
5622 ExprResult
5623 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5624                            SourceLocation RParenLoc, Expr *InitExpr) {
5625   assert(Ty && "ActOnCompoundLiteral(): missing type");
5626   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5627 
5628   TypeSourceInfo *TInfo;
5629   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5630   if (!TInfo)
5631     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5632 
5633   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5634 }
5635 
5636 ExprResult
5637 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5638                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5639   QualType literalType = TInfo->getType();
5640 
5641   if (literalType->isArrayType()) {
5642     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5643           diag::err_illegal_decl_array_incomplete_type,
5644           SourceRange(LParenLoc,
5645                       LiteralExpr->getSourceRange().getEnd())))
5646       return ExprError();
5647     if (literalType->isVariableArrayType())
5648       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5649         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5650   } else if (!literalType->isDependentType() &&
5651              RequireCompleteType(LParenLoc, literalType,
5652                diag::err_typecheck_decl_incomplete_type,
5653                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5654     return ExprError();
5655 
5656   InitializedEntity Entity
5657     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5658   InitializationKind Kind
5659     = InitializationKind::CreateCStyleCast(LParenLoc,
5660                                            SourceRange(LParenLoc, RParenLoc),
5661                                            /*InitList=*/true);
5662   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5663   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5664                                       &literalType);
5665   if (Result.isInvalid())
5666     return ExprError();
5667   LiteralExpr = Result.get();
5668 
5669   bool isFileScope = !CurContext->isFunctionOrMethod();
5670   if (isFileScope &&
5671       !LiteralExpr->isTypeDependent() &&
5672       !LiteralExpr->isValueDependent() &&
5673       !literalType->isDependentType()) { // 6.5.2.5p3
5674     if (CheckForConstantInitializer(LiteralExpr, literalType))
5675       return ExprError();
5676   }
5677 
5678   // In C, compound literals are l-values for some reason.
5679   // For GCC compatibility, in C++, file-scope array compound literals with
5680   // constant initializers are also l-values, and compound literals are
5681   // otherwise prvalues.
5682   //
5683   // (GCC also treats C++ list-initialized file-scope array prvalues with
5684   // constant initializers as l-values, but that's non-conforming, so we don't
5685   // follow it there.)
5686   //
5687   // FIXME: It would be better to handle the lvalue cases as materializing and
5688   // lifetime-extending a temporary object, but our materialized temporaries
5689   // representation only supports lifetime extension from a variable, not "out
5690   // of thin air".
5691   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5692   // is bound to the result of applying array-to-pointer decay to the compound
5693   // literal.
5694   // FIXME: GCC supports compound literals of reference type, which should
5695   // obviously have a value kind derived from the kind of reference involved.
5696   ExprValueKind VK =
5697       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5698           ? VK_RValue
5699           : VK_LValue;
5700 
5701   return MaybeBindToTemporary(
5702       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5703                                         VK, LiteralExpr, isFileScope));
5704 }
5705 
5706 ExprResult
5707 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5708                     SourceLocation RBraceLoc) {
5709   // Immediately handle non-overload placeholders.  Overloads can be
5710   // resolved contextually, but everything else here can't.
5711   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5712     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5713       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5714 
5715       // Ignore failures; dropping the entire initializer list because
5716       // of one failure would be terrible for indexing/etc.
5717       if (result.isInvalid()) continue;
5718 
5719       InitArgList[I] = result.get();
5720     }
5721   }
5722 
5723   // Semantic analysis for initializers is done by ActOnDeclarator() and
5724   // CheckInitializer() - it requires knowledge of the object being initialized.
5725 
5726   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5727                                                RBraceLoc);
5728   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5729   return E;
5730 }
5731 
5732 /// Do an explicit extend of the given block pointer if we're in ARC.
5733 void Sema::maybeExtendBlockObject(ExprResult &E) {
5734   assert(E.get()->getType()->isBlockPointerType());
5735   assert(E.get()->isRValue());
5736 
5737   // Only do this in an r-value context.
5738   if (!getLangOpts().ObjCAutoRefCount) return;
5739 
5740   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5741                                CK_ARCExtendBlockObject, E.get(),
5742                                /*base path*/ nullptr, VK_RValue);
5743   Cleanup.setExprNeedsCleanups(true);
5744 }
5745 
5746 /// Prepare a conversion of the given expression to an ObjC object
5747 /// pointer type.
5748 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5749   QualType type = E.get()->getType();
5750   if (type->isObjCObjectPointerType()) {
5751     return CK_BitCast;
5752   } else if (type->isBlockPointerType()) {
5753     maybeExtendBlockObject(E);
5754     return CK_BlockPointerToObjCPointerCast;
5755   } else {
5756     assert(type->isPointerType());
5757     return CK_CPointerToObjCPointerCast;
5758   }
5759 }
5760 
5761 /// Prepares for a scalar cast, performing all the necessary stages
5762 /// except the final cast and returning the kind required.
5763 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5764   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5765   // Also, callers should have filtered out the invalid cases with
5766   // pointers.  Everything else should be possible.
5767 
5768   QualType SrcTy = Src.get()->getType();
5769   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5770     return CK_NoOp;
5771 
5772   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5773   case Type::STK_MemberPointer:
5774     llvm_unreachable("member pointer type in C");
5775 
5776   case Type::STK_CPointer:
5777   case Type::STK_BlockPointer:
5778   case Type::STK_ObjCObjectPointer:
5779     switch (DestTy->getScalarTypeKind()) {
5780     case Type::STK_CPointer: {
5781       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5782       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5783       if (SrcAS != DestAS)
5784         return CK_AddressSpaceConversion;
5785       return CK_BitCast;
5786     }
5787     case Type::STK_BlockPointer:
5788       return (SrcKind == Type::STK_BlockPointer
5789                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5790     case Type::STK_ObjCObjectPointer:
5791       if (SrcKind == Type::STK_ObjCObjectPointer)
5792         return CK_BitCast;
5793       if (SrcKind == Type::STK_CPointer)
5794         return CK_CPointerToObjCPointerCast;
5795       maybeExtendBlockObject(Src);
5796       return CK_BlockPointerToObjCPointerCast;
5797     case Type::STK_Bool:
5798       return CK_PointerToBoolean;
5799     case Type::STK_Integral:
5800       return CK_PointerToIntegral;
5801     case Type::STK_Floating:
5802     case Type::STK_FloatingComplex:
5803     case Type::STK_IntegralComplex:
5804     case Type::STK_MemberPointer:
5805       llvm_unreachable("illegal cast from pointer");
5806     }
5807     llvm_unreachable("Should have returned before this");
5808 
5809   case Type::STK_Bool: // casting from bool is like casting from an integer
5810   case Type::STK_Integral:
5811     switch (DestTy->getScalarTypeKind()) {
5812     case Type::STK_CPointer:
5813     case Type::STK_ObjCObjectPointer:
5814     case Type::STK_BlockPointer:
5815       if (Src.get()->isNullPointerConstant(Context,
5816                                            Expr::NPC_ValueDependentIsNull))
5817         return CK_NullToPointer;
5818       return CK_IntegralToPointer;
5819     case Type::STK_Bool:
5820       return CK_IntegralToBoolean;
5821     case Type::STK_Integral:
5822       return CK_IntegralCast;
5823     case Type::STK_Floating:
5824       return CK_IntegralToFloating;
5825     case Type::STK_IntegralComplex:
5826       Src = ImpCastExprToType(Src.get(),
5827                       DestTy->castAs<ComplexType>()->getElementType(),
5828                       CK_IntegralCast);
5829       return CK_IntegralRealToComplex;
5830     case Type::STK_FloatingComplex:
5831       Src = ImpCastExprToType(Src.get(),
5832                       DestTy->castAs<ComplexType>()->getElementType(),
5833                       CK_IntegralToFloating);
5834       return CK_FloatingRealToComplex;
5835     case Type::STK_MemberPointer:
5836       llvm_unreachable("member pointer type in C");
5837     }
5838     llvm_unreachable("Should have returned before this");
5839 
5840   case Type::STK_Floating:
5841     switch (DestTy->getScalarTypeKind()) {
5842     case Type::STK_Floating:
5843       return CK_FloatingCast;
5844     case Type::STK_Bool:
5845       return CK_FloatingToBoolean;
5846     case Type::STK_Integral:
5847       return CK_FloatingToIntegral;
5848     case Type::STK_FloatingComplex:
5849       Src = ImpCastExprToType(Src.get(),
5850                               DestTy->castAs<ComplexType>()->getElementType(),
5851                               CK_FloatingCast);
5852       return CK_FloatingRealToComplex;
5853     case Type::STK_IntegralComplex:
5854       Src = ImpCastExprToType(Src.get(),
5855                               DestTy->castAs<ComplexType>()->getElementType(),
5856                               CK_FloatingToIntegral);
5857       return CK_IntegralRealToComplex;
5858     case Type::STK_CPointer:
5859     case Type::STK_ObjCObjectPointer:
5860     case Type::STK_BlockPointer:
5861       llvm_unreachable("valid float->pointer cast?");
5862     case Type::STK_MemberPointer:
5863       llvm_unreachable("member pointer type in C");
5864     }
5865     llvm_unreachable("Should have returned before this");
5866 
5867   case Type::STK_FloatingComplex:
5868     switch (DestTy->getScalarTypeKind()) {
5869     case Type::STK_FloatingComplex:
5870       return CK_FloatingComplexCast;
5871     case Type::STK_IntegralComplex:
5872       return CK_FloatingComplexToIntegralComplex;
5873     case Type::STK_Floating: {
5874       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5875       if (Context.hasSameType(ET, DestTy))
5876         return CK_FloatingComplexToReal;
5877       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5878       return CK_FloatingCast;
5879     }
5880     case Type::STK_Bool:
5881       return CK_FloatingComplexToBoolean;
5882     case Type::STK_Integral:
5883       Src = ImpCastExprToType(Src.get(),
5884                               SrcTy->castAs<ComplexType>()->getElementType(),
5885                               CK_FloatingComplexToReal);
5886       return CK_FloatingToIntegral;
5887     case Type::STK_CPointer:
5888     case Type::STK_ObjCObjectPointer:
5889     case Type::STK_BlockPointer:
5890       llvm_unreachable("valid complex float->pointer cast?");
5891     case Type::STK_MemberPointer:
5892       llvm_unreachable("member pointer type in C");
5893     }
5894     llvm_unreachable("Should have returned before this");
5895 
5896   case Type::STK_IntegralComplex:
5897     switch (DestTy->getScalarTypeKind()) {
5898     case Type::STK_FloatingComplex:
5899       return CK_IntegralComplexToFloatingComplex;
5900     case Type::STK_IntegralComplex:
5901       return CK_IntegralComplexCast;
5902     case Type::STK_Integral: {
5903       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5904       if (Context.hasSameType(ET, DestTy))
5905         return CK_IntegralComplexToReal;
5906       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5907       return CK_IntegralCast;
5908     }
5909     case Type::STK_Bool:
5910       return CK_IntegralComplexToBoolean;
5911     case Type::STK_Floating:
5912       Src = ImpCastExprToType(Src.get(),
5913                               SrcTy->castAs<ComplexType>()->getElementType(),
5914                               CK_IntegralComplexToReal);
5915       return CK_IntegralToFloating;
5916     case Type::STK_CPointer:
5917     case Type::STK_ObjCObjectPointer:
5918     case Type::STK_BlockPointer:
5919       llvm_unreachable("valid complex int->pointer cast?");
5920     case Type::STK_MemberPointer:
5921       llvm_unreachable("member pointer type in C");
5922     }
5923     llvm_unreachable("Should have returned before this");
5924   }
5925 
5926   llvm_unreachable("Unhandled scalar cast");
5927 }
5928 
5929 static bool breakDownVectorType(QualType type, uint64_t &len,
5930                                 QualType &eltType) {
5931   // Vectors are simple.
5932   if (const VectorType *vecType = type->getAs<VectorType>()) {
5933     len = vecType->getNumElements();
5934     eltType = vecType->getElementType();
5935     assert(eltType->isScalarType());
5936     return true;
5937   }
5938 
5939   // We allow lax conversion to and from non-vector types, but only if
5940   // they're real types (i.e. non-complex, non-pointer scalar types).
5941   if (!type->isRealType()) return false;
5942 
5943   len = 1;
5944   eltType = type;
5945   return true;
5946 }
5947 
5948 /// Are the two types lax-compatible vector types?  That is, given
5949 /// that one of them is a vector, do they have equal storage sizes,
5950 /// where the storage size is the number of elements times the element
5951 /// size?
5952 ///
5953 /// This will also return false if either of the types is neither a
5954 /// vector nor a real type.
5955 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5956   assert(destTy->isVectorType() || srcTy->isVectorType());
5957 
5958   // Disallow lax conversions between scalars and ExtVectors (these
5959   // conversions are allowed for other vector types because common headers
5960   // depend on them).  Most scalar OP ExtVector cases are handled by the
5961   // splat path anyway, which does what we want (convert, not bitcast).
5962   // What this rules out for ExtVectors is crazy things like char4*float.
5963   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5964   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5965 
5966   uint64_t srcLen, destLen;
5967   QualType srcEltTy, destEltTy;
5968   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5969   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5970 
5971   // ASTContext::getTypeSize will return the size rounded up to a
5972   // power of 2, so instead of using that, we need to use the raw
5973   // element size multiplied by the element count.
5974   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5975   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5976 
5977   return (srcLen * srcEltSize == destLen * destEltSize);
5978 }
5979 
5980 /// Is this a legal conversion between two types, one of which is
5981 /// known to be a vector type?
5982 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5983   assert(destTy->isVectorType() || srcTy->isVectorType());
5984 
5985   if (!Context.getLangOpts().LaxVectorConversions)
5986     return false;
5987   return areLaxCompatibleVectorTypes(srcTy, destTy);
5988 }
5989 
5990 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5991                            CastKind &Kind) {
5992   assert(VectorTy->isVectorType() && "Not a vector type!");
5993 
5994   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5995     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5996       return Diag(R.getBegin(),
5997                   Ty->isVectorType() ?
5998                   diag::err_invalid_conversion_between_vectors :
5999                   diag::err_invalid_conversion_between_vector_and_integer)
6000         << VectorTy << Ty << R;
6001   } else
6002     return Diag(R.getBegin(),
6003                 diag::err_invalid_conversion_between_vector_and_scalar)
6004       << VectorTy << Ty << R;
6005 
6006   Kind = CK_BitCast;
6007   return false;
6008 }
6009 
6010 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6011   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6012 
6013   if (DestElemTy == SplattedExpr->getType())
6014     return SplattedExpr;
6015 
6016   assert(DestElemTy->isFloatingType() ||
6017          DestElemTy->isIntegralOrEnumerationType());
6018 
6019   CastKind CK;
6020   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6021     // OpenCL requires that we convert `true` boolean expressions to -1, but
6022     // only when splatting vectors.
6023     if (DestElemTy->isFloatingType()) {
6024       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6025       // in two steps: boolean to signed integral, then to floating.
6026       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6027                                                  CK_BooleanToSignedIntegral);
6028       SplattedExpr = CastExprRes.get();
6029       CK = CK_IntegralToFloating;
6030     } else {
6031       CK = CK_BooleanToSignedIntegral;
6032     }
6033   } else {
6034     ExprResult CastExprRes = SplattedExpr;
6035     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6036     if (CastExprRes.isInvalid())
6037       return ExprError();
6038     SplattedExpr = CastExprRes.get();
6039   }
6040   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6041 }
6042 
6043 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6044                                     Expr *CastExpr, CastKind &Kind) {
6045   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6046 
6047   QualType SrcTy = CastExpr->getType();
6048 
6049   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6050   // an ExtVectorType.
6051   // In OpenCL, casts between vectors of different types are not allowed.
6052   // (See OpenCL 6.2).
6053   if (SrcTy->isVectorType()) {
6054     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6055         (getLangOpts().OpenCL &&
6056          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6057       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6058         << DestTy << SrcTy << R;
6059       return ExprError();
6060     }
6061     Kind = CK_BitCast;
6062     return CastExpr;
6063   }
6064 
6065   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6066   // conversion will take place first from scalar to elt type, and then
6067   // splat from elt type to vector.
6068   if (SrcTy->isPointerType())
6069     return Diag(R.getBegin(),
6070                 diag::err_invalid_conversion_between_vector_and_scalar)
6071       << DestTy << SrcTy << R;
6072 
6073   Kind = CK_VectorSplat;
6074   return prepareVectorSplat(DestTy, CastExpr);
6075 }
6076 
6077 ExprResult
6078 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6079                     Declarator &D, ParsedType &Ty,
6080                     SourceLocation RParenLoc, Expr *CastExpr) {
6081   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6082          "ActOnCastExpr(): missing type or expr");
6083 
6084   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6085   if (D.isInvalidType())
6086     return ExprError();
6087 
6088   if (getLangOpts().CPlusPlus) {
6089     // Check that there are no default arguments (C++ only).
6090     CheckExtraCXXDefaultArguments(D);
6091   } else {
6092     // Make sure any TypoExprs have been dealt with.
6093     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6094     if (!Res.isUsable())
6095       return ExprError();
6096     CastExpr = Res.get();
6097   }
6098 
6099   checkUnusedDeclAttributes(D);
6100 
6101   QualType castType = castTInfo->getType();
6102   Ty = CreateParsedType(castType, castTInfo);
6103 
6104   bool isVectorLiteral = false;
6105 
6106   // Check for an altivec or OpenCL literal,
6107   // i.e. all the elements are integer constants.
6108   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6109   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6110   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6111        && castType->isVectorType() && (PE || PLE)) {
6112     if (PLE && PLE->getNumExprs() == 0) {
6113       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6114       return ExprError();
6115     }
6116     if (PE || PLE->getNumExprs() == 1) {
6117       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6118       if (!E->getType()->isVectorType())
6119         isVectorLiteral = true;
6120     }
6121     else
6122       isVectorLiteral = true;
6123   }
6124 
6125   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6126   // then handle it as such.
6127   if (isVectorLiteral)
6128     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6129 
6130   // If the Expr being casted is a ParenListExpr, handle it specially.
6131   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6132   // sequence of BinOp comma operators.
6133   if (isa<ParenListExpr>(CastExpr)) {
6134     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6135     if (Result.isInvalid()) return ExprError();
6136     CastExpr = Result.get();
6137   }
6138 
6139   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6140       !getSourceManager().isInSystemMacro(LParenLoc))
6141     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6142 
6143   CheckTollFreeBridgeCast(castType, CastExpr);
6144 
6145   CheckObjCBridgeRelatedCast(castType, CastExpr);
6146 
6147   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6148 
6149   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6150 }
6151 
6152 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6153                                     SourceLocation RParenLoc, Expr *E,
6154                                     TypeSourceInfo *TInfo) {
6155   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6156          "Expected paren or paren list expression");
6157 
6158   Expr **exprs;
6159   unsigned numExprs;
6160   Expr *subExpr;
6161   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6162   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6163     LiteralLParenLoc = PE->getLParenLoc();
6164     LiteralRParenLoc = PE->getRParenLoc();
6165     exprs = PE->getExprs();
6166     numExprs = PE->getNumExprs();
6167   } else { // isa<ParenExpr> by assertion at function entrance
6168     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6169     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6170     subExpr = cast<ParenExpr>(E)->getSubExpr();
6171     exprs = &subExpr;
6172     numExprs = 1;
6173   }
6174 
6175   QualType Ty = TInfo->getType();
6176   assert(Ty->isVectorType() && "Expected vector type");
6177 
6178   SmallVector<Expr *, 8> initExprs;
6179   const VectorType *VTy = Ty->getAs<VectorType>();
6180   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6181 
6182   // '(...)' form of vector initialization in AltiVec: the number of
6183   // initializers must be one or must match the size of the vector.
6184   // If a single value is specified in the initializer then it will be
6185   // replicated to all the components of the vector
6186   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6187     // The number of initializers must be one or must match the size of the
6188     // vector. If a single value is specified in the initializer then it will
6189     // be replicated to all the components of the vector
6190     if (numExprs == 1) {
6191       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6192       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6193       if (Literal.isInvalid())
6194         return ExprError();
6195       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6196                                   PrepareScalarCast(Literal, ElemTy));
6197       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6198     }
6199     else if (numExprs < numElems) {
6200       Diag(E->getExprLoc(),
6201            diag::err_incorrect_number_of_vector_initializers);
6202       return ExprError();
6203     }
6204     else
6205       initExprs.append(exprs, exprs + numExprs);
6206   }
6207   else {
6208     // For OpenCL, when the number of initializers is a single value,
6209     // it will be replicated to all components of the vector.
6210     if (getLangOpts().OpenCL &&
6211         VTy->getVectorKind() == VectorType::GenericVector &&
6212         numExprs == 1) {
6213         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6214         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6215         if (Literal.isInvalid())
6216           return ExprError();
6217         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6218                                     PrepareScalarCast(Literal, ElemTy));
6219         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6220     }
6221 
6222     initExprs.append(exprs, exprs + numExprs);
6223   }
6224   // FIXME: This means that pretty-printing the final AST will produce curly
6225   // braces instead of the original commas.
6226   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6227                                                    initExprs, LiteralRParenLoc);
6228   initE->setType(Ty);
6229   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6230 }
6231 
6232 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6233 /// the ParenListExpr into a sequence of comma binary operators.
6234 ExprResult
6235 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6236   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6237   if (!E)
6238     return OrigExpr;
6239 
6240   ExprResult Result(E->getExpr(0));
6241 
6242   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6243     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6244                         E->getExpr(i));
6245 
6246   if (Result.isInvalid()) return ExprError();
6247 
6248   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6249 }
6250 
6251 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6252                                     SourceLocation R,
6253                                     MultiExprArg Val) {
6254   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6255   return expr;
6256 }
6257 
6258 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6259 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6260 /// emitted.
6261 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6262                                       SourceLocation QuestionLoc) {
6263   Expr *NullExpr = LHSExpr;
6264   Expr *NonPointerExpr = RHSExpr;
6265   Expr::NullPointerConstantKind NullKind =
6266       NullExpr->isNullPointerConstant(Context,
6267                                       Expr::NPC_ValueDependentIsNotNull);
6268 
6269   if (NullKind == Expr::NPCK_NotNull) {
6270     NullExpr = RHSExpr;
6271     NonPointerExpr = LHSExpr;
6272     NullKind =
6273         NullExpr->isNullPointerConstant(Context,
6274                                         Expr::NPC_ValueDependentIsNotNull);
6275   }
6276 
6277   if (NullKind == Expr::NPCK_NotNull)
6278     return false;
6279 
6280   if (NullKind == Expr::NPCK_ZeroExpression)
6281     return false;
6282 
6283   if (NullKind == Expr::NPCK_ZeroLiteral) {
6284     // In this case, check to make sure that we got here from a "NULL"
6285     // string in the source code.
6286     NullExpr = NullExpr->IgnoreParenImpCasts();
6287     SourceLocation loc = NullExpr->getExprLoc();
6288     if (!findMacroSpelling(loc, "NULL"))
6289       return false;
6290   }
6291 
6292   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6293   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6294       << NonPointerExpr->getType() << DiagType
6295       << NonPointerExpr->getSourceRange();
6296   return true;
6297 }
6298 
6299 /// \brief Return false if the condition expression is valid, true otherwise.
6300 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6301   QualType CondTy = Cond->getType();
6302 
6303   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6304   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6305     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6306       << CondTy << Cond->getSourceRange();
6307     return true;
6308   }
6309 
6310   // C99 6.5.15p2
6311   if (CondTy->isScalarType()) return false;
6312 
6313   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6314     << CondTy << Cond->getSourceRange();
6315   return true;
6316 }
6317 
6318 /// \brief Handle when one or both operands are void type.
6319 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6320                                          ExprResult &RHS) {
6321     Expr *LHSExpr = LHS.get();
6322     Expr *RHSExpr = RHS.get();
6323 
6324     if (!LHSExpr->getType()->isVoidType())
6325       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6326         << RHSExpr->getSourceRange();
6327     if (!RHSExpr->getType()->isVoidType())
6328       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6329         << LHSExpr->getSourceRange();
6330     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6331     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6332     return S.Context.VoidTy;
6333 }
6334 
6335 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6336 /// true otherwise.
6337 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6338                                         QualType PointerTy) {
6339   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6340       !NullExpr.get()->isNullPointerConstant(S.Context,
6341                                             Expr::NPC_ValueDependentIsNull))
6342     return true;
6343 
6344   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6345   return false;
6346 }
6347 
6348 /// \brief Checks compatibility between two pointers and return the resulting
6349 /// type.
6350 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6351                                                      ExprResult &RHS,
6352                                                      SourceLocation Loc) {
6353   QualType LHSTy = LHS.get()->getType();
6354   QualType RHSTy = RHS.get()->getType();
6355 
6356   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6357     // Two identical pointers types are always compatible.
6358     return LHSTy;
6359   }
6360 
6361   QualType lhptee, rhptee;
6362 
6363   // Get the pointee types.
6364   bool IsBlockPointer = false;
6365   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6366     lhptee = LHSBTy->getPointeeType();
6367     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6368     IsBlockPointer = true;
6369   } else {
6370     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6371     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6372   }
6373 
6374   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6375   // differently qualified versions of compatible types, the result type is
6376   // a pointer to an appropriately qualified version of the composite
6377   // type.
6378 
6379   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6380   // clause doesn't make sense for our extensions. E.g. address space 2 should
6381   // be incompatible with address space 3: they may live on different devices or
6382   // anything.
6383   Qualifiers lhQual = lhptee.getQualifiers();
6384   Qualifiers rhQual = rhptee.getQualifiers();
6385 
6386   LangAS ResultAddrSpace = LangAS::Default;
6387   LangAS LAddrSpace = lhQual.getAddressSpace();
6388   LangAS RAddrSpace = rhQual.getAddressSpace();
6389   if (S.getLangOpts().OpenCL) {
6390     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6391     // spaces is disallowed.
6392     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6393       ResultAddrSpace = LAddrSpace;
6394     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6395       ResultAddrSpace = RAddrSpace;
6396     else {
6397       S.Diag(Loc,
6398              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6399           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6400           << RHS.get()->getSourceRange();
6401       return QualType();
6402     }
6403   }
6404 
6405   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6406   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6407   lhQual.removeCVRQualifiers();
6408   rhQual.removeCVRQualifiers();
6409 
6410   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6411   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6412   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6413   // qual types are compatible iff
6414   //  * corresponded types are compatible
6415   //  * CVR qualifiers are equal
6416   //  * address spaces are equal
6417   // Thus for conditional operator we merge CVR and address space unqualified
6418   // pointees and if there is a composite type we return a pointer to it with
6419   // merged qualifiers.
6420   if (S.getLangOpts().OpenCL) {
6421     LHSCastKind = LAddrSpace == ResultAddrSpace
6422                       ? CK_BitCast
6423                       : CK_AddressSpaceConversion;
6424     RHSCastKind = RAddrSpace == ResultAddrSpace
6425                       ? CK_BitCast
6426                       : CK_AddressSpaceConversion;
6427     lhQual.removeAddressSpace();
6428     rhQual.removeAddressSpace();
6429   }
6430 
6431   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6432   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6433 
6434   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6435 
6436   if (CompositeTy.isNull()) {
6437     // In this situation, we assume void* type. No especially good
6438     // reason, but this is what gcc does, and we do have to pick
6439     // to get a consistent AST.
6440     QualType incompatTy;
6441     incompatTy = S.Context.getPointerType(
6442         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6443     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6444     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6445     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6446     // for casts between types with incompatible address space qualifiers.
6447     // For the following code the compiler produces casts between global and
6448     // local address spaces of the corresponded innermost pointees:
6449     // local int *global *a;
6450     // global int *global *b;
6451     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6452     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6453         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6454         << RHS.get()->getSourceRange();
6455     return incompatTy;
6456   }
6457 
6458   // The pointer types are compatible.
6459   // In case of OpenCL ResultTy should have the address space qualifier
6460   // which is a superset of address spaces of both the 2nd and the 3rd
6461   // operands of the conditional operator.
6462   QualType ResultTy = [&, ResultAddrSpace]() {
6463     if (S.getLangOpts().OpenCL) {
6464       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6465       CompositeQuals.setAddressSpace(ResultAddrSpace);
6466       return S.Context
6467           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6468           .withCVRQualifiers(MergedCVRQual);
6469     }
6470     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6471   }();
6472   if (IsBlockPointer)
6473     ResultTy = S.Context.getBlockPointerType(ResultTy);
6474   else
6475     ResultTy = S.Context.getPointerType(ResultTy);
6476 
6477   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6478   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6479   return ResultTy;
6480 }
6481 
6482 /// \brief Return the resulting type when the operands are both block pointers.
6483 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6484                                                           ExprResult &LHS,
6485                                                           ExprResult &RHS,
6486                                                           SourceLocation Loc) {
6487   QualType LHSTy = LHS.get()->getType();
6488   QualType RHSTy = RHS.get()->getType();
6489 
6490   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6491     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6492       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6493       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6494       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6495       return destType;
6496     }
6497     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6498       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6499       << RHS.get()->getSourceRange();
6500     return QualType();
6501   }
6502 
6503   // We have 2 block pointer types.
6504   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6505 }
6506 
6507 /// \brief Return the resulting type when the operands are both pointers.
6508 static QualType
6509 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6510                                             ExprResult &RHS,
6511                                             SourceLocation Loc) {
6512   // get the pointer types
6513   QualType LHSTy = LHS.get()->getType();
6514   QualType RHSTy = RHS.get()->getType();
6515 
6516   // get the "pointed to" types
6517   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6518   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6519 
6520   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6521   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6522     // Figure out necessary qualifiers (C99 6.5.15p6)
6523     QualType destPointee
6524       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6525     QualType destType = S.Context.getPointerType(destPointee);
6526     // Add qualifiers if necessary.
6527     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6528     // Promote to void*.
6529     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6530     return destType;
6531   }
6532   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6533     QualType destPointee
6534       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6535     QualType destType = S.Context.getPointerType(destPointee);
6536     // Add qualifiers if necessary.
6537     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6538     // Promote to void*.
6539     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6540     return destType;
6541   }
6542 
6543   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6544 }
6545 
6546 /// \brief Return false if the first expression is not an integer and the second
6547 /// expression is not a pointer, true otherwise.
6548 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6549                                         Expr* PointerExpr, SourceLocation Loc,
6550                                         bool IsIntFirstExpr) {
6551   if (!PointerExpr->getType()->isPointerType() ||
6552       !Int.get()->getType()->isIntegerType())
6553     return false;
6554 
6555   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6556   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6557 
6558   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6559     << Expr1->getType() << Expr2->getType()
6560     << Expr1->getSourceRange() << Expr2->getSourceRange();
6561   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6562                             CK_IntegralToPointer);
6563   return true;
6564 }
6565 
6566 /// \brief Simple conversion between integer and floating point types.
6567 ///
6568 /// Used when handling the OpenCL conditional operator where the
6569 /// condition is a vector while the other operands are scalar.
6570 ///
6571 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6572 /// types are either integer or floating type. Between the two
6573 /// operands, the type with the higher rank is defined as the "result
6574 /// type". The other operand needs to be promoted to the same type. No
6575 /// other type promotion is allowed. We cannot use
6576 /// UsualArithmeticConversions() for this purpose, since it always
6577 /// promotes promotable types.
6578 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6579                                             ExprResult &RHS,
6580                                             SourceLocation QuestionLoc) {
6581   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6582   if (LHS.isInvalid())
6583     return QualType();
6584   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6585   if (RHS.isInvalid())
6586     return QualType();
6587 
6588   // For conversion purposes, we ignore any qualifiers.
6589   // For example, "const float" and "float" are equivalent.
6590   QualType LHSType =
6591     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6592   QualType RHSType =
6593     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6594 
6595   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6596     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6597       << LHSType << LHS.get()->getSourceRange();
6598     return QualType();
6599   }
6600 
6601   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6602     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6603       << RHSType << RHS.get()->getSourceRange();
6604     return QualType();
6605   }
6606 
6607   // If both types are identical, no conversion is needed.
6608   if (LHSType == RHSType)
6609     return LHSType;
6610 
6611   // Now handle "real" floating types (i.e. float, double, long double).
6612   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6613     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6614                                  /*IsCompAssign = */ false);
6615 
6616   // Finally, we have two differing integer types.
6617   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6618   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6619 }
6620 
6621 /// \brief Convert scalar operands to a vector that matches the
6622 ///        condition in length.
6623 ///
6624 /// Used when handling the OpenCL conditional operator where the
6625 /// condition is a vector while the other operands are scalar.
6626 ///
6627 /// We first compute the "result type" for the scalar operands
6628 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6629 /// into a vector of that type where the length matches the condition
6630 /// vector type. s6.11.6 requires that the element types of the result
6631 /// and the condition must have the same number of bits.
6632 static QualType
6633 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6634                               QualType CondTy, SourceLocation QuestionLoc) {
6635   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6636   if (ResTy.isNull()) return QualType();
6637 
6638   const VectorType *CV = CondTy->getAs<VectorType>();
6639   assert(CV);
6640 
6641   // Determine the vector result type
6642   unsigned NumElements = CV->getNumElements();
6643   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6644 
6645   // Ensure that all types have the same number of bits
6646   if (S.Context.getTypeSize(CV->getElementType())
6647       != S.Context.getTypeSize(ResTy)) {
6648     // Since VectorTy is created internally, it does not pretty print
6649     // with an OpenCL name. Instead, we just print a description.
6650     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6651     SmallString<64> Str;
6652     llvm::raw_svector_ostream OS(Str);
6653     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6654     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6655       << CondTy << OS.str();
6656     return QualType();
6657   }
6658 
6659   // Convert operands to the vector result type
6660   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6661   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6662 
6663   return VectorTy;
6664 }
6665 
6666 /// \brief Return false if this is a valid OpenCL condition vector
6667 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6668                                        SourceLocation QuestionLoc) {
6669   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6670   // integral type.
6671   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6672   assert(CondTy);
6673   QualType EleTy = CondTy->getElementType();
6674   if (EleTy->isIntegerType()) return false;
6675 
6676   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6677     << Cond->getType() << Cond->getSourceRange();
6678   return true;
6679 }
6680 
6681 /// \brief Return false if the vector condition type and the vector
6682 ///        result type are compatible.
6683 ///
6684 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6685 /// number of elements, and their element types have the same number
6686 /// of bits.
6687 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6688                               SourceLocation QuestionLoc) {
6689   const VectorType *CV = CondTy->getAs<VectorType>();
6690   const VectorType *RV = VecResTy->getAs<VectorType>();
6691   assert(CV && RV);
6692 
6693   if (CV->getNumElements() != RV->getNumElements()) {
6694     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6695       << CondTy << VecResTy;
6696     return true;
6697   }
6698 
6699   QualType CVE = CV->getElementType();
6700   QualType RVE = RV->getElementType();
6701 
6702   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6703     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6704       << CondTy << VecResTy;
6705     return true;
6706   }
6707 
6708   return false;
6709 }
6710 
6711 /// \brief Return the resulting type for the conditional operator in
6712 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6713 ///        s6.3.i) when the condition is a vector type.
6714 static QualType
6715 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6716                              ExprResult &LHS, ExprResult &RHS,
6717                              SourceLocation QuestionLoc) {
6718   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6719   if (Cond.isInvalid())
6720     return QualType();
6721   QualType CondTy = Cond.get()->getType();
6722 
6723   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6724     return QualType();
6725 
6726   // If either operand is a vector then find the vector type of the
6727   // result as specified in OpenCL v1.1 s6.3.i.
6728   if (LHS.get()->getType()->isVectorType() ||
6729       RHS.get()->getType()->isVectorType()) {
6730     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6731                                               /*isCompAssign*/false,
6732                                               /*AllowBothBool*/true,
6733                                               /*AllowBoolConversions*/false);
6734     if (VecResTy.isNull()) return QualType();
6735     // The result type must match the condition type as specified in
6736     // OpenCL v1.1 s6.11.6.
6737     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6738       return QualType();
6739     return VecResTy;
6740   }
6741 
6742   // Both operands are scalar.
6743   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6744 }
6745 
6746 /// \brief Return true if the Expr is block type
6747 static bool checkBlockType(Sema &S, const Expr *E) {
6748   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6749     QualType Ty = CE->getCallee()->getType();
6750     if (Ty->isBlockPointerType()) {
6751       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6752       return true;
6753     }
6754   }
6755   return false;
6756 }
6757 
6758 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6759 /// In that case, LHS = cond.
6760 /// C99 6.5.15
6761 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6762                                         ExprResult &RHS, ExprValueKind &VK,
6763                                         ExprObjectKind &OK,
6764                                         SourceLocation QuestionLoc) {
6765 
6766   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6767   if (!LHSResult.isUsable()) return QualType();
6768   LHS = LHSResult;
6769 
6770   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6771   if (!RHSResult.isUsable()) return QualType();
6772   RHS = RHSResult;
6773 
6774   // C++ is sufficiently different to merit its own checker.
6775   if (getLangOpts().CPlusPlus)
6776     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6777 
6778   VK = VK_RValue;
6779   OK = OK_Ordinary;
6780 
6781   // The OpenCL operator with a vector condition is sufficiently
6782   // different to merit its own checker.
6783   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6784     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6785 
6786   // First, check the condition.
6787   Cond = UsualUnaryConversions(Cond.get());
6788   if (Cond.isInvalid())
6789     return QualType();
6790   if (checkCondition(*this, Cond.get(), QuestionLoc))
6791     return QualType();
6792 
6793   // Now check the two expressions.
6794   if (LHS.get()->getType()->isVectorType() ||
6795       RHS.get()->getType()->isVectorType())
6796     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6797                                /*AllowBothBool*/true,
6798                                /*AllowBoolConversions*/false);
6799 
6800   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6801   if (LHS.isInvalid() || RHS.isInvalid())
6802     return QualType();
6803 
6804   QualType LHSTy = LHS.get()->getType();
6805   QualType RHSTy = RHS.get()->getType();
6806 
6807   // Diagnose attempts to convert between __float128 and long double where
6808   // such conversions currently can't be handled.
6809   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6810     Diag(QuestionLoc,
6811          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6812       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6813     return QualType();
6814   }
6815 
6816   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6817   // selection operator (?:).
6818   if (getLangOpts().OpenCL &&
6819       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6820     return QualType();
6821   }
6822 
6823   // If both operands have arithmetic type, do the usual arithmetic conversions
6824   // to find a common type: C99 6.5.15p3,5.
6825   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6826     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6827     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6828 
6829     return ResTy;
6830   }
6831 
6832   // If both operands are the same structure or union type, the result is that
6833   // type.
6834   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6835     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6836       if (LHSRT->getDecl() == RHSRT->getDecl())
6837         // "If both the operands have structure or union type, the result has
6838         // that type."  This implies that CV qualifiers are dropped.
6839         return LHSTy.getUnqualifiedType();
6840     // FIXME: Type of conditional expression must be complete in C mode.
6841   }
6842 
6843   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6844   // The following || allows only one side to be void (a GCC-ism).
6845   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6846     return checkConditionalVoidType(*this, LHS, RHS);
6847   }
6848 
6849   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6850   // the type of the other operand."
6851   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6852   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6853 
6854   // All objective-c pointer type analysis is done here.
6855   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6856                                                         QuestionLoc);
6857   if (LHS.isInvalid() || RHS.isInvalid())
6858     return QualType();
6859   if (!compositeType.isNull())
6860     return compositeType;
6861 
6862 
6863   // Handle block pointer types.
6864   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6865     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6866                                                      QuestionLoc);
6867 
6868   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6869   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6870     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6871                                                        QuestionLoc);
6872 
6873   // GCC compatibility: soften pointer/integer mismatch.  Note that
6874   // null pointers have been filtered out by this point.
6875   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6876       /*isIntFirstExpr=*/true))
6877     return RHSTy;
6878   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6879       /*isIntFirstExpr=*/false))
6880     return LHSTy;
6881 
6882   // Emit a better diagnostic if one of the expressions is a null pointer
6883   // constant and the other is not a pointer type. In this case, the user most
6884   // likely forgot to take the address of the other expression.
6885   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6886     return QualType();
6887 
6888   // Otherwise, the operands are not compatible.
6889   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6890     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6891     << RHS.get()->getSourceRange();
6892   return QualType();
6893 }
6894 
6895 /// FindCompositeObjCPointerType - Helper method to find composite type of
6896 /// two objective-c pointer types of the two input expressions.
6897 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6898                                             SourceLocation QuestionLoc) {
6899   QualType LHSTy = LHS.get()->getType();
6900   QualType RHSTy = RHS.get()->getType();
6901 
6902   // Handle things like Class and struct objc_class*.  Here we case the result
6903   // to the pseudo-builtin, because that will be implicitly cast back to the
6904   // redefinition type if an attempt is made to access its fields.
6905   if (LHSTy->isObjCClassType() &&
6906       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6907     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6908     return LHSTy;
6909   }
6910   if (RHSTy->isObjCClassType() &&
6911       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6912     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6913     return RHSTy;
6914   }
6915   // And the same for struct objc_object* / id
6916   if (LHSTy->isObjCIdType() &&
6917       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6918     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6919     return LHSTy;
6920   }
6921   if (RHSTy->isObjCIdType() &&
6922       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6923     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6924     return RHSTy;
6925   }
6926   // And the same for struct objc_selector* / SEL
6927   if (Context.isObjCSelType(LHSTy) &&
6928       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6929     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6930     return LHSTy;
6931   }
6932   if (Context.isObjCSelType(RHSTy) &&
6933       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6934     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6935     return RHSTy;
6936   }
6937   // Check constraints for Objective-C object pointers types.
6938   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6939 
6940     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6941       // Two identical object pointer types are always compatible.
6942       return LHSTy;
6943     }
6944     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6945     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6946     QualType compositeType = LHSTy;
6947 
6948     // If both operands are interfaces and either operand can be
6949     // assigned to the other, use that type as the composite
6950     // type. This allows
6951     //   xxx ? (A*) a : (B*) b
6952     // where B is a subclass of A.
6953     //
6954     // Additionally, as for assignment, if either type is 'id'
6955     // allow silent coercion. Finally, if the types are
6956     // incompatible then make sure to use 'id' as the composite
6957     // type so the result is acceptable for sending messages to.
6958 
6959     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6960     // It could return the composite type.
6961     if (!(compositeType =
6962           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6963       // Nothing more to do.
6964     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6965       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6966     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6967       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6968     } else if ((LHSTy->isObjCQualifiedIdType() ||
6969                 RHSTy->isObjCQualifiedIdType()) &&
6970                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6971       // Need to handle "id<xx>" explicitly.
6972       // GCC allows qualified id and any Objective-C type to devolve to
6973       // id. Currently localizing to here until clear this should be
6974       // part of ObjCQualifiedIdTypesAreCompatible.
6975       compositeType = Context.getObjCIdType();
6976     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6977       compositeType = Context.getObjCIdType();
6978     } else {
6979       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6980       << LHSTy << RHSTy
6981       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6982       QualType incompatTy = Context.getObjCIdType();
6983       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6984       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6985       return incompatTy;
6986     }
6987     // The object pointer types are compatible.
6988     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6989     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6990     return compositeType;
6991   }
6992   // Check Objective-C object pointer types and 'void *'
6993   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6994     if (getLangOpts().ObjCAutoRefCount) {
6995       // ARC forbids the implicit conversion of object pointers to 'void *',
6996       // so these types are not compatible.
6997       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6998           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6999       LHS = RHS = true;
7000       return QualType();
7001     }
7002     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7003     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7004     QualType destPointee
7005     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7006     QualType destType = Context.getPointerType(destPointee);
7007     // Add qualifiers if necessary.
7008     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7009     // Promote to void*.
7010     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7011     return destType;
7012   }
7013   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7014     if (getLangOpts().ObjCAutoRefCount) {
7015       // ARC forbids the implicit conversion of object pointers to 'void *',
7016       // so these types are not compatible.
7017       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7018           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7019       LHS = RHS = true;
7020       return QualType();
7021     }
7022     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7023     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7024     QualType destPointee
7025     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7026     QualType destType = Context.getPointerType(destPointee);
7027     // Add qualifiers if necessary.
7028     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7029     // Promote to void*.
7030     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7031     return destType;
7032   }
7033   return QualType();
7034 }
7035 
7036 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7037 /// ParenRange in parentheses.
7038 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7039                                const PartialDiagnostic &Note,
7040                                SourceRange ParenRange) {
7041   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7042   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7043       EndLoc.isValid()) {
7044     Self.Diag(Loc, Note)
7045       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7046       << FixItHint::CreateInsertion(EndLoc, ")");
7047   } else {
7048     // We can't display the parentheses, so just show the bare note.
7049     Self.Diag(Loc, Note) << ParenRange;
7050   }
7051 }
7052 
7053 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7054   return BinaryOperator::isAdditiveOp(Opc) ||
7055          BinaryOperator::isMultiplicativeOp(Opc) ||
7056          BinaryOperator::isShiftOp(Opc);
7057 }
7058 
7059 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7060 /// expression, either using a built-in or overloaded operator,
7061 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7062 /// expression.
7063 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7064                                    Expr **RHSExprs) {
7065   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7066   E = E->IgnoreImpCasts();
7067   E = E->IgnoreConversionOperator();
7068   E = E->IgnoreImpCasts();
7069 
7070   // Built-in binary operator.
7071   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7072     if (IsArithmeticOp(OP->getOpcode())) {
7073       *Opcode = OP->getOpcode();
7074       *RHSExprs = OP->getRHS();
7075       return true;
7076     }
7077   }
7078 
7079   // Overloaded operator.
7080   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7081     if (Call->getNumArgs() != 2)
7082       return false;
7083 
7084     // Make sure this is really a binary operator that is safe to pass into
7085     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7086     OverloadedOperatorKind OO = Call->getOperator();
7087     if (OO < OO_Plus || OO > OO_Arrow ||
7088         OO == OO_PlusPlus || OO == OO_MinusMinus)
7089       return false;
7090 
7091     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7092     if (IsArithmeticOp(OpKind)) {
7093       *Opcode = OpKind;
7094       *RHSExprs = Call->getArg(1);
7095       return true;
7096     }
7097   }
7098 
7099   return false;
7100 }
7101 
7102 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7103 /// or is a logical expression such as (x==y) which has int type, but is
7104 /// commonly interpreted as boolean.
7105 static bool ExprLooksBoolean(Expr *E) {
7106   E = E->IgnoreParenImpCasts();
7107 
7108   if (E->getType()->isBooleanType())
7109     return true;
7110   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7111     return OP->isComparisonOp() || OP->isLogicalOp();
7112   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7113     return OP->getOpcode() == UO_LNot;
7114   if (E->getType()->isPointerType())
7115     return true;
7116 
7117   return false;
7118 }
7119 
7120 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7121 /// and binary operator are mixed in a way that suggests the programmer assumed
7122 /// the conditional operator has higher precedence, for example:
7123 /// "int x = a + someBinaryCondition ? 1 : 2".
7124 static void DiagnoseConditionalPrecedence(Sema &Self,
7125                                           SourceLocation OpLoc,
7126                                           Expr *Condition,
7127                                           Expr *LHSExpr,
7128                                           Expr *RHSExpr) {
7129   BinaryOperatorKind CondOpcode;
7130   Expr *CondRHS;
7131 
7132   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7133     return;
7134   if (!ExprLooksBoolean(CondRHS))
7135     return;
7136 
7137   // The condition is an arithmetic binary expression, with a right-
7138   // hand side that looks boolean, so warn.
7139 
7140   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7141       << Condition->getSourceRange()
7142       << BinaryOperator::getOpcodeStr(CondOpcode);
7143 
7144   SuggestParentheses(Self, OpLoc,
7145     Self.PDiag(diag::note_precedence_silence)
7146       << BinaryOperator::getOpcodeStr(CondOpcode),
7147     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7148 
7149   SuggestParentheses(Self, OpLoc,
7150     Self.PDiag(diag::note_precedence_conditional_first),
7151     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7152 }
7153 
7154 /// Compute the nullability of a conditional expression.
7155 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7156                                               QualType LHSTy, QualType RHSTy,
7157                                               ASTContext &Ctx) {
7158   if (!ResTy->isAnyPointerType())
7159     return ResTy;
7160 
7161   auto GetNullability = [&Ctx](QualType Ty) {
7162     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7163     if (Kind)
7164       return *Kind;
7165     return NullabilityKind::Unspecified;
7166   };
7167 
7168   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7169   NullabilityKind MergedKind;
7170 
7171   // Compute nullability of a binary conditional expression.
7172   if (IsBin) {
7173     if (LHSKind == NullabilityKind::NonNull)
7174       MergedKind = NullabilityKind::NonNull;
7175     else
7176       MergedKind = RHSKind;
7177   // Compute nullability of a normal conditional expression.
7178   } else {
7179     if (LHSKind == NullabilityKind::Nullable ||
7180         RHSKind == NullabilityKind::Nullable)
7181       MergedKind = NullabilityKind::Nullable;
7182     else if (LHSKind == NullabilityKind::NonNull)
7183       MergedKind = RHSKind;
7184     else if (RHSKind == NullabilityKind::NonNull)
7185       MergedKind = LHSKind;
7186     else
7187       MergedKind = NullabilityKind::Unspecified;
7188   }
7189 
7190   // Return if ResTy already has the correct nullability.
7191   if (GetNullability(ResTy) == MergedKind)
7192     return ResTy;
7193 
7194   // Strip all nullability from ResTy.
7195   while (ResTy->getNullability(Ctx))
7196     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7197 
7198   // Create a new AttributedType with the new nullability kind.
7199   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7200   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7201 }
7202 
7203 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7204 /// in the case of a the GNU conditional expr extension.
7205 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7206                                     SourceLocation ColonLoc,
7207                                     Expr *CondExpr, Expr *LHSExpr,
7208                                     Expr *RHSExpr) {
7209   if (!getLangOpts().CPlusPlus) {
7210     // C cannot handle TypoExpr nodes in the condition because it
7211     // doesn't handle dependent types properly, so make sure any TypoExprs have
7212     // been dealt with before checking the operands.
7213     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7214     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7215     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7216 
7217     if (!CondResult.isUsable())
7218       return ExprError();
7219 
7220     if (LHSExpr) {
7221       if (!LHSResult.isUsable())
7222         return ExprError();
7223     }
7224 
7225     if (!RHSResult.isUsable())
7226       return ExprError();
7227 
7228     CondExpr = CondResult.get();
7229     LHSExpr = LHSResult.get();
7230     RHSExpr = RHSResult.get();
7231   }
7232 
7233   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7234   // was the condition.
7235   OpaqueValueExpr *opaqueValue = nullptr;
7236   Expr *commonExpr = nullptr;
7237   if (!LHSExpr) {
7238     commonExpr = CondExpr;
7239     // Lower out placeholder types first.  This is important so that we don't
7240     // try to capture a placeholder. This happens in few cases in C++; such
7241     // as Objective-C++'s dictionary subscripting syntax.
7242     if (commonExpr->hasPlaceholderType()) {
7243       ExprResult result = CheckPlaceholderExpr(commonExpr);
7244       if (!result.isUsable()) return ExprError();
7245       commonExpr = result.get();
7246     }
7247     // We usually want to apply unary conversions *before* saving, except
7248     // in the special case of a C++ l-value conditional.
7249     if (!(getLangOpts().CPlusPlus
7250           && !commonExpr->isTypeDependent()
7251           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7252           && commonExpr->isGLValue()
7253           && commonExpr->isOrdinaryOrBitFieldObject()
7254           && RHSExpr->isOrdinaryOrBitFieldObject()
7255           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7256       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7257       if (commonRes.isInvalid())
7258         return ExprError();
7259       commonExpr = commonRes.get();
7260     }
7261 
7262     // If the common expression is a class or array prvalue, materialize it
7263     // so that we can safely refer to it multiple times.
7264     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7265                                    commonExpr->getType()->isArrayType())) {
7266       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7267       if (MatExpr.isInvalid())
7268         return ExprError();
7269       commonExpr = MatExpr.get();
7270     }
7271 
7272     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7273                                                 commonExpr->getType(),
7274                                                 commonExpr->getValueKind(),
7275                                                 commonExpr->getObjectKind(),
7276                                                 commonExpr);
7277     LHSExpr = CondExpr = opaqueValue;
7278   }
7279 
7280   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7281   ExprValueKind VK = VK_RValue;
7282   ExprObjectKind OK = OK_Ordinary;
7283   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7284   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7285                                              VK, OK, QuestionLoc);
7286   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7287       RHS.isInvalid())
7288     return ExprError();
7289 
7290   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7291                                 RHS.get());
7292 
7293   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7294 
7295   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7296                                          Context);
7297 
7298   if (!commonExpr)
7299     return new (Context)
7300         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7301                             RHS.get(), result, VK, OK);
7302 
7303   return new (Context) BinaryConditionalOperator(
7304       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7305       ColonLoc, result, VK, OK);
7306 }
7307 
7308 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7309 // being closely modeled after the C99 spec:-). The odd characteristic of this
7310 // routine is it effectively iqnores the qualifiers on the top level pointee.
7311 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7312 // FIXME: add a couple examples in this comment.
7313 static Sema::AssignConvertType
7314 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7315   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7316   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7317 
7318   // get the "pointed to" type (ignoring qualifiers at the top level)
7319   const Type *lhptee, *rhptee;
7320   Qualifiers lhq, rhq;
7321   std::tie(lhptee, lhq) =
7322       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7323   std::tie(rhptee, rhq) =
7324       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7325 
7326   Sema::AssignConvertType ConvTy = Sema::Compatible;
7327 
7328   // C99 6.5.16.1p1: This following citation is common to constraints
7329   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7330   // qualifiers of the type *pointed to* by the right;
7331 
7332   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7333   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7334       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7335     // Ignore lifetime for further calculation.
7336     lhq.removeObjCLifetime();
7337     rhq.removeObjCLifetime();
7338   }
7339 
7340   if (!lhq.compatiblyIncludes(rhq)) {
7341     // Treat address-space mismatches as fatal.  TODO: address subspaces
7342     if (!lhq.isAddressSpaceSupersetOf(rhq))
7343       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7344 
7345     // It's okay to add or remove GC or lifetime qualifiers when converting to
7346     // and from void*.
7347     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7348                         .compatiblyIncludes(
7349                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7350              && (lhptee->isVoidType() || rhptee->isVoidType()))
7351       ; // keep old
7352 
7353     // Treat lifetime mismatches as fatal.
7354     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7355       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7356 
7357     // For GCC/MS compatibility, other qualifier mismatches are treated
7358     // as still compatible in C.
7359     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7360   }
7361 
7362   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7363   // incomplete type and the other is a pointer to a qualified or unqualified
7364   // version of void...
7365   if (lhptee->isVoidType()) {
7366     if (rhptee->isIncompleteOrObjectType())
7367       return ConvTy;
7368 
7369     // As an extension, we allow cast to/from void* to function pointer.
7370     assert(rhptee->isFunctionType());
7371     return Sema::FunctionVoidPointer;
7372   }
7373 
7374   if (rhptee->isVoidType()) {
7375     if (lhptee->isIncompleteOrObjectType())
7376       return ConvTy;
7377 
7378     // As an extension, we allow cast to/from void* to function pointer.
7379     assert(lhptee->isFunctionType());
7380     return Sema::FunctionVoidPointer;
7381   }
7382 
7383   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7384   // unqualified versions of compatible types, ...
7385   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7386   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7387     // Check if the pointee types are compatible ignoring the sign.
7388     // We explicitly check for char so that we catch "char" vs
7389     // "unsigned char" on systems where "char" is unsigned.
7390     if (lhptee->isCharType())
7391       ltrans = S.Context.UnsignedCharTy;
7392     else if (lhptee->hasSignedIntegerRepresentation())
7393       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7394 
7395     if (rhptee->isCharType())
7396       rtrans = S.Context.UnsignedCharTy;
7397     else if (rhptee->hasSignedIntegerRepresentation())
7398       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7399 
7400     if (ltrans == rtrans) {
7401       // Types are compatible ignoring the sign. Qualifier incompatibility
7402       // takes priority over sign incompatibility because the sign
7403       // warning can be disabled.
7404       if (ConvTy != Sema::Compatible)
7405         return ConvTy;
7406 
7407       return Sema::IncompatiblePointerSign;
7408     }
7409 
7410     // If we are a multi-level pointer, it's possible that our issue is simply
7411     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7412     // the eventual target type is the same and the pointers have the same
7413     // level of indirection, this must be the issue.
7414     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7415       do {
7416         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7417         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7418       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7419 
7420       if (lhptee == rhptee)
7421         return Sema::IncompatibleNestedPointerQualifiers;
7422     }
7423 
7424     // General pointer incompatibility takes priority over qualifiers.
7425     return Sema::IncompatiblePointer;
7426   }
7427   if (!S.getLangOpts().CPlusPlus &&
7428       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7429     return Sema::IncompatiblePointer;
7430   return ConvTy;
7431 }
7432 
7433 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7434 /// block pointer types are compatible or whether a block and normal pointer
7435 /// are compatible. It is more restrict than comparing two function pointer
7436 // types.
7437 static Sema::AssignConvertType
7438 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7439                                     QualType RHSType) {
7440   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7441   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7442 
7443   QualType lhptee, rhptee;
7444 
7445   // get the "pointed to" type (ignoring qualifiers at the top level)
7446   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7447   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7448 
7449   // In C++, the types have to match exactly.
7450   if (S.getLangOpts().CPlusPlus)
7451     return Sema::IncompatibleBlockPointer;
7452 
7453   Sema::AssignConvertType ConvTy = Sema::Compatible;
7454 
7455   // For blocks we enforce that qualifiers are identical.
7456   Qualifiers LQuals = lhptee.getLocalQualifiers();
7457   Qualifiers RQuals = rhptee.getLocalQualifiers();
7458   if (S.getLangOpts().OpenCL) {
7459     LQuals.removeAddressSpace();
7460     RQuals.removeAddressSpace();
7461   }
7462   if (LQuals != RQuals)
7463     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7464 
7465   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7466   // assignment.
7467   // The current behavior is similar to C++ lambdas. A block might be
7468   // assigned to a variable iff its return type and parameters are compatible
7469   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7470   // an assignment. Presumably it should behave in way that a function pointer
7471   // assignment does in C, so for each parameter and return type:
7472   //  * CVR and address space of LHS should be a superset of CVR and address
7473   //  space of RHS.
7474   //  * unqualified types should be compatible.
7475   if (S.getLangOpts().OpenCL) {
7476     if (!S.Context.typesAreBlockPointerCompatible(
7477             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7478             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7479       return Sema::IncompatibleBlockPointer;
7480   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7481     return Sema::IncompatibleBlockPointer;
7482 
7483   return ConvTy;
7484 }
7485 
7486 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7487 /// for assignment compatibility.
7488 static Sema::AssignConvertType
7489 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7490                                    QualType RHSType) {
7491   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7492   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7493 
7494   if (LHSType->isObjCBuiltinType()) {
7495     // Class is not compatible with ObjC object pointers.
7496     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7497         !RHSType->isObjCQualifiedClassType())
7498       return Sema::IncompatiblePointer;
7499     return Sema::Compatible;
7500   }
7501   if (RHSType->isObjCBuiltinType()) {
7502     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7503         !LHSType->isObjCQualifiedClassType())
7504       return Sema::IncompatiblePointer;
7505     return Sema::Compatible;
7506   }
7507   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7508   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7509 
7510   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7511       // make an exception for id<P>
7512       !LHSType->isObjCQualifiedIdType())
7513     return Sema::CompatiblePointerDiscardsQualifiers;
7514 
7515   if (S.Context.typesAreCompatible(LHSType, RHSType))
7516     return Sema::Compatible;
7517   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7518     return Sema::IncompatibleObjCQualifiedId;
7519   return Sema::IncompatiblePointer;
7520 }
7521 
7522 Sema::AssignConvertType
7523 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7524                                  QualType LHSType, QualType RHSType) {
7525   // Fake up an opaque expression.  We don't actually care about what
7526   // cast operations are required, so if CheckAssignmentConstraints
7527   // adds casts to this they'll be wasted, but fortunately that doesn't
7528   // usually happen on valid code.
7529   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7530   ExprResult RHSPtr = &RHSExpr;
7531   CastKind K;
7532 
7533   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7534 }
7535 
7536 /// This helper function returns true if QT is a vector type that has element
7537 /// type ElementType.
7538 static bool isVector(QualType QT, QualType ElementType) {
7539   if (const VectorType *VT = QT->getAs<VectorType>())
7540     return VT->getElementType() == ElementType;
7541   return false;
7542 }
7543 
7544 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7545 /// has code to accommodate several GCC extensions when type checking
7546 /// pointers. Here are some objectionable examples that GCC considers warnings:
7547 ///
7548 ///  int a, *pint;
7549 ///  short *pshort;
7550 ///  struct foo *pfoo;
7551 ///
7552 ///  pint = pshort; // warning: assignment from incompatible pointer type
7553 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7554 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7555 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7556 ///
7557 /// As a result, the code for dealing with pointers is more complex than the
7558 /// C99 spec dictates.
7559 ///
7560 /// Sets 'Kind' for any result kind except Incompatible.
7561 Sema::AssignConvertType
7562 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7563                                  CastKind &Kind, bool ConvertRHS) {
7564   QualType RHSType = RHS.get()->getType();
7565   QualType OrigLHSType = LHSType;
7566 
7567   // Get canonical types.  We're not formatting these types, just comparing
7568   // them.
7569   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7570   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7571 
7572   // Common case: no conversion required.
7573   if (LHSType == RHSType) {
7574     Kind = CK_NoOp;
7575     return Compatible;
7576   }
7577 
7578   // If we have an atomic type, try a non-atomic assignment, then just add an
7579   // atomic qualification step.
7580   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7581     Sema::AssignConvertType result =
7582       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7583     if (result != Compatible)
7584       return result;
7585     if (Kind != CK_NoOp && ConvertRHS)
7586       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7587     Kind = CK_NonAtomicToAtomic;
7588     return Compatible;
7589   }
7590 
7591   // If the left-hand side is a reference type, then we are in a
7592   // (rare!) case where we've allowed the use of references in C,
7593   // e.g., as a parameter type in a built-in function. In this case,
7594   // just make sure that the type referenced is compatible with the
7595   // right-hand side type. The caller is responsible for adjusting
7596   // LHSType so that the resulting expression does not have reference
7597   // type.
7598   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7599     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7600       Kind = CK_LValueBitCast;
7601       return Compatible;
7602     }
7603     return Incompatible;
7604   }
7605 
7606   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7607   // to the same ExtVector type.
7608   if (LHSType->isExtVectorType()) {
7609     if (RHSType->isExtVectorType())
7610       return Incompatible;
7611     if (RHSType->isArithmeticType()) {
7612       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7613       if (ConvertRHS)
7614         RHS = prepareVectorSplat(LHSType, RHS.get());
7615       Kind = CK_VectorSplat;
7616       return Compatible;
7617     }
7618   }
7619 
7620   // Conversions to or from vector type.
7621   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7622     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7623       // Allow assignments of an AltiVec vector type to an equivalent GCC
7624       // vector type and vice versa
7625       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7626         Kind = CK_BitCast;
7627         return Compatible;
7628       }
7629 
7630       // If we are allowing lax vector conversions, and LHS and RHS are both
7631       // vectors, the total size only needs to be the same. This is a bitcast;
7632       // no bits are changed but the result type is different.
7633       if (isLaxVectorConversion(RHSType, LHSType)) {
7634         Kind = CK_BitCast;
7635         return IncompatibleVectors;
7636       }
7637     }
7638 
7639     // When the RHS comes from another lax conversion (e.g. binops between
7640     // scalars and vectors) the result is canonicalized as a vector. When the
7641     // LHS is also a vector, the lax is allowed by the condition above. Handle
7642     // the case where LHS is a scalar.
7643     if (LHSType->isScalarType()) {
7644       const VectorType *VecType = RHSType->getAs<VectorType>();
7645       if (VecType && VecType->getNumElements() == 1 &&
7646           isLaxVectorConversion(RHSType, LHSType)) {
7647         ExprResult *VecExpr = &RHS;
7648         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7649         Kind = CK_BitCast;
7650         return Compatible;
7651       }
7652     }
7653 
7654     return Incompatible;
7655   }
7656 
7657   // Diagnose attempts to convert between __float128 and long double where
7658   // such conversions currently can't be handled.
7659   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7660     return Incompatible;
7661 
7662   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7663   // discards the imaginary part.
7664   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7665       !LHSType->getAs<ComplexType>())
7666     return Incompatible;
7667 
7668   // Arithmetic conversions.
7669   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7670       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7671     if (ConvertRHS)
7672       Kind = PrepareScalarCast(RHS, LHSType);
7673     return Compatible;
7674   }
7675 
7676   // Conversions to normal pointers.
7677   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7678     // U* -> T*
7679     if (isa<PointerType>(RHSType)) {
7680       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7681       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7682       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7683       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7684     }
7685 
7686     // int -> T*
7687     if (RHSType->isIntegerType()) {
7688       Kind = CK_IntegralToPointer; // FIXME: null?
7689       return IntToPointer;
7690     }
7691 
7692     // C pointers are not compatible with ObjC object pointers,
7693     // with two exceptions:
7694     if (isa<ObjCObjectPointerType>(RHSType)) {
7695       //  - conversions to void*
7696       if (LHSPointer->getPointeeType()->isVoidType()) {
7697         Kind = CK_BitCast;
7698         return Compatible;
7699       }
7700 
7701       //  - conversions from 'Class' to the redefinition type
7702       if (RHSType->isObjCClassType() &&
7703           Context.hasSameType(LHSType,
7704                               Context.getObjCClassRedefinitionType())) {
7705         Kind = CK_BitCast;
7706         return Compatible;
7707       }
7708 
7709       Kind = CK_BitCast;
7710       return IncompatiblePointer;
7711     }
7712 
7713     // U^ -> void*
7714     if (RHSType->getAs<BlockPointerType>()) {
7715       if (LHSPointer->getPointeeType()->isVoidType()) {
7716         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7717         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7718                                 ->getPointeeType()
7719                                 .getAddressSpace();
7720         Kind =
7721             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7722         return Compatible;
7723       }
7724     }
7725 
7726     return Incompatible;
7727   }
7728 
7729   // Conversions to block pointers.
7730   if (isa<BlockPointerType>(LHSType)) {
7731     // U^ -> T^
7732     if (RHSType->isBlockPointerType()) {
7733       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7734                               ->getPointeeType()
7735                               .getAddressSpace();
7736       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7737                               ->getPointeeType()
7738                               .getAddressSpace();
7739       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7740       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7741     }
7742 
7743     // int or null -> T^
7744     if (RHSType->isIntegerType()) {
7745       Kind = CK_IntegralToPointer; // FIXME: null
7746       return IntToBlockPointer;
7747     }
7748 
7749     // id -> T^
7750     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7751       Kind = CK_AnyPointerToBlockPointerCast;
7752       return Compatible;
7753     }
7754 
7755     // void* -> T^
7756     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7757       if (RHSPT->getPointeeType()->isVoidType()) {
7758         Kind = CK_AnyPointerToBlockPointerCast;
7759         return Compatible;
7760       }
7761 
7762     return Incompatible;
7763   }
7764 
7765   // Conversions to Objective-C pointers.
7766   if (isa<ObjCObjectPointerType>(LHSType)) {
7767     // A* -> B*
7768     if (RHSType->isObjCObjectPointerType()) {
7769       Kind = CK_BitCast;
7770       Sema::AssignConvertType result =
7771         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7772       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7773           result == Compatible &&
7774           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7775         result = IncompatibleObjCWeakRef;
7776       return result;
7777     }
7778 
7779     // int or null -> A*
7780     if (RHSType->isIntegerType()) {
7781       Kind = CK_IntegralToPointer; // FIXME: null
7782       return IntToPointer;
7783     }
7784 
7785     // In general, C pointers are not compatible with ObjC object pointers,
7786     // with two exceptions:
7787     if (isa<PointerType>(RHSType)) {
7788       Kind = CK_CPointerToObjCPointerCast;
7789 
7790       //  - conversions from 'void*'
7791       if (RHSType->isVoidPointerType()) {
7792         return Compatible;
7793       }
7794 
7795       //  - conversions to 'Class' from its redefinition type
7796       if (LHSType->isObjCClassType() &&
7797           Context.hasSameType(RHSType,
7798                               Context.getObjCClassRedefinitionType())) {
7799         return Compatible;
7800       }
7801 
7802       return IncompatiblePointer;
7803     }
7804 
7805     // Only under strict condition T^ is compatible with an Objective-C pointer.
7806     if (RHSType->isBlockPointerType() &&
7807         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7808       if (ConvertRHS)
7809         maybeExtendBlockObject(RHS);
7810       Kind = CK_BlockPointerToObjCPointerCast;
7811       return Compatible;
7812     }
7813 
7814     return Incompatible;
7815   }
7816 
7817   // Conversions from pointers that are not covered by the above.
7818   if (isa<PointerType>(RHSType)) {
7819     // T* -> _Bool
7820     if (LHSType == Context.BoolTy) {
7821       Kind = CK_PointerToBoolean;
7822       return Compatible;
7823     }
7824 
7825     // T* -> int
7826     if (LHSType->isIntegerType()) {
7827       Kind = CK_PointerToIntegral;
7828       return PointerToInt;
7829     }
7830 
7831     return Incompatible;
7832   }
7833 
7834   // Conversions from Objective-C pointers that are not covered by the above.
7835   if (isa<ObjCObjectPointerType>(RHSType)) {
7836     // T* -> _Bool
7837     if (LHSType == Context.BoolTy) {
7838       Kind = CK_PointerToBoolean;
7839       return Compatible;
7840     }
7841 
7842     // T* -> int
7843     if (LHSType->isIntegerType()) {
7844       Kind = CK_PointerToIntegral;
7845       return PointerToInt;
7846     }
7847 
7848     return Incompatible;
7849   }
7850 
7851   // struct A -> struct B
7852   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7853     if (Context.typesAreCompatible(LHSType, RHSType)) {
7854       Kind = CK_NoOp;
7855       return Compatible;
7856     }
7857   }
7858 
7859   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7860     Kind = CK_IntToOCLSampler;
7861     return Compatible;
7862   }
7863 
7864   return Incompatible;
7865 }
7866 
7867 /// \brief Constructs a transparent union from an expression that is
7868 /// used to initialize the transparent union.
7869 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7870                                       ExprResult &EResult, QualType UnionType,
7871                                       FieldDecl *Field) {
7872   // Build an initializer list that designates the appropriate member
7873   // of the transparent union.
7874   Expr *E = EResult.get();
7875   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7876                                                    E, SourceLocation());
7877   Initializer->setType(UnionType);
7878   Initializer->setInitializedFieldInUnion(Field);
7879 
7880   // Build a compound literal constructing a value of the transparent
7881   // union type from this initializer list.
7882   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7883   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7884                                         VK_RValue, Initializer, false);
7885 }
7886 
7887 Sema::AssignConvertType
7888 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7889                                                ExprResult &RHS) {
7890   QualType RHSType = RHS.get()->getType();
7891 
7892   // If the ArgType is a Union type, we want to handle a potential
7893   // transparent_union GCC extension.
7894   const RecordType *UT = ArgType->getAsUnionType();
7895   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7896     return Incompatible;
7897 
7898   // The field to initialize within the transparent union.
7899   RecordDecl *UD = UT->getDecl();
7900   FieldDecl *InitField = nullptr;
7901   // It's compatible if the expression matches any of the fields.
7902   for (auto *it : UD->fields()) {
7903     if (it->getType()->isPointerType()) {
7904       // If the transparent union contains a pointer type, we allow:
7905       // 1) void pointer
7906       // 2) null pointer constant
7907       if (RHSType->isPointerType())
7908         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7909           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7910           InitField = it;
7911           break;
7912         }
7913 
7914       if (RHS.get()->isNullPointerConstant(Context,
7915                                            Expr::NPC_ValueDependentIsNull)) {
7916         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7917                                 CK_NullToPointer);
7918         InitField = it;
7919         break;
7920       }
7921     }
7922 
7923     CastKind Kind;
7924     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7925           == Compatible) {
7926       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7927       InitField = it;
7928       break;
7929     }
7930   }
7931 
7932   if (!InitField)
7933     return Incompatible;
7934 
7935   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7936   return Compatible;
7937 }
7938 
7939 Sema::AssignConvertType
7940 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7941                                        bool Diagnose,
7942                                        bool DiagnoseCFAudited,
7943                                        bool ConvertRHS) {
7944   // We need to be able to tell the caller whether we diagnosed a problem, if
7945   // they ask us to issue diagnostics.
7946   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7947 
7948   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7949   // we can't avoid *all* modifications at the moment, so we need some somewhere
7950   // to put the updated value.
7951   ExprResult LocalRHS = CallerRHS;
7952   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7953 
7954   if (getLangOpts().CPlusPlus) {
7955     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7956       // C++ 5.17p3: If the left operand is not of class type, the
7957       // expression is implicitly converted (C++ 4) to the
7958       // cv-unqualified type of the left operand.
7959       QualType RHSType = RHS.get()->getType();
7960       if (Diagnose) {
7961         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7962                                         AA_Assigning);
7963       } else {
7964         ImplicitConversionSequence ICS =
7965             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7966                                   /*SuppressUserConversions=*/false,
7967                                   /*AllowExplicit=*/false,
7968                                   /*InOverloadResolution=*/false,
7969                                   /*CStyle=*/false,
7970                                   /*AllowObjCWritebackConversion=*/false);
7971         if (ICS.isFailure())
7972           return Incompatible;
7973         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7974                                         ICS, AA_Assigning);
7975       }
7976       if (RHS.isInvalid())
7977         return Incompatible;
7978       Sema::AssignConvertType result = Compatible;
7979       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7980           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7981         result = IncompatibleObjCWeakRef;
7982       return result;
7983     }
7984 
7985     // FIXME: Currently, we fall through and treat C++ classes like C
7986     // structures.
7987     // FIXME: We also fall through for atomics; not sure what should
7988     // happen there, though.
7989   } else if (RHS.get()->getType() == Context.OverloadTy) {
7990     // As a set of extensions to C, we support overloading on functions. These
7991     // functions need to be resolved here.
7992     DeclAccessPair DAP;
7993     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7994             RHS.get(), LHSType, /*Complain=*/false, DAP))
7995       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7996     else
7997       return Incompatible;
7998   }
7999 
8000   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8001   // a null pointer constant.
8002   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8003        LHSType->isBlockPointerType()) &&
8004       RHS.get()->isNullPointerConstant(Context,
8005                                        Expr::NPC_ValueDependentIsNull)) {
8006     if (Diagnose || ConvertRHS) {
8007       CastKind Kind;
8008       CXXCastPath Path;
8009       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8010                              /*IgnoreBaseAccess=*/false, Diagnose);
8011       if (ConvertRHS)
8012         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8013     }
8014     return Compatible;
8015   }
8016 
8017   // This check seems unnatural, however it is necessary to ensure the proper
8018   // conversion of functions/arrays. If the conversion were done for all
8019   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8020   // expressions that suppress this implicit conversion (&, sizeof).
8021   //
8022   // Suppress this for references: C++ 8.5.3p5.
8023   if (!LHSType->isReferenceType()) {
8024     // FIXME: We potentially allocate here even if ConvertRHS is false.
8025     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8026     if (RHS.isInvalid())
8027       return Incompatible;
8028   }
8029 
8030   Expr *PRE = RHS.get()->IgnoreParenCasts();
8031   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8032     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8033     if (PDecl && !PDecl->hasDefinition()) {
8034       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8035       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8036     }
8037   }
8038 
8039   CastKind Kind;
8040   Sema::AssignConvertType result =
8041     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8042 
8043   // C99 6.5.16.1p2: The value of the right operand is converted to the
8044   // type of the assignment expression.
8045   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8046   // so that we can use references in built-in functions even in C.
8047   // The getNonReferenceType() call makes sure that the resulting expression
8048   // does not have reference type.
8049   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8050     QualType Ty = LHSType.getNonLValueExprType(Context);
8051     Expr *E = RHS.get();
8052 
8053     // Check for various Objective-C errors. If we are not reporting
8054     // diagnostics and just checking for errors, e.g., during overload
8055     // resolution, return Incompatible to indicate the failure.
8056     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8057         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8058                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8059       if (!Diagnose)
8060         return Incompatible;
8061     }
8062     if (getLangOpts().ObjC1 &&
8063         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8064                                            E->getType(), E, Diagnose) ||
8065          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8066       if (!Diagnose)
8067         return Incompatible;
8068       // Replace the expression with a corrected version and continue so we
8069       // can find further errors.
8070       RHS = E;
8071       return Compatible;
8072     }
8073 
8074     if (ConvertRHS)
8075       RHS = ImpCastExprToType(E, Ty, Kind);
8076   }
8077   return result;
8078 }
8079 
8080 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8081                                ExprResult &RHS) {
8082   Diag(Loc, diag::err_typecheck_invalid_operands)
8083     << LHS.get()->getType() << RHS.get()->getType()
8084     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8085   return QualType();
8086 }
8087 
8088 // Diagnose cases where a scalar was implicitly converted to a vector and
8089 // diagnose the underlying types. Otherwise, diagnose the error
8090 // as invalid vector logical operands for non-C++ cases.
8091 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8092                                             ExprResult &RHS) {
8093   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8094   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8095 
8096   bool LHSNatVec = LHSType->isVectorType();
8097   bool RHSNatVec = RHSType->isVectorType();
8098 
8099   if (!(LHSNatVec && RHSNatVec)) {
8100     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8101     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8102     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8103         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8104         << Vector->getSourceRange();
8105     return QualType();
8106   }
8107 
8108   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8109       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8110       << RHS.get()->getSourceRange();
8111 
8112   return QualType();
8113 }
8114 
8115 /// Try to convert a value of non-vector type to a vector type by converting
8116 /// the type to the element type of the vector and then performing a splat.
8117 /// If the language is OpenCL, we only use conversions that promote scalar
8118 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8119 /// for float->int.
8120 ///
8121 /// OpenCL V2.0 6.2.6.p2:
8122 /// An error shall occur if any scalar operand type has greater rank
8123 /// than the type of the vector element.
8124 ///
8125 /// \param scalar - if non-null, actually perform the conversions
8126 /// \return true if the operation fails (but without diagnosing the failure)
8127 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8128                                      QualType scalarTy,
8129                                      QualType vectorEltTy,
8130                                      QualType vectorTy,
8131                                      unsigned &DiagID) {
8132   // The conversion to apply to the scalar before splatting it,
8133   // if necessary.
8134   CastKind scalarCast = CK_NoOp;
8135 
8136   if (vectorEltTy->isIntegralType(S.Context)) {
8137     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8138         (scalarTy->isIntegerType() &&
8139          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8140       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8141       return true;
8142     }
8143     if (!scalarTy->isIntegralType(S.Context))
8144       return true;
8145     scalarCast = CK_IntegralCast;
8146   } else if (vectorEltTy->isRealFloatingType()) {
8147     if (scalarTy->isRealFloatingType()) {
8148       if (S.getLangOpts().OpenCL &&
8149           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8150         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8151         return true;
8152       }
8153       scalarCast = CK_FloatingCast;
8154     }
8155     else if (scalarTy->isIntegralType(S.Context))
8156       scalarCast = CK_IntegralToFloating;
8157     else
8158       return true;
8159   } else {
8160     return true;
8161   }
8162 
8163   // Adjust scalar if desired.
8164   if (scalar) {
8165     if (scalarCast != CK_NoOp)
8166       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8167     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8168   }
8169   return false;
8170 }
8171 
8172 /// Convert vector E to a vector with the same number of elements but different
8173 /// element type.
8174 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8175   const auto *VecTy = E->getType()->getAs<VectorType>();
8176   assert(VecTy && "Expression E must be a vector");
8177   QualType NewVecTy = S.Context.getVectorType(ElementType,
8178                                               VecTy->getNumElements(),
8179                                               VecTy->getVectorKind());
8180 
8181   // Look through the implicit cast. Return the subexpression if its type is
8182   // NewVecTy.
8183   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8184     if (ICE->getSubExpr()->getType() == NewVecTy)
8185       return ICE->getSubExpr();
8186 
8187   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8188   return S.ImpCastExprToType(E, NewVecTy, Cast);
8189 }
8190 
8191 /// Test if a (constant) integer Int can be casted to another integer type
8192 /// IntTy without losing precision.
8193 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8194                                       QualType OtherIntTy) {
8195   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8196 
8197   // Reject cases where the value of the Int is unknown as that would
8198   // possibly cause truncation, but accept cases where the scalar can be
8199   // demoted without loss of precision.
8200   llvm::APSInt Result;
8201   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8202   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8203   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8204   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8205 
8206   if (CstInt) {
8207     // If the scalar is constant and is of a higher order and has more active
8208     // bits that the vector element type, reject it.
8209     unsigned NumBits = IntSigned
8210                            ? (Result.isNegative() ? Result.getMinSignedBits()
8211                                                   : Result.getActiveBits())
8212                            : Result.getActiveBits();
8213     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8214       return true;
8215 
8216     // If the signedness of the scalar type and the vector element type
8217     // differs and the number of bits is greater than that of the vector
8218     // element reject it.
8219     return (IntSigned != OtherIntSigned &&
8220             NumBits > S.Context.getIntWidth(OtherIntTy));
8221   }
8222 
8223   // Reject cases where the value of the scalar is not constant and it's
8224   // order is greater than that of the vector element type.
8225   return (Order < 0);
8226 }
8227 
8228 /// Test if a (constant) integer Int can be casted to floating point type
8229 /// FloatTy without losing precision.
8230 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8231                                      QualType FloatTy) {
8232   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8233 
8234   // Determine if the integer constant can be expressed as a floating point
8235   // number of the appropriate type.
8236   llvm::APSInt Result;
8237   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8238   uint64_t Bits = 0;
8239   if (CstInt) {
8240     // Reject constants that would be truncated if they were converted to
8241     // the floating point type. Test by simple to/from conversion.
8242     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8243     //        could be avoided if there was a convertFromAPInt method
8244     //        which could signal back if implicit truncation occurred.
8245     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8246     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8247                            llvm::APFloat::rmTowardZero);
8248     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8249                              !IntTy->hasSignedIntegerRepresentation());
8250     bool Ignored = false;
8251     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8252                            &Ignored);
8253     if (Result != ConvertBack)
8254       return true;
8255   } else {
8256     // Reject types that cannot be fully encoded into the mantissa of
8257     // the float.
8258     Bits = S.Context.getTypeSize(IntTy);
8259     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8260         S.Context.getFloatTypeSemantics(FloatTy));
8261     if (Bits > FloatPrec)
8262       return true;
8263   }
8264 
8265   return false;
8266 }
8267 
8268 /// Attempt to convert and splat Scalar into a vector whose types matches
8269 /// Vector following GCC conversion rules. The rule is that implicit
8270 /// conversion can occur when Scalar can be casted to match Vector's element
8271 /// type without causing truncation of Scalar.
8272 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8273                                         ExprResult *Vector) {
8274   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8275   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8276   const VectorType *VT = VectorTy->getAs<VectorType>();
8277 
8278   assert(!isa<ExtVectorType>(VT) &&
8279          "ExtVectorTypes should not be handled here!");
8280 
8281   QualType VectorEltTy = VT->getElementType();
8282 
8283   // Reject cases where the vector element type or the scalar element type are
8284   // not integral or floating point types.
8285   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8286     return true;
8287 
8288   // The conversion to apply to the scalar before splatting it,
8289   // if necessary.
8290   CastKind ScalarCast = CK_NoOp;
8291 
8292   // Accept cases where the vector elements are integers and the scalar is
8293   // an integer.
8294   // FIXME: Notionally if the scalar was a floating point value with a precise
8295   //        integral representation, we could cast it to an appropriate integer
8296   //        type and then perform the rest of the checks here. GCC will perform
8297   //        this conversion in some cases as determined by the input language.
8298   //        We should accept it on a language independent basis.
8299   if (VectorEltTy->isIntegralType(S.Context) &&
8300       ScalarTy->isIntegralType(S.Context) &&
8301       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8302 
8303     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8304       return true;
8305 
8306     ScalarCast = CK_IntegralCast;
8307   } else if (VectorEltTy->isRealFloatingType()) {
8308     if (ScalarTy->isRealFloatingType()) {
8309 
8310       // Reject cases where the scalar type is not a constant and has a higher
8311       // Order than the vector element type.
8312       llvm::APFloat Result(0.0);
8313       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8314       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8315       if (!CstScalar && Order < 0)
8316         return true;
8317 
8318       // If the scalar cannot be safely casted to the vector element type,
8319       // reject it.
8320       if (CstScalar) {
8321         bool Truncated = false;
8322         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8323                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8324         if (Truncated)
8325           return true;
8326       }
8327 
8328       ScalarCast = CK_FloatingCast;
8329     } else if (ScalarTy->isIntegralType(S.Context)) {
8330       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8331         return true;
8332 
8333       ScalarCast = CK_IntegralToFloating;
8334     } else
8335       return true;
8336   }
8337 
8338   // Adjust scalar if desired.
8339   if (Scalar) {
8340     if (ScalarCast != CK_NoOp)
8341       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8342     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8343   }
8344   return false;
8345 }
8346 
8347 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8348                                    SourceLocation Loc, bool IsCompAssign,
8349                                    bool AllowBothBool,
8350                                    bool AllowBoolConversions) {
8351   if (!IsCompAssign) {
8352     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8353     if (LHS.isInvalid())
8354       return QualType();
8355   }
8356   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8357   if (RHS.isInvalid())
8358     return QualType();
8359 
8360   // For conversion purposes, we ignore any qualifiers.
8361   // For example, "const float" and "float" are equivalent.
8362   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8363   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8364 
8365   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8366   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8367   assert(LHSVecType || RHSVecType);
8368 
8369   // AltiVec-style "vector bool op vector bool" combinations are allowed
8370   // for some operators but not others.
8371   if (!AllowBothBool &&
8372       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8373       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8374     return InvalidOperands(Loc, LHS, RHS);
8375 
8376   // If the vector types are identical, return.
8377   if (Context.hasSameType(LHSType, RHSType))
8378     return LHSType;
8379 
8380   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8381   if (LHSVecType && RHSVecType &&
8382       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8383     if (isa<ExtVectorType>(LHSVecType)) {
8384       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8385       return LHSType;
8386     }
8387 
8388     if (!IsCompAssign)
8389       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8390     return RHSType;
8391   }
8392 
8393   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8394   // can be mixed, with the result being the non-bool type.  The non-bool
8395   // operand must have integer element type.
8396   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8397       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8398       (Context.getTypeSize(LHSVecType->getElementType()) ==
8399        Context.getTypeSize(RHSVecType->getElementType()))) {
8400     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8401         LHSVecType->getElementType()->isIntegerType() &&
8402         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8403       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8404       return LHSType;
8405     }
8406     if (!IsCompAssign &&
8407         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8408         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8409         RHSVecType->getElementType()->isIntegerType()) {
8410       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8411       return RHSType;
8412     }
8413   }
8414 
8415   // If there's a vector type and a scalar, try to convert the scalar to
8416   // the vector element type and splat.
8417   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8418   if (!RHSVecType) {
8419     if (isa<ExtVectorType>(LHSVecType)) {
8420       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8421                                     LHSVecType->getElementType(), LHSType,
8422                                     DiagID))
8423         return LHSType;
8424     } else {
8425       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8426         return LHSType;
8427     }
8428   }
8429   if (!LHSVecType) {
8430     if (isa<ExtVectorType>(RHSVecType)) {
8431       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8432                                     LHSType, RHSVecType->getElementType(),
8433                                     RHSType, DiagID))
8434         return RHSType;
8435     } else {
8436       if (LHS.get()->getValueKind() == VK_LValue ||
8437           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8438         return RHSType;
8439     }
8440   }
8441 
8442   // FIXME: The code below also handles conversion between vectors and
8443   // non-scalars, we should break this down into fine grained specific checks
8444   // and emit proper diagnostics.
8445   QualType VecType = LHSVecType ? LHSType : RHSType;
8446   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8447   QualType OtherType = LHSVecType ? RHSType : LHSType;
8448   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8449   if (isLaxVectorConversion(OtherType, VecType)) {
8450     // If we're allowing lax vector conversions, only the total (data) size
8451     // needs to be the same. For non compound assignment, if one of the types is
8452     // scalar, the result is always the vector type.
8453     if (!IsCompAssign) {
8454       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8455       return VecType;
8456     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8457     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8458     // type. Note that this is already done by non-compound assignments in
8459     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8460     // <1 x T> -> T. The result is also a vector type.
8461     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8462                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8463       ExprResult *RHSExpr = &RHS;
8464       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8465       return VecType;
8466     }
8467   }
8468 
8469   // Okay, the expression is invalid.
8470 
8471   // If there's a non-vector, non-real operand, diagnose that.
8472   if ((!RHSVecType && !RHSType->isRealType()) ||
8473       (!LHSVecType && !LHSType->isRealType())) {
8474     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8475       << LHSType << RHSType
8476       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8477     return QualType();
8478   }
8479 
8480   // OpenCL V1.1 6.2.6.p1:
8481   // If the operands are of more than one vector type, then an error shall
8482   // occur. Implicit conversions between vector types are not permitted, per
8483   // section 6.2.1.
8484   if (getLangOpts().OpenCL &&
8485       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8486       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8487     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8488                                                            << RHSType;
8489     return QualType();
8490   }
8491 
8492 
8493   // If there is a vector type that is not a ExtVector and a scalar, we reach
8494   // this point if scalar could not be converted to the vector's element type
8495   // without truncation.
8496   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8497       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8498     QualType Scalar = LHSVecType ? RHSType : LHSType;
8499     QualType Vector = LHSVecType ? LHSType : RHSType;
8500     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8501     Diag(Loc,
8502          diag::err_typecheck_vector_not_convertable_implict_truncation)
8503         << ScalarOrVector << Scalar << Vector;
8504 
8505     return QualType();
8506   }
8507 
8508   // Otherwise, use the generic diagnostic.
8509   Diag(Loc, DiagID)
8510     << LHSType << RHSType
8511     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8512   return QualType();
8513 }
8514 
8515 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8516 // expression.  These are mainly cases where the null pointer is used as an
8517 // integer instead of a pointer.
8518 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8519                                 SourceLocation Loc, bool IsCompare) {
8520   // The canonical way to check for a GNU null is with isNullPointerConstant,
8521   // but we use a bit of a hack here for speed; this is a relatively
8522   // hot path, and isNullPointerConstant is slow.
8523   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8524   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8525 
8526   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8527 
8528   // Avoid analyzing cases where the result will either be invalid (and
8529   // diagnosed as such) or entirely valid and not something to warn about.
8530   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8531       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8532     return;
8533 
8534   // Comparison operations would not make sense with a null pointer no matter
8535   // what the other expression is.
8536   if (!IsCompare) {
8537     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8538         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8539         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8540     return;
8541   }
8542 
8543   // The rest of the operations only make sense with a null pointer
8544   // if the other expression is a pointer.
8545   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8546       NonNullType->canDecayToPointerType())
8547     return;
8548 
8549   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8550       << LHSNull /* LHS is NULL */ << NonNullType
8551       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8552 }
8553 
8554 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8555                                                ExprResult &RHS,
8556                                                SourceLocation Loc, bool IsDiv) {
8557   // Check for division/remainder by zero.
8558   llvm::APSInt RHSValue;
8559   if (!RHS.get()->isValueDependent() &&
8560       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8561     S.DiagRuntimeBehavior(Loc, RHS.get(),
8562                           S.PDiag(diag::warn_remainder_division_by_zero)
8563                             << IsDiv << RHS.get()->getSourceRange());
8564 }
8565 
8566 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8567                                            SourceLocation Loc,
8568                                            bool IsCompAssign, bool IsDiv) {
8569   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8570 
8571   if (LHS.get()->getType()->isVectorType() ||
8572       RHS.get()->getType()->isVectorType())
8573     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8574                                /*AllowBothBool*/getLangOpts().AltiVec,
8575                                /*AllowBoolConversions*/false);
8576 
8577   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8578   if (LHS.isInvalid() || RHS.isInvalid())
8579     return QualType();
8580 
8581 
8582   if (compType.isNull() || !compType->isArithmeticType())
8583     return InvalidOperands(Loc, LHS, RHS);
8584   if (IsDiv)
8585     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8586   return compType;
8587 }
8588 
8589 QualType Sema::CheckRemainderOperands(
8590   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8591   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8592 
8593   if (LHS.get()->getType()->isVectorType() ||
8594       RHS.get()->getType()->isVectorType()) {
8595     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8596         RHS.get()->getType()->hasIntegerRepresentation())
8597       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8598                                  /*AllowBothBool*/getLangOpts().AltiVec,
8599                                  /*AllowBoolConversions*/false);
8600     return InvalidOperands(Loc, LHS, RHS);
8601   }
8602 
8603   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8604   if (LHS.isInvalid() || RHS.isInvalid())
8605     return QualType();
8606 
8607   if (compType.isNull() || !compType->isIntegerType())
8608     return InvalidOperands(Loc, LHS, RHS);
8609   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8610   return compType;
8611 }
8612 
8613 /// \brief Diagnose invalid arithmetic on two void pointers.
8614 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8615                                                 Expr *LHSExpr, Expr *RHSExpr) {
8616   S.Diag(Loc, S.getLangOpts().CPlusPlus
8617                 ? diag::err_typecheck_pointer_arith_void_type
8618                 : diag::ext_gnu_void_ptr)
8619     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8620                             << RHSExpr->getSourceRange();
8621 }
8622 
8623 /// \brief Diagnose invalid arithmetic on a void pointer.
8624 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8625                                             Expr *Pointer) {
8626   S.Diag(Loc, S.getLangOpts().CPlusPlus
8627                 ? diag::err_typecheck_pointer_arith_void_type
8628                 : diag::ext_gnu_void_ptr)
8629     << 0 /* one pointer */ << Pointer->getSourceRange();
8630 }
8631 
8632 /// \brief Diagnose invalid arithmetic on a null pointer.
8633 ///
8634 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8635 /// idiom, which we recognize as a GNU extension.
8636 ///
8637 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8638                                             Expr *Pointer, bool IsGNUIdiom) {
8639   if (IsGNUIdiom)
8640     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8641       << Pointer->getSourceRange();
8642   else
8643     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8644       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8645 }
8646 
8647 /// \brief Diagnose invalid arithmetic on two function pointers.
8648 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8649                                                     Expr *LHS, Expr *RHS) {
8650   assert(LHS->getType()->isAnyPointerType());
8651   assert(RHS->getType()->isAnyPointerType());
8652   S.Diag(Loc, S.getLangOpts().CPlusPlus
8653                 ? diag::err_typecheck_pointer_arith_function_type
8654                 : diag::ext_gnu_ptr_func_arith)
8655     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8656     // We only show the second type if it differs from the first.
8657     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8658                                                    RHS->getType())
8659     << RHS->getType()->getPointeeType()
8660     << LHS->getSourceRange() << RHS->getSourceRange();
8661 }
8662 
8663 /// \brief Diagnose invalid arithmetic on a function pointer.
8664 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8665                                                 Expr *Pointer) {
8666   assert(Pointer->getType()->isAnyPointerType());
8667   S.Diag(Loc, S.getLangOpts().CPlusPlus
8668                 ? diag::err_typecheck_pointer_arith_function_type
8669                 : diag::ext_gnu_ptr_func_arith)
8670     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8671     << 0 /* one pointer, so only one type */
8672     << Pointer->getSourceRange();
8673 }
8674 
8675 /// \brief Emit error if Operand is incomplete pointer type
8676 ///
8677 /// \returns True if pointer has incomplete type
8678 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8679                                                  Expr *Operand) {
8680   QualType ResType = Operand->getType();
8681   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8682     ResType = ResAtomicType->getValueType();
8683 
8684   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8685   QualType PointeeTy = ResType->getPointeeType();
8686   return S.RequireCompleteType(Loc, PointeeTy,
8687                                diag::err_typecheck_arithmetic_incomplete_type,
8688                                PointeeTy, Operand->getSourceRange());
8689 }
8690 
8691 /// \brief Check the validity of an arithmetic pointer operand.
8692 ///
8693 /// If the operand has pointer type, this code will check for pointer types
8694 /// which are invalid in arithmetic operations. These will be diagnosed
8695 /// appropriately, including whether or not the use is supported as an
8696 /// extension.
8697 ///
8698 /// \returns True when the operand is valid to use (even if as an extension).
8699 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8700                                             Expr *Operand) {
8701   QualType ResType = Operand->getType();
8702   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8703     ResType = ResAtomicType->getValueType();
8704 
8705   if (!ResType->isAnyPointerType()) return true;
8706 
8707   QualType PointeeTy = ResType->getPointeeType();
8708   if (PointeeTy->isVoidType()) {
8709     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8710     return !S.getLangOpts().CPlusPlus;
8711   }
8712   if (PointeeTy->isFunctionType()) {
8713     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8714     return !S.getLangOpts().CPlusPlus;
8715   }
8716 
8717   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8718 
8719   return true;
8720 }
8721 
8722 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8723 /// operands.
8724 ///
8725 /// This routine will diagnose any invalid arithmetic on pointer operands much
8726 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8727 /// for emitting a single diagnostic even for operations where both LHS and RHS
8728 /// are (potentially problematic) pointers.
8729 ///
8730 /// \returns True when the operand is valid to use (even if as an extension).
8731 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8732                                                 Expr *LHSExpr, Expr *RHSExpr) {
8733   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8734   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8735   if (!isLHSPointer && !isRHSPointer) return true;
8736 
8737   QualType LHSPointeeTy, RHSPointeeTy;
8738   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8739   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8740 
8741   // if both are pointers check if operation is valid wrt address spaces
8742   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8743     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8744     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8745     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8746       S.Diag(Loc,
8747              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8748           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8749           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8750       return false;
8751     }
8752   }
8753 
8754   // Check for arithmetic on pointers to incomplete types.
8755   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8756   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8757   if (isLHSVoidPtr || isRHSVoidPtr) {
8758     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8759     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8760     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8761 
8762     return !S.getLangOpts().CPlusPlus;
8763   }
8764 
8765   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8766   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8767   if (isLHSFuncPtr || isRHSFuncPtr) {
8768     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8769     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8770                                                                 RHSExpr);
8771     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8772 
8773     return !S.getLangOpts().CPlusPlus;
8774   }
8775 
8776   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8777     return false;
8778   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8779     return false;
8780 
8781   return true;
8782 }
8783 
8784 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8785 /// literal.
8786 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8787                                   Expr *LHSExpr, Expr *RHSExpr) {
8788   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8789   Expr* IndexExpr = RHSExpr;
8790   if (!StrExpr) {
8791     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8792     IndexExpr = LHSExpr;
8793   }
8794 
8795   bool IsStringPlusInt = StrExpr &&
8796       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8797   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8798     return;
8799 
8800   llvm::APSInt index;
8801   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8802     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8803     if (index.isNonNegative() &&
8804         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8805                               index.isUnsigned()))
8806       return;
8807   }
8808 
8809   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8810   Self.Diag(OpLoc, diag::warn_string_plus_int)
8811       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8812 
8813   // Only print a fixit for "str" + int, not for int + "str".
8814   if (IndexExpr == RHSExpr) {
8815     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8816     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8817         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8818         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8819         << FixItHint::CreateInsertion(EndLoc, "]");
8820   } else
8821     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8822 }
8823 
8824 /// \brief Emit a warning when adding a char literal to a string.
8825 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8826                                    Expr *LHSExpr, Expr *RHSExpr) {
8827   const Expr *StringRefExpr = LHSExpr;
8828   const CharacterLiteral *CharExpr =
8829       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8830 
8831   if (!CharExpr) {
8832     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8833     StringRefExpr = RHSExpr;
8834   }
8835 
8836   if (!CharExpr || !StringRefExpr)
8837     return;
8838 
8839   const QualType StringType = StringRefExpr->getType();
8840 
8841   // Return if not a PointerType.
8842   if (!StringType->isAnyPointerType())
8843     return;
8844 
8845   // Return if not a CharacterType.
8846   if (!StringType->getPointeeType()->isAnyCharacterType())
8847     return;
8848 
8849   ASTContext &Ctx = Self.getASTContext();
8850   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8851 
8852   const QualType CharType = CharExpr->getType();
8853   if (!CharType->isAnyCharacterType() &&
8854       CharType->isIntegerType() &&
8855       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8856     Self.Diag(OpLoc, diag::warn_string_plus_char)
8857         << DiagRange << Ctx.CharTy;
8858   } else {
8859     Self.Diag(OpLoc, diag::warn_string_plus_char)
8860         << DiagRange << CharExpr->getType();
8861   }
8862 
8863   // Only print a fixit for str + char, not for char + str.
8864   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8865     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8866     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8867         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8868         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8869         << FixItHint::CreateInsertion(EndLoc, "]");
8870   } else {
8871     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8872   }
8873 }
8874 
8875 /// \brief Emit error when two pointers are incompatible.
8876 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8877                                            Expr *LHSExpr, Expr *RHSExpr) {
8878   assert(LHSExpr->getType()->isAnyPointerType());
8879   assert(RHSExpr->getType()->isAnyPointerType());
8880   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8881     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8882     << RHSExpr->getSourceRange();
8883 }
8884 
8885 // C99 6.5.6
8886 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8887                                      SourceLocation Loc, BinaryOperatorKind Opc,
8888                                      QualType* CompLHSTy) {
8889   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8890 
8891   if (LHS.get()->getType()->isVectorType() ||
8892       RHS.get()->getType()->isVectorType()) {
8893     QualType compType = CheckVectorOperands(
8894         LHS, RHS, Loc, CompLHSTy,
8895         /*AllowBothBool*/getLangOpts().AltiVec,
8896         /*AllowBoolConversions*/getLangOpts().ZVector);
8897     if (CompLHSTy) *CompLHSTy = compType;
8898     return compType;
8899   }
8900 
8901   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8902   if (LHS.isInvalid() || RHS.isInvalid())
8903     return QualType();
8904 
8905   // Diagnose "string literal" '+' int and string '+' "char literal".
8906   if (Opc == BO_Add) {
8907     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8908     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8909   }
8910 
8911   // handle the common case first (both operands are arithmetic).
8912   if (!compType.isNull() && compType->isArithmeticType()) {
8913     if (CompLHSTy) *CompLHSTy = compType;
8914     return compType;
8915   }
8916 
8917   // Type-checking.  Ultimately the pointer's going to be in PExp;
8918   // note that we bias towards the LHS being the pointer.
8919   Expr *PExp = LHS.get(), *IExp = RHS.get();
8920 
8921   bool isObjCPointer;
8922   if (PExp->getType()->isPointerType()) {
8923     isObjCPointer = false;
8924   } else if (PExp->getType()->isObjCObjectPointerType()) {
8925     isObjCPointer = true;
8926   } else {
8927     std::swap(PExp, IExp);
8928     if (PExp->getType()->isPointerType()) {
8929       isObjCPointer = false;
8930     } else if (PExp->getType()->isObjCObjectPointerType()) {
8931       isObjCPointer = true;
8932     } else {
8933       return InvalidOperands(Loc, LHS, RHS);
8934     }
8935   }
8936   assert(PExp->getType()->isAnyPointerType());
8937 
8938   if (!IExp->getType()->isIntegerType())
8939     return InvalidOperands(Loc, LHS, RHS);
8940 
8941   // Adding to a null pointer results in undefined behavior.
8942   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
8943           Context, Expr::NPC_ValueDependentIsNotNull)) {
8944     // In C++ adding zero to a null pointer is defined.
8945     llvm::APSInt KnownVal;
8946     if (!getLangOpts().CPlusPlus ||
8947         (!IExp->isValueDependent() &&
8948          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
8949       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
8950       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
8951           Context, BO_Add, PExp, IExp);
8952       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
8953     }
8954   }
8955 
8956   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8957     return QualType();
8958 
8959   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8960     return QualType();
8961 
8962   // Check array bounds for pointer arithemtic
8963   CheckArrayAccess(PExp, IExp);
8964 
8965   if (CompLHSTy) {
8966     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8967     if (LHSTy.isNull()) {
8968       LHSTy = LHS.get()->getType();
8969       if (LHSTy->isPromotableIntegerType())
8970         LHSTy = Context.getPromotedIntegerType(LHSTy);
8971     }
8972     *CompLHSTy = LHSTy;
8973   }
8974 
8975   return PExp->getType();
8976 }
8977 
8978 // C99 6.5.6
8979 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8980                                         SourceLocation Loc,
8981                                         QualType* CompLHSTy) {
8982   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8983 
8984   if (LHS.get()->getType()->isVectorType() ||
8985       RHS.get()->getType()->isVectorType()) {
8986     QualType compType = CheckVectorOperands(
8987         LHS, RHS, Loc, CompLHSTy,
8988         /*AllowBothBool*/getLangOpts().AltiVec,
8989         /*AllowBoolConversions*/getLangOpts().ZVector);
8990     if (CompLHSTy) *CompLHSTy = compType;
8991     return compType;
8992   }
8993 
8994   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8995   if (LHS.isInvalid() || RHS.isInvalid())
8996     return QualType();
8997 
8998   // Enforce type constraints: C99 6.5.6p3.
8999 
9000   // Handle the common case first (both operands are arithmetic).
9001   if (!compType.isNull() && compType->isArithmeticType()) {
9002     if (CompLHSTy) *CompLHSTy = compType;
9003     return compType;
9004   }
9005 
9006   // Either ptr - int   or   ptr - ptr.
9007   if (LHS.get()->getType()->isAnyPointerType()) {
9008     QualType lpointee = LHS.get()->getType()->getPointeeType();
9009 
9010     // Diagnose bad cases where we step over interface counts.
9011     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9012         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9013       return QualType();
9014 
9015     // The result type of a pointer-int computation is the pointer type.
9016     if (RHS.get()->getType()->isIntegerType()) {
9017       // Subtracting from a null pointer should produce a warning.
9018       // The last argument to the diagnose call says this doesn't match the
9019       // GNU int-to-pointer idiom.
9020       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9021                                            Expr::NPC_ValueDependentIsNotNull)) {
9022         // In C++ adding zero to a null pointer is defined.
9023         llvm::APSInt KnownVal;
9024         if (!getLangOpts().CPlusPlus ||
9025             (!RHS.get()->isValueDependent() &&
9026              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9027           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9028         }
9029       }
9030 
9031       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9032         return QualType();
9033 
9034       // Check array bounds for pointer arithemtic
9035       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9036                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9037 
9038       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9039       return LHS.get()->getType();
9040     }
9041 
9042     // Handle pointer-pointer subtractions.
9043     if (const PointerType *RHSPTy
9044           = RHS.get()->getType()->getAs<PointerType>()) {
9045       QualType rpointee = RHSPTy->getPointeeType();
9046 
9047       if (getLangOpts().CPlusPlus) {
9048         // Pointee types must be the same: C++ [expr.add]
9049         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9050           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9051         }
9052       } else {
9053         // Pointee types must be compatible C99 6.5.6p3
9054         if (!Context.typesAreCompatible(
9055                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9056                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9057           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9058           return QualType();
9059         }
9060       }
9061 
9062       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9063                                                LHS.get(), RHS.get()))
9064         return QualType();
9065 
9066       // FIXME: Add warnings for nullptr - ptr.
9067 
9068       // The pointee type may have zero size.  As an extension, a structure or
9069       // union may have zero size or an array may have zero length.  In this
9070       // case subtraction does not make sense.
9071       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9072         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9073         if (ElementSize.isZero()) {
9074           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9075             << rpointee.getUnqualifiedType()
9076             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9077         }
9078       }
9079 
9080       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9081       return Context.getPointerDiffType();
9082     }
9083   }
9084 
9085   return InvalidOperands(Loc, LHS, RHS);
9086 }
9087 
9088 static bool isScopedEnumerationType(QualType T) {
9089   if (const EnumType *ET = T->getAs<EnumType>())
9090     return ET->getDecl()->isScoped();
9091   return false;
9092 }
9093 
9094 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9095                                    SourceLocation Loc, BinaryOperatorKind Opc,
9096                                    QualType LHSType) {
9097   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9098   // so skip remaining warnings as we don't want to modify values within Sema.
9099   if (S.getLangOpts().OpenCL)
9100     return;
9101 
9102   llvm::APSInt Right;
9103   // Check right/shifter operand
9104   if (RHS.get()->isValueDependent() ||
9105       !RHS.get()->EvaluateAsInt(Right, S.Context))
9106     return;
9107 
9108   if (Right.isNegative()) {
9109     S.DiagRuntimeBehavior(Loc, RHS.get(),
9110                           S.PDiag(diag::warn_shift_negative)
9111                             << RHS.get()->getSourceRange());
9112     return;
9113   }
9114   llvm::APInt LeftBits(Right.getBitWidth(),
9115                        S.Context.getTypeSize(LHS.get()->getType()));
9116   if (Right.uge(LeftBits)) {
9117     S.DiagRuntimeBehavior(Loc, RHS.get(),
9118                           S.PDiag(diag::warn_shift_gt_typewidth)
9119                             << RHS.get()->getSourceRange());
9120     return;
9121   }
9122   if (Opc != BO_Shl)
9123     return;
9124 
9125   // When left shifting an ICE which is signed, we can check for overflow which
9126   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9127   // integers have defined behavior modulo one more than the maximum value
9128   // representable in the result type, so never warn for those.
9129   llvm::APSInt Left;
9130   if (LHS.get()->isValueDependent() ||
9131       LHSType->hasUnsignedIntegerRepresentation() ||
9132       !LHS.get()->EvaluateAsInt(Left, S.Context))
9133     return;
9134 
9135   // If LHS does not have a signed type and non-negative value
9136   // then, the behavior is undefined. Warn about it.
9137   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9138     S.DiagRuntimeBehavior(Loc, LHS.get(),
9139                           S.PDiag(diag::warn_shift_lhs_negative)
9140                             << LHS.get()->getSourceRange());
9141     return;
9142   }
9143 
9144   llvm::APInt ResultBits =
9145       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9146   if (LeftBits.uge(ResultBits))
9147     return;
9148   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9149   Result = Result.shl(Right);
9150 
9151   // Print the bit representation of the signed integer as an unsigned
9152   // hexadecimal number.
9153   SmallString<40> HexResult;
9154   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9155 
9156   // If we are only missing a sign bit, this is less likely to result in actual
9157   // bugs -- if the result is cast back to an unsigned type, it will have the
9158   // expected value. Thus we place this behind a different warning that can be
9159   // turned off separately if needed.
9160   if (LeftBits == ResultBits - 1) {
9161     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9162         << HexResult << LHSType
9163         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9164     return;
9165   }
9166 
9167   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9168     << HexResult.str() << Result.getMinSignedBits() << LHSType
9169     << Left.getBitWidth() << LHS.get()->getSourceRange()
9170     << RHS.get()->getSourceRange();
9171 }
9172 
9173 /// \brief Return the resulting type when a vector is shifted
9174 ///        by a scalar or vector shift amount.
9175 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9176                                  SourceLocation Loc, bool IsCompAssign) {
9177   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9178   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9179       !LHS.get()->getType()->isVectorType()) {
9180     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9181       << RHS.get()->getType() << LHS.get()->getType()
9182       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9183     return QualType();
9184   }
9185 
9186   if (!IsCompAssign) {
9187     LHS = S.UsualUnaryConversions(LHS.get());
9188     if (LHS.isInvalid()) return QualType();
9189   }
9190 
9191   RHS = S.UsualUnaryConversions(RHS.get());
9192   if (RHS.isInvalid()) return QualType();
9193 
9194   QualType LHSType = LHS.get()->getType();
9195   // Note that LHS might be a scalar because the routine calls not only in
9196   // OpenCL case.
9197   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9198   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9199 
9200   // Note that RHS might not be a vector.
9201   QualType RHSType = RHS.get()->getType();
9202   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9203   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9204 
9205   // The operands need to be integers.
9206   if (!LHSEleType->isIntegerType()) {
9207     S.Diag(Loc, diag::err_typecheck_expect_int)
9208       << LHS.get()->getType() << LHS.get()->getSourceRange();
9209     return QualType();
9210   }
9211 
9212   if (!RHSEleType->isIntegerType()) {
9213     S.Diag(Loc, diag::err_typecheck_expect_int)
9214       << RHS.get()->getType() << RHS.get()->getSourceRange();
9215     return QualType();
9216   }
9217 
9218   if (!LHSVecTy) {
9219     assert(RHSVecTy);
9220     if (IsCompAssign)
9221       return RHSType;
9222     if (LHSEleType != RHSEleType) {
9223       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9224       LHSEleType = RHSEleType;
9225     }
9226     QualType VecTy =
9227         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9228     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9229     LHSType = VecTy;
9230   } else if (RHSVecTy) {
9231     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9232     // are applied component-wise. So if RHS is a vector, then ensure
9233     // that the number of elements is the same as LHS...
9234     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9235       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9236         << LHS.get()->getType() << RHS.get()->getType()
9237         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9238       return QualType();
9239     }
9240     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9241       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9242       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9243       if (LHSBT != RHSBT &&
9244           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9245         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9246             << LHS.get()->getType() << RHS.get()->getType()
9247             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9248       }
9249     }
9250   } else {
9251     // ...else expand RHS to match the number of elements in LHS.
9252     QualType VecTy =
9253       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9254     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9255   }
9256 
9257   return LHSType;
9258 }
9259 
9260 // C99 6.5.7
9261 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9262                                   SourceLocation Loc, BinaryOperatorKind Opc,
9263                                   bool IsCompAssign) {
9264   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9265 
9266   // Vector shifts promote their scalar inputs to vector type.
9267   if (LHS.get()->getType()->isVectorType() ||
9268       RHS.get()->getType()->isVectorType()) {
9269     if (LangOpts.ZVector) {
9270       // The shift operators for the z vector extensions work basically
9271       // like general shifts, except that neither the LHS nor the RHS is
9272       // allowed to be a "vector bool".
9273       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9274         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9275           return InvalidOperands(Loc, LHS, RHS);
9276       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9277         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9278           return InvalidOperands(Loc, LHS, RHS);
9279     }
9280     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9281   }
9282 
9283   // Shifts don't perform usual arithmetic conversions, they just do integer
9284   // promotions on each operand. C99 6.5.7p3
9285 
9286   // For the LHS, do usual unary conversions, but then reset them away
9287   // if this is a compound assignment.
9288   ExprResult OldLHS = LHS;
9289   LHS = UsualUnaryConversions(LHS.get());
9290   if (LHS.isInvalid())
9291     return QualType();
9292   QualType LHSType = LHS.get()->getType();
9293   if (IsCompAssign) LHS = OldLHS;
9294 
9295   // The RHS is simpler.
9296   RHS = UsualUnaryConversions(RHS.get());
9297   if (RHS.isInvalid())
9298     return QualType();
9299   QualType RHSType = RHS.get()->getType();
9300 
9301   // C99 6.5.7p2: Each of the operands shall have integer type.
9302   if (!LHSType->hasIntegerRepresentation() ||
9303       !RHSType->hasIntegerRepresentation())
9304     return InvalidOperands(Loc, LHS, RHS);
9305 
9306   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9307   // hasIntegerRepresentation() above instead of this.
9308   if (isScopedEnumerationType(LHSType) ||
9309       isScopedEnumerationType(RHSType)) {
9310     return InvalidOperands(Loc, LHS, RHS);
9311   }
9312   // Sanity-check shift operands
9313   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9314 
9315   // "The type of the result is that of the promoted left operand."
9316   return LHSType;
9317 }
9318 
9319 /// If two different enums are compared, raise a warning.
9320 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9321                                 Expr *RHS) {
9322   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9323   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9324 
9325   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9326   if (!LHSEnumType)
9327     return;
9328   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9329   if (!RHSEnumType)
9330     return;
9331 
9332   // Ignore anonymous enums.
9333   if (!LHSEnumType->getDecl()->getIdentifier() &&
9334       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9335     return;
9336   if (!RHSEnumType->getDecl()->getIdentifier() &&
9337       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9338     return;
9339 
9340   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9341     return;
9342 
9343   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9344       << LHSStrippedType << RHSStrippedType
9345       << LHS->getSourceRange() << RHS->getSourceRange();
9346 }
9347 
9348 /// \brief Diagnose bad pointer comparisons.
9349 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9350                                               ExprResult &LHS, ExprResult &RHS,
9351                                               bool IsError) {
9352   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9353                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9354     << LHS.get()->getType() << RHS.get()->getType()
9355     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9356 }
9357 
9358 /// \brief Returns false if the pointers are converted to a composite type,
9359 /// true otherwise.
9360 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9361                                            ExprResult &LHS, ExprResult &RHS) {
9362   // C++ [expr.rel]p2:
9363   //   [...] Pointer conversions (4.10) and qualification
9364   //   conversions (4.4) are performed on pointer operands (or on
9365   //   a pointer operand and a null pointer constant) to bring
9366   //   them to their composite pointer type. [...]
9367   //
9368   // C++ [expr.eq]p1 uses the same notion for (in)equality
9369   // comparisons of pointers.
9370 
9371   QualType LHSType = LHS.get()->getType();
9372   QualType RHSType = RHS.get()->getType();
9373   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9374          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9375 
9376   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9377   if (T.isNull()) {
9378     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9379         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9380       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9381     else
9382       S.InvalidOperands(Loc, LHS, RHS);
9383     return true;
9384   }
9385 
9386   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9387   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9388   return false;
9389 }
9390 
9391 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9392                                                     ExprResult &LHS,
9393                                                     ExprResult &RHS,
9394                                                     bool IsError) {
9395   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9396                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9397     << LHS.get()->getType() << RHS.get()->getType()
9398     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9399 }
9400 
9401 static bool isObjCObjectLiteral(ExprResult &E) {
9402   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9403   case Stmt::ObjCArrayLiteralClass:
9404   case Stmt::ObjCDictionaryLiteralClass:
9405   case Stmt::ObjCStringLiteralClass:
9406   case Stmt::ObjCBoxedExprClass:
9407     return true;
9408   default:
9409     // Note that ObjCBoolLiteral is NOT an object literal!
9410     return false;
9411   }
9412 }
9413 
9414 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9415   const ObjCObjectPointerType *Type =
9416     LHS->getType()->getAs<ObjCObjectPointerType>();
9417 
9418   // If this is not actually an Objective-C object, bail out.
9419   if (!Type)
9420     return false;
9421 
9422   // Get the LHS object's interface type.
9423   QualType InterfaceType = Type->getPointeeType();
9424 
9425   // If the RHS isn't an Objective-C object, bail out.
9426   if (!RHS->getType()->isObjCObjectPointerType())
9427     return false;
9428 
9429   // Try to find the -isEqual: method.
9430   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9431   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9432                                                       InterfaceType,
9433                                                       /*instance=*/true);
9434   if (!Method) {
9435     if (Type->isObjCIdType()) {
9436       // For 'id', just check the global pool.
9437       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9438                                                   /*receiverId=*/true);
9439     } else {
9440       // Check protocols.
9441       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9442                                              /*instance=*/true);
9443     }
9444   }
9445 
9446   if (!Method)
9447     return false;
9448 
9449   QualType T = Method->parameters()[0]->getType();
9450   if (!T->isObjCObjectPointerType())
9451     return false;
9452 
9453   QualType R = Method->getReturnType();
9454   if (!R->isScalarType())
9455     return false;
9456 
9457   return true;
9458 }
9459 
9460 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9461   FromE = FromE->IgnoreParenImpCasts();
9462   switch (FromE->getStmtClass()) {
9463     default:
9464       break;
9465     case Stmt::ObjCStringLiteralClass:
9466       // "string literal"
9467       return LK_String;
9468     case Stmt::ObjCArrayLiteralClass:
9469       // "array literal"
9470       return LK_Array;
9471     case Stmt::ObjCDictionaryLiteralClass:
9472       // "dictionary literal"
9473       return LK_Dictionary;
9474     case Stmt::BlockExprClass:
9475       return LK_Block;
9476     case Stmt::ObjCBoxedExprClass: {
9477       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9478       switch (Inner->getStmtClass()) {
9479         case Stmt::IntegerLiteralClass:
9480         case Stmt::FloatingLiteralClass:
9481         case Stmt::CharacterLiteralClass:
9482         case Stmt::ObjCBoolLiteralExprClass:
9483         case Stmt::CXXBoolLiteralExprClass:
9484           // "numeric literal"
9485           return LK_Numeric;
9486         case Stmt::ImplicitCastExprClass: {
9487           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9488           // Boolean literals can be represented by implicit casts.
9489           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9490             return LK_Numeric;
9491           break;
9492         }
9493         default:
9494           break;
9495       }
9496       return LK_Boxed;
9497     }
9498   }
9499   return LK_None;
9500 }
9501 
9502 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9503                                           ExprResult &LHS, ExprResult &RHS,
9504                                           BinaryOperator::Opcode Opc){
9505   Expr *Literal;
9506   Expr *Other;
9507   if (isObjCObjectLiteral(LHS)) {
9508     Literal = LHS.get();
9509     Other = RHS.get();
9510   } else {
9511     Literal = RHS.get();
9512     Other = LHS.get();
9513   }
9514 
9515   // Don't warn on comparisons against nil.
9516   Other = Other->IgnoreParenCasts();
9517   if (Other->isNullPointerConstant(S.getASTContext(),
9518                                    Expr::NPC_ValueDependentIsNotNull))
9519     return;
9520 
9521   // This should be kept in sync with warn_objc_literal_comparison.
9522   // LK_String should always be after the other literals, since it has its own
9523   // warning flag.
9524   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9525   assert(LiteralKind != Sema::LK_Block);
9526   if (LiteralKind == Sema::LK_None) {
9527     llvm_unreachable("Unknown Objective-C object literal kind");
9528   }
9529 
9530   if (LiteralKind == Sema::LK_String)
9531     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9532       << Literal->getSourceRange();
9533   else
9534     S.Diag(Loc, diag::warn_objc_literal_comparison)
9535       << LiteralKind << Literal->getSourceRange();
9536 
9537   if (BinaryOperator::isEqualityOp(Opc) &&
9538       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9539     SourceLocation Start = LHS.get()->getLocStart();
9540     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9541     CharSourceRange OpRange =
9542       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9543 
9544     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9545       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9546       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9547       << FixItHint::CreateInsertion(End, "]");
9548   }
9549 }
9550 
9551 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9552 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9553                                            ExprResult &RHS, SourceLocation Loc,
9554                                            BinaryOperatorKind Opc) {
9555   // Check that left hand side is !something.
9556   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9557   if (!UO || UO->getOpcode() != UO_LNot) return;
9558 
9559   // Only check if the right hand side is non-bool arithmetic type.
9560   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9561 
9562   // Make sure that the something in !something is not bool.
9563   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9564   if (SubExpr->isKnownToHaveBooleanValue()) return;
9565 
9566   // Emit warning.
9567   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9568   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9569       << Loc << IsBitwiseOp;
9570 
9571   // First note suggest !(x < y)
9572   SourceLocation FirstOpen = SubExpr->getLocStart();
9573   SourceLocation FirstClose = RHS.get()->getLocEnd();
9574   FirstClose = S.getLocForEndOfToken(FirstClose);
9575   if (FirstClose.isInvalid())
9576     FirstOpen = SourceLocation();
9577   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9578       << IsBitwiseOp
9579       << FixItHint::CreateInsertion(FirstOpen, "(")
9580       << FixItHint::CreateInsertion(FirstClose, ")");
9581 
9582   // Second note suggests (!x) < y
9583   SourceLocation SecondOpen = LHS.get()->getLocStart();
9584   SourceLocation SecondClose = LHS.get()->getLocEnd();
9585   SecondClose = S.getLocForEndOfToken(SecondClose);
9586   if (SecondClose.isInvalid())
9587     SecondOpen = SourceLocation();
9588   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9589       << FixItHint::CreateInsertion(SecondOpen, "(")
9590       << FixItHint::CreateInsertion(SecondClose, ")");
9591 }
9592 
9593 // Get the decl for a simple expression: a reference to a variable,
9594 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9595 static ValueDecl *getCompareDecl(Expr *E) {
9596   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9597     return DR->getDecl();
9598   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9599     if (Ivar->isFreeIvar())
9600       return Ivar->getDecl();
9601   }
9602   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9603     if (Mem->isImplicitAccess())
9604       return Mem->getMemberDecl();
9605   }
9606   return nullptr;
9607 }
9608 
9609 /// Diagnose some forms of syntactically-obvious tautological comparison.
9610 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9611                                            Expr *LHS, Expr *RHS,
9612                                            BinaryOperatorKind Opc) {
9613   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9614   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9615 
9616   QualType LHSType = LHS->getType();
9617   if (LHSType->hasFloatingRepresentation() ||
9618       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9619       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9620       S.inTemplateInstantiation())
9621     return;
9622 
9623   // For non-floating point types, check for self-comparisons of the form
9624   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9625   // often indicate logic errors in the program.
9626   //
9627   // NOTE: Don't warn about comparison expressions resulting from macro
9628   // expansion. Also don't warn about comparisons which are only self
9629   // comparisons within a template instantiation. The warnings should catch
9630   // obvious cases in the definition of the template anyways. The idea is to
9631   // warn when the typed comparison operator will always evaluate to the same
9632   // result.
9633   ValueDecl *DL = getCompareDecl(LHSStripped);
9634   ValueDecl *DR = getCompareDecl(RHSStripped);
9635   if (DL && DR && declaresSameEntity(DL, DR)) {
9636     StringRef Result;
9637     switch (Opc) {
9638     case BO_EQ: case BO_LE: case BO_GE:
9639       Result = "true";
9640       break;
9641     case BO_NE: case BO_LT: case BO_GT:
9642       Result = "false";
9643       break;
9644     case BO_Cmp:
9645       Result = "'std::strong_ordering::equal'";
9646       break;
9647     default:
9648       break;
9649     }
9650     S.DiagRuntimeBehavior(Loc, nullptr,
9651                           S.PDiag(diag::warn_comparison_always)
9652                               << 0 /*self-comparison*/ << !Result.empty()
9653                               << Result);
9654   } else if (DL && DR &&
9655              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9656              !DL->isWeak() && !DR->isWeak()) {
9657     // What is it always going to evaluate to?
9658     StringRef Result;
9659     switch(Opc) {
9660     case BO_EQ: // e.g. array1 == array2
9661       Result = "false";
9662       break;
9663     case BO_NE: // e.g. array1 != array2
9664       Result = "true";
9665       break;
9666     default: // e.g. array1 <= array2
9667       // The best we can say is 'a constant'
9668       break;
9669     }
9670     S.DiagRuntimeBehavior(Loc, nullptr,
9671                           S.PDiag(diag::warn_comparison_always)
9672                               << 1 /*array comparison*/
9673                               << !Result.empty() << Result);
9674   }
9675 
9676   if (isa<CastExpr>(LHSStripped))
9677     LHSStripped = LHSStripped->IgnoreParenCasts();
9678   if (isa<CastExpr>(RHSStripped))
9679     RHSStripped = RHSStripped->IgnoreParenCasts();
9680 
9681   // Warn about comparisons against a string constant (unless the other
9682   // operand is null); the user probably wants strcmp.
9683   Expr *LiteralString = nullptr;
9684   Expr *LiteralStringStripped = nullptr;
9685   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9686       !RHSStripped->isNullPointerConstant(S.Context,
9687                                           Expr::NPC_ValueDependentIsNull)) {
9688     LiteralString = LHS;
9689     LiteralStringStripped = LHSStripped;
9690   } else if ((isa<StringLiteral>(RHSStripped) ||
9691               isa<ObjCEncodeExpr>(RHSStripped)) &&
9692              !LHSStripped->isNullPointerConstant(S.Context,
9693                                           Expr::NPC_ValueDependentIsNull)) {
9694     LiteralString = RHS;
9695     LiteralStringStripped = RHSStripped;
9696   }
9697 
9698   if (LiteralString) {
9699     S.DiagRuntimeBehavior(Loc, nullptr,
9700                           S.PDiag(diag::warn_stringcompare)
9701                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9702                               << LiteralString->getSourceRange());
9703   }
9704 }
9705 
9706 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9707                                                  ExprResult &RHS,
9708                                                  SourceLocation Loc,
9709                                                  BinaryOperatorKind Opc) {
9710   // C99 6.5.8p3 / C99 6.5.9p4
9711   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9712   if (LHS.isInvalid() || RHS.isInvalid())
9713     return QualType();
9714   if (Type.isNull())
9715     return S.InvalidOperands(Loc, LHS, RHS);
9716   assert(Type->isArithmeticType() || Type->isEnumeralType());
9717 
9718   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
9719 
9720   enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering;
9721   if (Type->isAnyComplexType())
9722     Ordering = StrongEquality;
9723   else if (Type->isFloatingType())
9724     Ordering = PartialOrdering;
9725   else
9726     Ordering = StrongOrdering;
9727 
9728   if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc))
9729     return S.InvalidOperands(Loc, LHS, RHS);
9730 
9731   // Check for comparisons of floating point operands using != and ==.
9732   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
9733     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
9734 
9735   // The result of comparisons is 'bool' in C++, 'int' in C.
9736   // FIXME: For BO_Cmp, return the relevant comparison category type.
9737   return S.Context.getLogicalOperationType();
9738 }
9739 
9740 // C99 6.5.8, C++ [expr.rel]
9741 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9742                                     SourceLocation Loc, BinaryOperatorKind Opc,
9743                                     bool IsRelational) {
9744   // Comparisons expect an rvalue, so convert to rvalue before any
9745   // type-related checks.
9746   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9747   if (LHS.isInvalid())
9748     return QualType();
9749   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9750   if (RHS.isInvalid())
9751     return QualType();
9752 
9753   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9754 
9755   // Handle vector comparisons separately.
9756   if (LHS.get()->getType()->isVectorType() ||
9757       RHS.get()->getType()->isVectorType())
9758     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
9759 
9760   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9761   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
9762 
9763   QualType LHSType = LHS.get()->getType();
9764   QualType RHSType = RHS.get()->getType();
9765   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
9766       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
9767     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
9768 
9769   QualType ResultTy = Context.getLogicalOperationType();
9770 
9771   const Expr::NullPointerConstantKind LHSNullKind =
9772       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9773   const Expr::NullPointerConstantKind RHSNullKind =
9774       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9775   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9776   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9777 
9778   if (!IsRelational && LHSIsNull != RHSIsNull) {
9779     bool IsEquality = Opc == BO_EQ;
9780     if (RHSIsNull)
9781       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9782                                    RHS.get()->getSourceRange());
9783     else
9784       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9785                                    LHS.get()->getSourceRange());
9786   }
9787 
9788   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9789       (RHSType->isIntegerType() && !RHSIsNull)) {
9790     // Skip normal pointer conversion checks in this case; we have better
9791     // diagnostics for this below.
9792   } else if (getLangOpts().CPlusPlus) {
9793     // Equality comparison of a function pointer to a void pointer is invalid,
9794     // but we allow it as an extension.
9795     // FIXME: If we really want to allow this, should it be part of composite
9796     // pointer type computation so it works in conditionals too?
9797     if (!IsRelational &&
9798         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9799          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9800       // This is a gcc extension compatibility comparison.
9801       // In a SFINAE context, we treat this as a hard error to maintain
9802       // conformance with the C++ standard.
9803       diagnoseFunctionPointerToVoidComparison(
9804           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9805 
9806       if (isSFINAEContext())
9807         return QualType();
9808 
9809       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9810       return ResultTy;
9811     }
9812 
9813     // C++ [expr.eq]p2:
9814     //   If at least one operand is a pointer [...] bring them to their
9815     //   composite pointer type.
9816     // C++ [expr.rel]p2:
9817     //   If both operands are pointers, [...] bring them to their composite
9818     //   pointer type.
9819     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9820             (IsRelational ? 2 : 1) &&
9821         (!LangOpts.ObjCAutoRefCount ||
9822          !(LHSType->isObjCObjectPointerType() ||
9823            RHSType->isObjCObjectPointerType()))) {
9824       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9825         return QualType();
9826       else
9827         return ResultTy;
9828     }
9829   } else if (LHSType->isPointerType() &&
9830              RHSType->isPointerType()) { // C99 6.5.8p2
9831     // All of the following pointer-related warnings are GCC extensions, except
9832     // when handling null pointer constants.
9833     QualType LCanPointeeTy =
9834       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9835     QualType RCanPointeeTy =
9836       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9837 
9838     // C99 6.5.9p2 and C99 6.5.8p2
9839     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9840                                    RCanPointeeTy.getUnqualifiedType())) {
9841       // Valid unless a relational comparison of function pointers
9842       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9843         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9844           << LHSType << RHSType << LHS.get()->getSourceRange()
9845           << RHS.get()->getSourceRange();
9846       }
9847     } else if (!IsRelational &&
9848                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9849       // Valid unless comparison between non-null pointer and function pointer
9850       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9851           && !LHSIsNull && !RHSIsNull)
9852         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9853                                                 /*isError*/false);
9854     } else {
9855       // Invalid
9856       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9857     }
9858     if (LCanPointeeTy != RCanPointeeTy) {
9859       // Treat NULL constant as a special case in OpenCL.
9860       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9861         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9862         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9863           Diag(Loc,
9864                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9865               << LHSType << RHSType << 0 /* comparison */
9866               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9867         }
9868       }
9869       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
9870       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
9871       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9872                                                : CK_BitCast;
9873       if (LHSIsNull && !RHSIsNull)
9874         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9875       else
9876         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9877     }
9878     return ResultTy;
9879   }
9880 
9881   if (getLangOpts().CPlusPlus) {
9882     // C++ [expr.eq]p4:
9883     //   Two operands of type std::nullptr_t or one operand of type
9884     //   std::nullptr_t and the other a null pointer constant compare equal.
9885     if (!IsRelational && LHSIsNull && RHSIsNull) {
9886       if (LHSType->isNullPtrType()) {
9887         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9888         return ResultTy;
9889       }
9890       if (RHSType->isNullPtrType()) {
9891         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9892         return ResultTy;
9893       }
9894     }
9895 
9896     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9897     // These aren't covered by the composite pointer type rules.
9898     if (!IsRelational && RHSType->isNullPtrType() &&
9899         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9900       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9901       return ResultTy;
9902     }
9903     if (!IsRelational && LHSType->isNullPtrType() &&
9904         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9905       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9906       return ResultTy;
9907     }
9908 
9909     if (IsRelational &&
9910         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9911          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9912       // HACK: Relational comparison of nullptr_t against a pointer type is
9913       // invalid per DR583, but we allow it within std::less<> and friends,
9914       // since otherwise common uses of it break.
9915       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9916       // friends to have std::nullptr_t overload candidates.
9917       DeclContext *DC = CurContext;
9918       if (isa<FunctionDecl>(DC))
9919         DC = DC->getParent();
9920       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9921         if (CTSD->isInStdNamespace() &&
9922             llvm::StringSwitch<bool>(CTSD->getName())
9923                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9924                 .Default(false)) {
9925           if (RHSType->isNullPtrType())
9926             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9927           else
9928             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9929           return ResultTy;
9930         }
9931       }
9932     }
9933 
9934     // C++ [expr.eq]p2:
9935     //   If at least one operand is a pointer to member, [...] bring them to
9936     //   their composite pointer type.
9937     if (!IsRelational &&
9938         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9939       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9940         return QualType();
9941       else
9942         return ResultTy;
9943     }
9944   }
9945 
9946   // Handle block pointer types.
9947   if (!IsRelational && LHSType->isBlockPointerType() &&
9948       RHSType->isBlockPointerType()) {
9949     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9950     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9951 
9952     if (!LHSIsNull && !RHSIsNull &&
9953         !Context.typesAreCompatible(lpointee, rpointee)) {
9954       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9955         << LHSType << RHSType << LHS.get()->getSourceRange()
9956         << RHS.get()->getSourceRange();
9957     }
9958     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9959     return ResultTy;
9960   }
9961 
9962   // Allow block pointers to be compared with null pointer constants.
9963   if (!IsRelational
9964       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9965           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9966     if (!LHSIsNull && !RHSIsNull) {
9967       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9968              ->getPointeeType()->isVoidType())
9969             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9970                 ->getPointeeType()->isVoidType())))
9971         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9972           << LHSType << RHSType << LHS.get()->getSourceRange()
9973           << RHS.get()->getSourceRange();
9974     }
9975     if (LHSIsNull && !RHSIsNull)
9976       LHS = ImpCastExprToType(LHS.get(), RHSType,
9977                               RHSType->isPointerType() ? CK_BitCast
9978                                 : CK_AnyPointerToBlockPointerCast);
9979     else
9980       RHS = ImpCastExprToType(RHS.get(), LHSType,
9981                               LHSType->isPointerType() ? CK_BitCast
9982                                 : CK_AnyPointerToBlockPointerCast);
9983     return ResultTy;
9984   }
9985 
9986   if (LHSType->isObjCObjectPointerType() ||
9987       RHSType->isObjCObjectPointerType()) {
9988     const PointerType *LPT = LHSType->getAs<PointerType>();
9989     const PointerType *RPT = RHSType->getAs<PointerType>();
9990     if (LPT || RPT) {
9991       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9992       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9993 
9994       if (!LPtrToVoid && !RPtrToVoid &&
9995           !Context.typesAreCompatible(LHSType, RHSType)) {
9996         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9997                                           /*isError*/false);
9998       }
9999       if (LHSIsNull && !RHSIsNull) {
10000         Expr *E = LHS.get();
10001         if (getLangOpts().ObjCAutoRefCount)
10002           CheckObjCConversion(SourceRange(), RHSType, E,
10003                               CCK_ImplicitConversion);
10004         LHS = ImpCastExprToType(E, RHSType,
10005                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10006       }
10007       else {
10008         Expr *E = RHS.get();
10009         if (getLangOpts().ObjCAutoRefCount)
10010           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10011                               /*Diagnose=*/true,
10012                               /*DiagnoseCFAudited=*/false, Opc);
10013         RHS = ImpCastExprToType(E, LHSType,
10014                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10015       }
10016       return ResultTy;
10017     }
10018     if (LHSType->isObjCObjectPointerType() &&
10019         RHSType->isObjCObjectPointerType()) {
10020       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10021         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10022                                           /*isError*/false);
10023       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10024         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10025 
10026       if (LHSIsNull && !RHSIsNull)
10027         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10028       else
10029         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10030       return ResultTy;
10031     }
10032 
10033     if (!IsRelational && LHSType->isBlockPointerType() &&
10034         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10035       LHS = ImpCastExprToType(LHS.get(), RHSType,
10036                               CK_BlockPointerToObjCPointerCast);
10037       return ResultTy;
10038     } else if (!IsRelational &&
10039                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10040                RHSType->isBlockPointerType()) {
10041       RHS = ImpCastExprToType(RHS.get(), LHSType,
10042                               CK_BlockPointerToObjCPointerCast);
10043       return ResultTy;
10044     }
10045   }
10046   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10047       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10048     unsigned DiagID = 0;
10049     bool isError = false;
10050     if (LangOpts.DebuggerSupport) {
10051       // Under a debugger, allow the comparison of pointers to integers,
10052       // since users tend to want to compare addresses.
10053     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10054                (RHSIsNull && RHSType->isIntegerType())) {
10055       if (IsRelational) {
10056         isError = getLangOpts().CPlusPlus;
10057         DiagID =
10058           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10059                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10060       }
10061     } else if (getLangOpts().CPlusPlus) {
10062       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10063       isError = true;
10064     } else if (IsRelational)
10065       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10066     else
10067       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10068 
10069     if (DiagID) {
10070       Diag(Loc, DiagID)
10071         << LHSType << RHSType << LHS.get()->getSourceRange()
10072         << RHS.get()->getSourceRange();
10073       if (isError)
10074         return QualType();
10075     }
10076 
10077     if (LHSType->isIntegerType())
10078       LHS = ImpCastExprToType(LHS.get(), RHSType,
10079                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10080     else
10081       RHS = ImpCastExprToType(RHS.get(), LHSType,
10082                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10083     return ResultTy;
10084   }
10085 
10086   // Handle block pointers.
10087   if (!IsRelational && RHSIsNull
10088       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10089     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10090     return ResultTy;
10091   }
10092   if (!IsRelational && LHSIsNull
10093       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10094     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10095     return ResultTy;
10096   }
10097 
10098   if (getLangOpts().OpenCLVersion >= 200) {
10099     if (LHSIsNull && RHSType->isQueueT()) {
10100       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10101       return ResultTy;
10102     }
10103 
10104     if (LHSType->isQueueT() && RHSIsNull) {
10105       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10106       return ResultTy;
10107     }
10108   }
10109 
10110   return InvalidOperands(Loc, LHS, RHS);
10111 }
10112 
10113 // Return a signed ext_vector_type that is of identical size and number of
10114 // elements. For floating point vectors, return an integer type of identical
10115 // size and number of elements. In the non ext_vector_type case, search from
10116 // the largest type to the smallest type to avoid cases where long long == long,
10117 // where long gets picked over long long.
10118 QualType Sema::GetSignedVectorType(QualType V) {
10119   const VectorType *VTy = V->getAs<VectorType>();
10120   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10121 
10122   if (isa<ExtVectorType>(VTy)) {
10123     if (TypeSize == Context.getTypeSize(Context.CharTy))
10124       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10125     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10126       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10127     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10128       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10129     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10130       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10131     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10132            "Unhandled vector element size in vector compare");
10133     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10134   }
10135 
10136   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10137     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10138                                  VectorType::GenericVector);
10139   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10140     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10141                                  VectorType::GenericVector);
10142   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10143     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10144                                  VectorType::GenericVector);
10145   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10146     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10147                                  VectorType::GenericVector);
10148   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10149          "Unhandled vector element size in vector compare");
10150   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10151                                VectorType::GenericVector);
10152 }
10153 
10154 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10155 /// operates on extended vector types.  Instead of producing an IntTy result,
10156 /// like a scalar comparison, a vector comparison produces a vector of integer
10157 /// types.
10158 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10159                                           SourceLocation Loc,
10160                                           BinaryOperatorKind Opc) {
10161   // Check to make sure we're operating on vectors of the same type and width,
10162   // Allowing one side to be a scalar of element type.
10163   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10164                               /*AllowBothBool*/true,
10165                               /*AllowBoolConversions*/getLangOpts().ZVector);
10166   if (vType.isNull())
10167     return vType;
10168 
10169   QualType LHSType = LHS.get()->getType();
10170 
10171   // If AltiVec, the comparison results in a numeric type, i.e.
10172   // bool for C++, int for C
10173   if (getLangOpts().AltiVec &&
10174       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10175     return Context.getLogicalOperationType();
10176 
10177   // For non-floating point types, check for self-comparisons of the form
10178   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10179   // often indicate logic errors in the program.
10180   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10181 
10182   // Check for comparisons of floating point operands using != and ==.
10183   if (BinaryOperator::isEqualityOp(Opc) &&
10184       LHSType->hasFloatingRepresentation()) {
10185     assert(RHS.get()->getType()->hasFloatingRepresentation());
10186     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10187   }
10188 
10189   // Return a signed type for the vector.
10190   return GetSignedVectorType(vType);
10191 }
10192 
10193 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10194                                           SourceLocation Loc) {
10195   // Ensure that either both operands are of the same vector type, or
10196   // one operand is of a vector type and the other is of its element type.
10197   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10198                                        /*AllowBothBool*/true,
10199                                        /*AllowBoolConversions*/false);
10200   if (vType.isNull())
10201     return InvalidOperands(Loc, LHS, RHS);
10202   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10203       vType->hasFloatingRepresentation())
10204     return InvalidOperands(Loc, LHS, RHS);
10205   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10206   //        usage of the logical operators && and || with vectors in C. This
10207   //        check could be notionally dropped.
10208   if (!getLangOpts().CPlusPlus &&
10209       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10210     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10211 
10212   return GetSignedVectorType(LHS.get()->getType());
10213 }
10214 
10215 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10216                                            SourceLocation Loc,
10217                                            BinaryOperatorKind Opc) {
10218   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10219 
10220   bool IsCompAssign =
10221       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10222 
10223   if (LHS.get()->getType()->isVectorType() ||
10224       RHS.get()->getType()->isVectorType()) {
10225     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10226         RHS.get()->getType()->hasIntegerRepresentation())
10227       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10228                         /*AllowBothBool*/true,
10229                         /*AllowBoolConversions*/getLangOpts().ZVector);
10230     return InvalidOperands(Loc, LHS, RHS);
10231   }
10232 
10233   if (Opc == BO_And)
10234     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10235 
10236   ExprResult LHSResult = LHS, RHSResult = RHS;
10237   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10238                                                  IsCompAssign);
10239   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10240     return QualType();
10241   LHS = LHSResult.get();
10242   RHS = RHSResult.get();
10243 
10244   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10245     return compType;
10246   return InvalidOperands(Loc, LHS, RHS);
10247 }
10248 
10249 // C99 6.5.[13,14]
10250 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10251                                            SourceLocation Loc,
10252                                            BinaryOperatorKind Opc) {
10253   // Check vector operands differently.
10254   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10255     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10256 
10257   // Diagnose cases where the user write a logical and/or but probably meant a
10258   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10259   // is a constant.
10260   if (LHS.get()->getType()->isIntegerType() &&
10261       !LHS.get()->getType()->isBooleanType() &&
10262       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10263       // Don't warn in macros or template instantiations.
10264       !Loc.isMacroID() && !inTemplateInstantiation()) {
10265     // If the RHS can be constant folded, and if it constant folds to something
10266     // that isn't 0 or 1 (which indicate a potential logical operation that
10267     // happened to fold to true/false) then warn.
10268     // Parens on the RHS are ignored.
10269     llvm::APSInt Result;
10270     if (RHS.get()->EvaluateAsInt(Result, Context))
10271       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10272            !RHS.get()->getExprLoc().isMacroID()) ||
10273           (Result != 0 && Result != 1)) {
10274         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10275           << RHS.get()->getSourceRange()
10276           << (Opc == BO_LAnd ? "&&" : "||");
10277         // Suggest replacing the logical operator with the bitwise version
10278         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10279             << (Opc == BO_LAnd ? "&" : "|")
10280             << FixItHint::CreateReplacement(SourceRange(
10281                                                  Loc, getLocForEndOfToken(Loc)),
10282                                             Opc == BO_LAnd ? "&" : "|");
10283         if (Opc == BO_LAnd)
10284           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10285           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10286               << FixItHint::CreateRemoval(
10287                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10288                               RHS.get()->getLocEnd()));
10289       }
10290   }
10291 
10292   if (!Context.getLangOpts().CPlusPlus) {
10293     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10294     // not operate on the built-in scalar and vector float types.
10295     if (Context.getLangOpts().OpenCL &&
10296         Context.getLangOpts().OpenCLVersion < 120) {
10297       if (LHS.get()->getType()->isFloatingType() ||
10298           RHS.get()->getType()->isFloatingType())
10299         return InvalidOperands(Loc, LHS, RHS);
10300     }
10301 
10302     LHS = UsualUnaryConversions(LHS.get());
10303     if (LHS.isInvalid())
10304       return QualType();
10305 
10306     RHS = UsualUnaryConversions(RHS.get());
10307     if (RHS.isInvalid())
10308       return QualType();
10309 
10310     if (!LHS.get()->getType()->isScalarType() ||
10311         !RHS.get()->getType()->isScalarType())
10312       return InvalidOperands(Loc, LHS, RHS);
10313 
10314     return Context.IntTy;
10315   }
10316 
10317   // The following is safe because we only use this method for
10318   // non-overloadable operands.
10319 
10320   // C++ [expr.log.and]p1
10321   // C++ [expr.log.or]p1
10322   // The operands are both contextually converted to type bool.
10323   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10324   if (LHSRes.isInvalid())
10325     return InvalidOperands(Loc, LHS, RHS);
10326   LHS = LHSRes;
10327 
10328   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10329   if (RHSRes.isInvalid())
10330     return InvalidOperands(Loc, LHS, RHS);
10331   RHS = RHSRes;
10332 
10333   // C++ [expr.log.and]p2
10334   // C++ [expr.log.or]p2
10335   // The result is a bool.
10336   return Context.BoolTy;
10337 }
10338 
10339 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10340   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10341   if (!ME) return false;
10342   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10343   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10344       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10345   if (!Base) return false;
10346   return Base->getMethodDecl() != nullptr;
10347 }
10348 
10349 /// Is the given expression (which must be 'const') a reference to a
10350 /// variable which was originally non-const, but which has become
10351 /// 'const' due to being captured within a block?
10352 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10353 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10354   assert(E->isLValue() && E->getType().isConstQualified());
10355   E = E->IgnoreParens();
10356 
10357   // Must be a reference to a declaration from an enclosing scope.
10358   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10359   if (!DRE) return NCCK_None;
10360   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10361 
10362   // The declaration must be a variable which is not declared 'const'.
10363   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10364   if (!var) return NCCK_None;
10365   if (var->getType().isConstQualified()) return NCCK_None;
10366   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10367 
10368   // Decide whether the first capture was for a block or a lambda.
10369   DeclContext *DC = S.CurContext, *Prev = nullptr;
10370   // Decide whether the first capture was for a block or a lambda.
10371   while (DC) {
10372     // For init-capture, it is possible that the variable belongs to the
10373     // template pattern of the current context.
10374     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10375       if (var->isInitCapture() &&
10376           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10377         break;
10378     if (DC == var->getDeclContext())
10379       break;
10380     Prev = DC;
10381     DC = DC->getParent();
10382   }
10383   // Unless we have an init-capture, we've gone one step too far.
10384   if (!var->isInitCapture())
10385     DC = Prev;
10386   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10387 }
10388 
10389 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10390   Ty = Ty.getNonReferenceType();
10391   if (IsDereference && Ty->isPointerType())
10392     Ty = Ty->getPointeeType();
10393   return !Ty.isConstQualified();
10394 }
10395 
10396 // Update err_typecheck_assign_const and note_typecheck_assign_const
10397 // when this enum is changed.
10398 enum {
10399   ConstFunction,
10400   ConstVariable,
10401   ConstMember,
10402   ConstMethod,
10403   NestedConstMember,
10404   ConstUnknown,  // Keep as last element
10405 };
10406 
10407 /// Emit the "read-only variable not assignable" error and print notes to give
10408 /// more information about why the variable is not assignable, such as pointing
10409 /// to the declaration of a const variable, showing that a method is const, or
10410 /// that the function is returning a const reference.
10411 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10412                                     SourceLocation Loc) {
10413   SourceRange ExprRange = E->getSourceRange();
10414 
10415   // Only emit one error on the first const found.  All other consts will emit
10416   // a note to the error.
10417   bool DiagnosticEmitted = false;
10418 
10419   // Track if the current expression is the result of a dereference, and if the
10420   // next checked expression is the result of a dereference.
10421   bool IsDereference = false;
10422   bool NextIsDereference = false;
10423 
10424   // Loop to process MemberExpr chains.
10425   while (true) {
10426     IsDereference = NextIsDereference;
10427 
10428     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10429     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10430       NextIsDereference = ME->isArrow();
10431       const ValueDecl *VD = ME->getMemberDecl();
10432       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10433         // Mutable fields can be modified even if the class is const.
10434         if (Field->isMutable()) {
10435           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10436           break;
10437         }
10438 
10439         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10440           if (!DiagnosticEmitted) {
10441             S.Diag(Loc, diag::err_typecheck_assign_const)
10442                 << ExprRange << ConstMember << false /*static*/ << Field
10443                 << Field->getType();
10444             DiagnosticEmitted = true;
10445           }
10446           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10447               << ConstMember << false /*static*/ << Field << Field->getType()
10448               << Field->getSourceRange();
10449         }
10450         E = ME->getBase();
10451         continue;
10452       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10453         if (VDecl->getType().isConstQualified()) {
10454           if (!DiagnosticEmitted) {
10455             S.Diag(Loc, diag::err_typecheck_assign_const)
10456                 << ExprRange << ConstMember << true /*static*/ << VDecl
10457                 << VDecl->getType();
10458             DiagnosticEmitted = true;
10459           }
10460           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10461               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10462               << VDecl->getSourceRange();
10463         }
10464         // Static fields do not inherit constness from parents.
10465         break;
10466       }
10467       break; // End MemberExpr
10468     } else if (const ArraySubscriptExpr *ASE =
10469                    dyn_cast<ArraySubscriptExpr>(E)) {
10470       E = ASE->getBase()->IgnoreParenImpCasts();
10471       continue;
10472     } else if (const ExtVectorElementExpr *EVE =
10473                    dyn_cast<ExtVectorElementExpr>(E)) {
10474       E = EVE->getBase()->IgnoreParenImpCasts();
10475       continue;
10476     }
10477     break;
10478   }
10479 
10480   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10481     // Function calls
10482     const FunctionDecl *FD = CE->getDirectCallee();
10483     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10484       if (!DiagnosticEmitted) {
10485         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10486                                                       << ConstFunction << FD;
10487         DiagnosticEmitted = true;
10488       }
10489       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10490              diag::note_typecheck_assign_const)
10491           << ConstFunction << FD << FD->getReturnType()
10492           << FD->getReturnTypeSourceRange();
10493     }
10494   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10495     // Point to variable declaration.
10496     if (const ValueDecl *VD = DRE->getDecl()) {
10497       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10498         if (!DiagnosticEmitted) {
10499           S.Diag(Loc, diag::err_typecheck_assign_const)
10500               << ExprRange << ConstVariable << VD << VD->getType();
10501           DiagnosticEmitted = true;
10502         }
10503         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10504             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10505       }
10506     }
10507   } else if (isa<CXXThisExpr>(E)) {
10508     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10509       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10510         if (MD->isConst()) {
10511           if (!DiagnosticEmitted) {
10512             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10513                                                           << ConstMethod << MD;
10514             DiagnosticEmitted = true;
10515           }
10516           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10517               << ConstMethod << MD << MD->getSourceRange();
10518         }
10519       }
10520     }
10521   }
10522 
10523   if (DiagnosticEmitted)
10524     return;
10525 
10526   // Can't determine a more specific message, so display the generic error.
10527   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10528 }
10529 
10530 enum OriginalExprKind {
10531   OEK_Variable,
10532   OEK_Member,
10533   OEK_LValue
10534 };
10535 
10536 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10537                                          const RecordType *Ty,
10538                                          SourceLocation Loc, SourceRange Range,
10539                                          OriginalExprKind OEK,
10540                                          bool &DiagnosticEmitted,
10541                                          bool IsNested = false) {
10542   // We walk the record hierarchy breadth-first to ensure that we print
10543   // diagnostics in field nesting order.
10544   // First, check every field for constness.
10545   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10546     if (Field->getType().isConstQualified()) {
10547       if (!DiagnosticEmitted) {
10548         S.Diag(Loc, diag::err_typecheck_assign_const)
10549             << Range << NestedConstMember << OEK << VD
10550             << IsNested << Field;
10551         DiagnosticEmitted = true;
10552       }
10553       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10554           << NestedConstMember << IsNested << Field
10555           << Field->getType() << Field->getSourceRange();
10556     }
10557   }
10558   // Then, recurse.
10559   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10560     QualType FTy = Field->getType();
10561     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10562       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10563                                    OEK, DiagnosticEmitted, true);
10564   }
10565 }
10566 
10567 /// Emit an error for the case where a record we are trying to assign to has a
10568 /// const-qualified field somewhere in its hierarchy.
10569 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10570                                          SourceLocation Loc) {
10571   QualType Ty = E->getType();
10572   assert(Ty->isRecordType() && "lvalue was not record?");
10573   SourceRange Range = E->getSourceRange();
10574   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10575   bool DiagEmitted = false;
10576 
10577   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10578     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10579             Range, OEK_Member, DiagEmitted);
10580   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10581     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10582             Range, OEK_Variable, DiagEmitted);
10583   else
10584     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10585             Range, OEK_LValue, DiagEmitted);
10586   if (!DiagEmitted)
10587     DiagnoseConstAssignment(S, E, Loc);
10588 }
10589 
10590 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10591 /// emit an error and return true.  If so, return false.
10592 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10593   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10594 
10595   S.CheckShadowingDeclModification(E, Loc);
10596 
10597   SourceLocation OrigLoc = Loc;
10598   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10599                                                               &Loc);
10600   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10601     IsLV = Expr::MLV_InvalidMessageExpression;
10602   if (IsLV == Expr::MLV_Valid)
10603     return false;
10604 
10605   unsigned DiagID = 0;
10606   bool NeedType = false;
10607   switch (IsLV) { // C99 6.5.16p2
10608   case Expr::MLV_ConstQualified:
10609     // Use a specialized diagnostic when we're assigning to an object
10610     // from an enclosing function or block.
10611     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10612       if (NCCK == NCCK_Block)
10613         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10614       else
10615         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10616       break;
10617     }
10618 
10619     // In ARC, use some specialized diagnostics for occasions where we
10620     // infer 'const'.  These are always pseudo-strong variables.
10621     if (S.getLangOpts().ObjCAutoRefCount) {
10622       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10623       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10624         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10625 
10626         // Use the normal diagnostic if it's pseudo-__strong but the
10627         // user actually wrote 'const'.
10628         if (var->isARCPseudoStrong() &&
10629             (!var->getTypeSourceInfo() ||
10630              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10631           // There are two pseudo-strong cases:
10632           //  - self
10633           ObjCMethodDecl *method = S.getCurMethodDecl();
10634           if (method && var == method->getSelfDecl())
10635             DiagID = method->isClassMethod()
10636               ? diag::err_typecheck_arc_assign_self_class_method
10637               : diag::err_typecheck_arc_assign_self;
10638 
10639           //  - fast enumeration variables
10640           else
10641             DiagID = diag::err_typecheck_arr_assign_enumeration;
10642 
10643           SourceRange Assign;
10644           if (Loc != OrigLoc)
10645             Assign = SourceRange(OrigLoc, OrigLoc);
10646           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10647           // We need to preserve the AST regardless, so migration tool
10648           // can do its job.
10649           return false;
10650         }
10651       }
10652     }
10653 
10654     // If none of the special cases above are triggered, then this is a
10655     // simple const assignment.
10656     if (DiagID == 0) {
10657       DiagnoseConstAssignment(S, E, Loc);
10658       return true;
10659     }
10660 
10661     break;
10662   case Expr::MLV_ConstAddrSpace:
10663     DiagnoseConstAssignment(S, E, Loc);
10664     return true;
10665   case Expr::MLV_ConstQualifiedField:
10666     DiagnoseRecursiveConstFields(S, E, Loc);
10667     return true;
10668   case Expr::MLV_ArrayType:
10669   case Expr::MLV_ArrayTemporary:
10670     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10671     NeedType = true;
10672     break;
10673   case Expr::MLV_NotObjectType:
10674     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10675     NeedType = true;
10676     break;
10677   case Expr::MLV_LValueCast:
10678     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10679     break;
10680   case Expr::MLV_Valid:
10681     llvm_unreachable("did not take early return for MLV_Valid");
10682   case Expr::MLV_InvalidExpression:
10683   case Expr::MLV_MemberFunction:
10684   case Expr::MLV_ClassTemporary:
10685     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10686     break;
10687   case Expr::MLV_IncompleteType:
10688   case Expr::MLV_IncompleteVoidType:
10689     return S.RequireCompleteType(Loc, E->getType(),
10690              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10691   case Expr::MLV_DuplicateVectorComponents:
10692     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10693     break;
10694   case Expr::MLV_NoSetterProperty:
10695     llvm_unreachable("readonly properties should be processed differently");
10696   case Expr::MLV_InvalidMessageExpression:
10697     DiagID = diag::err_readonly_message_assignment;
10698     break;
10699   case Expr::MLV_SubObjCPropertySetting:
10700     DiagID = diag::err_no_subobject_property_setting;
10701     break;
10702   }
10703 
10704   SourceRange Assign;
10705   if (Loc != OrigLoc)
10706     Assign = SourceRange(OrigLoc, OrigLoc);
10707   if (NeedType)
10708     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10709   else
10710     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10711   return true;
10712 }
10713 
10714 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10715                                          SourceLocation Loc,
10716                                          Sema &Sema) {
10717   if (Sema.inTemplateInstantiation())
10718     return;
10719   if (Sema.isUnevaluatedContext())
10720     return;
10721   if (Loc.isInvalid() || Loc.isMacroID())
10722     return;
10723   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
10724     return;
10725 
10726   // C / C++ fields
10727   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10728   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10729   if (ML && MR) {
10730     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
10731       return;
10732     const ValueDecl *LHSDecl =
10733         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
10734     const ValueDecl *RHSDecl =
10735         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
10736     if (LHSDecl != RHSDecl)
10737       return;
10738     if (LHSDecl->getType().isVolatileQualified())
10739       return;
10740     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10741       if (RefTy->getPointeeType().isVolatileQualified())
10742         return;
10743 
10744     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10745   }
10746 
10747   // Objective-C instance variables
10748   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10749   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10750   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10751     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10752     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10753     if (RL && RR && RL->getDecl() == RR->getDecl())
10754       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10755   }
10756 }
10757 
10758 // C99 6.5.16.1
10759 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10760                                        SourceLocation Loc,
10761                                        QualType CompoundType) {
10762   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10763 
10764   // Verify that LHS is a modifiable lvalue, and emit error if not.
10765   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10766     return QualType();
10767 
10768   QualType LHSType = LHSExpr->getType();
10769   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10770                                              CompoundType;
10771   // OpenCL v1.2 s6.1.1.1 p2:
10772   // The half data type can only be used to declare a pointer to a buffer that
10773   // contains half values
10774   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10775     LHSType->isHalfType()) {
10776     Diag(Loc, diag::err_opencl_half_load_store) << 1
10777         << LHSType.getUnqualifiedType();
10778     return QualType();
10779   }
10780 
10781   AssignConvertType ConvTy;
10782   if (CompoundType.isNull()) {
10783     Expr *RHSCheck = RHS.get();
10784 
10785     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10786 
10787     QualType LHSTy(LHSType);
10788     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10789     if (RHS.isInvalid())
10790       return QualType();
10791     // Special case of NSObject attributes on c-style pointer types.
10792     if (ConvTy == IncompatiblePointer &&
10793         ((Context.isObjCNSObjectType(LHSType) &&
10794           RHSType->isObjCObjectPointerType()) ||
10795          (Context.isObjCNSObjectType(RHSType) &&
10796           LHSType->isObjCObjectPointerType())))
10797       ConvTy = Compatible;
10798 
10799     if (ConvTy == Compatible &&
10800         LHSType->isObjCObjectType())
10801         Diag(Loc, diag::err_objc_object_assignment)
10802           << LHSType;
10803 
10804     // If the RHS is a unary plus or minus, check to see if they = and + are
10805     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10806     // instead of "x += 4".
10807     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10808       RHSCheck = ICE->getSubExpr();
10809     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10810       if ((UO->getOpcode() == UO_Plus ||
10811            UO->getOpcode() == UO_Minus) &&
10812           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10813           // Only if the two operators are exactly adjacent.
10814           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10815           // And there is a space or other character before the subexpr of the
10816           // unary +/-.  We don't want to warn on "x=-1".
10817           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10818           UO->getSubExpr()->getLocStart().isFileID()) {
10819         Diag(Loc, diag::warn_not_compound_assign)
10820           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10821           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10822       }
10823     }
10824 
10825     if (ConvTy == Compatible) {
10826       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10827         // Warn about retain cycles where a block captures the LHS, but
10828         // not if the LHS is a simple variable into which the block is
10829         // being stored...unless that variable can be captured by reference!
10830         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10831         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10832         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10833           checkRetainCycles(LHSExpr, RHS.get());
10834       }
10835 
10836       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10837           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10838         // It is safe to assign a weak reference into a strong variable.
10839         // Although this code can still have problems:
10840         //   id x = self.weakProp;
10841         //   id y = self.weakProp;
10842         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10843         // paths through the function. This should be revisited if
10844         // -Wrepeated-use-of-weak is made flow-sensitive.
10845         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10846         // variable, which will be valid for the current autorelease scope.
10847         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10848                              RHS.get()->getLocStart()))
10849           getCurFunction()->markSafeWeakUse(RHS.get());
10850 
10851       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10852         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10853       }
10854     }
10855   } else {
10856     // Compound assignment "x += y"
10857     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10858   }
10859 
10860   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10861                                RHS.get(), AA_Assigning))
10862     return QualType();
10863 
10864   CheckForNullPointerDereference(*this, LHSExpr);
10865 
10866   // C99 6.5.16p3: The type of an assignment expression is the type of the
10867   // left operand unless the left operand has qualified type, in which case
10868   // it is the unqualified version of the type of the left operand.
10869   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10870   // is converted to the type of the assignment expression (above).
10871   // C++ 5.17p1: the type of the assignment expression is that of its left
10872   // operand.
10873   return (getLangOpts().CPlusPlus
10874           ? LHSType : LHSType.getUnqualifiedType());
10875 }
10876 
10877 // Only ignore explicit casts to void.
10878 static bool IgnoreCommaOperand(const Expr *E) {
10879   E = E->IgnoreParens();
10880 
10881   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10882     if (CE->getCastKind() == CK_ToVoid) {
10883       return true;
10884     }
10885   }
10886 
10887   return false;
10888 }
10889 
10890 // Look for instances where it is likely the comma operator is confused with
10891 // another operator.  There is a whitelist of acceptable expressions for the
10892 // left hand side of the comma operator, otherwise emit a warning.
10893 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10894   // No warnings in macros
10895   if (Loc.isMacroID())
10896     return;
10897 
10898   // Don't warn in template instantiations.
10899   if (inTemplateInstantiation())
10900     return;
10901 
10902   // Scope isn't fine-grained enough to whitelist the specific cases, so
10903   // instead, skip more than needed, then call back into here with the
10904   // CommaVisitor in SemaStmt.cpp.
10905   // The whitelisted locations are the initialization and increment portions
10906   // of a for loop.  The additional checks are on the condition of
10907   // if statements, do/while loops, and for loops.
10908   const unsigned ForIncrementFlags =
10909       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10910   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10911   const unsigned ScopeFlags = getCurScope()->getFlags();
10912   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10913       (ScopeFlags & ForInitFlags) == ForInitFlags)
10914     return;
10915 
10916   // If there are multiple comma operators used together, get the RHS of the
10917   // of the comma operator as the LHS.
10918   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10919     if (BO->getOpcode() != BO_Comma)
10920       break;
10921     LHS = BO->getRHS();
10922   }
10923 
10924   // Only allow some expressions on LHS to not warn.
10925   if (IgnoreCommaOperand(LHS))
10926     return;
10927 
10928   Diag(Loc, diag::warn_comma_operator);
10929   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10930       << LHS->getSourceRange()
10931       << FixItHint::CreateInsertion(LHS->getLocStart(),
10932                                     LangOpts.CPlusPlus ? "static_cast<void>("
10933                                                        : "(void)(")
10934       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10935                                     ")");
10936 }
10937 
10938 // C99 6.5.17
10939 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10940                                    SourceLocation Loc) {
10941   LHS = S.CheckPlaceholderExpr(LHS.get());
10942   RHS = S.CheckPlaceholderExpr(RHS.get());
10943   if (LHS.isInvalid() || RHS.isInvalid())
10944     return QualType();
10945 
10946   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10947   // operands, but not unary promotions.
10948   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10949 
10950   // So we treat the LHS as a ignored value, and in C++ we allow the
10951   // containing site to determine what should be done with the RHS.
10952   LHS = S.IgnoredValueConversions(LHS.get());
10953   if (LHS.isInvalid())
10954     return QualType();
10955 
10956   S.DiagnoseUnusedExprResult(LHS.get());
10957 
10958   if (!S.getLangOpts().CPlusPlus) {
10959     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10960     if (RHS.isInvalid())
10961       return QualType();
10962     if (!RHS.get()->getType()->isVoidType())
10963       S.RequireCompleteType(Loc, RHS.get()->getType(),
10964                             diag::err_incomplete_type);
10965   }
10966 
10967   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10968     S.DiagnoseCommaOperator(LHS.get(), Loc);
10969 
10970   return RHS.get()->getType();
10971 }
10972 
10973 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10974 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10975 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10976                                                ExprValueKind &VK,
10977                                                ExprObjectKind &OK,
10978                                                SourceLocation OpLoc,
10979                                                bool IsInc, bool IsPrefix) {
10980   if (Op->isTypeDependent())
10981     return S.Context.DependentTy;
10982 
10983   QualType ResType = Op->getType();
10984   // Atomic types can be used for increment / decrement where the non-atomic
10985   // versions can, so ignore the _Atomic() specifier for the purpose of
10986   // checking.
10987   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10988     ResType = ResAtomicType->getValueType();
10989 
10990   assert(!ResType.isNull() && "no type for increment/decrement expression");
10991 
10992   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10993     // Decrement of bool is not allowed.
10994     if (!IsInc) {
10995       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10996       return QualType();
10997     }
10998     // Increment of bool sets it to true, but is deprecated.
10999     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11000                                               : diag::warn_increment_bool)
11001       << Op->getSourceRange();
11002   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11003     // Error on enum increments and decrements in C++ mode
11004     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11005     return QualType();
11006   } else if (ResType->isRealType()) {
11007     // OK!
11008   } else if (ResType->isPointerType()) {
11009     // C99 6.5.2.4p2, 6.5.6p2
11010     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11011       return QualType();
11012   } else if (ResType->isObjCObjectPointerType()) {
11013     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11014     // Otherwise, we just need a complete type.
11015     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11016         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11017       return QualType();
11018   } else if (ResType->isAnyComplexType()) {
11019     // C99 does not support ++/-- on complex types, we allow as an extension.
11020     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11021       << ResType << Op->getSourceRange();
11022   } else if (ResType->isPlaceholderType()) {
11023     ExprResult PR = S.CheckPlaceholderExpr(Op);
11024     if (PR.isInvalid()) return QualType();
11025     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11026                                           IsInc, IsPrefix);
11027   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11028     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11029   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11030              (ResType->getAs<VectorType>()->getVectorKind() !=
11031               VectorType::AltiVecBool)) {
11032     // The z vector extensions allow ++ and -- for non-bool vectors.
11033   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11034             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11035     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11036   } else {
11037     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11038       << ResType << int(IsInc) << Op->getSourceRange();
11039     return QualType();
11040   }
11041   // At this point, we know we have a real, complex or pointer type.
11042   // Now make sure the operand is a modifiable lvalue.
11043   if (CheckForModifiableLvalue(Op, OpLoc, S))
11044     return QualType();
11045   // In C++, a prefix increment is the same type as the operand. Otherwise
11046   // (in C or with postfix), the increment is the unqualified type of the
11047   // operand.
11048   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11049     VK = VK_LValue;
11050     OK = Op->getObjectKind();
11051     return ResType;
11052   } else {
11053     VK = VK_RValue;
11054     return ResType.getUnqualifiedType();
11055   }
11056 }
11057 
11058 
11059 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11060 /// This routine allows us to typecheck complex/recursive expressions
11061 /// where the declaration is needed for type checking. We only need to
11062 /// handle cases when the expression references a function designator
11063 /// or is an lvalue. Here are some examples:
11064 ///  - &(x) => x
11065 ///  - &*****f => f for f a function designator.
11066 ///  - &s.xx => s
11067 ///  - &s.zz[1].yy -> s, if zz is an array
11068 ///  - *(x + 1) -> x, if x is an array
11069 ///  - &"123"[2] -> 0
11070 ///  - & __real__ x -> x
11071 static ValueDecl *getPrimaryDecl(Expr *E) {
11072   switch (E->getStmtClass()) {
11073   case Stmt::DeclRefExprClass:
11074     return cast<DeclRefExpr>(E)->getDecl();
11075   case Stmt::MemberExprClass:
11076     // If this is an arrow operator, the address is an offset from
11077     // the base's value, so the object the base refers to is
11078     // irrelevant.
11079     if (cast<MemberExpr>(E)->isArrow())
11080       return nullptr;
11081     // Otherwise, the expression refers to a part of the base
11082     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11083   case Stmt::ArraySubscriptExprClass: {
11084     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11085     // promotion of register arrays earlier.
11086     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11087     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11088       if (ICE->getSubExpr()->getType()->isArrayType())
11089         return getPrimaryDecl(ICE->getSubExpr());
11090     }
11091     return nullptr;
11092   }
11093   case Stmt::UnaryOperatorClass: {
11094     UnaryOperator *UO = cast<UnaryOperator>(E);
11095 
11096     switch(UO->getOpcode()) {
11097     case UO_Real:
11098     case UO_Imag:
11099     case UO_Extension:
11100       return getPrimaryDecl(UO->getSubExpr());
11101     default:
11102       return nullptr;
11103     }
11104   }
11105   case Stmt::ParenExprClass:
11106     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11107   case Stmt::ImplicitCastExprClass:
11108     // If the result of an implicit cast is an l-value, we care about
11109     // the sub-expression; otherwise, the result here doesn't matter.
11110     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11111   default:
11112     return nullptr;
11113   }
11114 }
11115 
11116 namespace {
11117   enum {
11118     AO_Bit_Field = 0,
11119     AO_Vector_Element = 1,
11120     AO_Property_Expansion = 2,
11121     AO_Register_Variable = 3,
11122     AO_No_Error = 4
11123   };
11124 }
11125 /// \brief Diagnose invalid operand for address of operations.
11126 ///
11127 /// \param Type The type of operand which cannot have its address taken.
11128 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11129                                          Expr *E, unsigned Type) {
11130   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11131 }
11132 
11133 /// CheckAddressOfOperand - The operand of & must be either a function
11134 /// designator or an lvalue designating an object. If it is an lvalue, the
11135 /// object cannot be declared with storage class register or be a bit field.
11136 /// Note: The usual conversions are *not* applied to the operand of the &
11137 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11138 /// In C++, the operand might be an overloaded function name, in which case
11139 /// we allow the '&' but retain the overloaded-function type.
11140 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11141   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11142     if (PTy->getKind() == BuiltinType::Overload) {
11143       Expr *E = OrigOp.get()->IgnoreParens();
11144       if (!isa<OverloadExpr>(E)) {
11145         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11146         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11147           << OrigOp.get()->getSourceRange();
11148         return QualType();
11149       }
11150 
11151       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11152       if (isa<UnresolvedMemberExpr>(Ovl))
11153         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11154           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11155             << OrigOp.get()->getSourceRange();
11156           return QualType();
11157         }
11158 
11159       return Context.OverloadTy;
11160     }
11161 
11162     if (PTy->getKind() == BuiltinType::UnknownAny)
11163       return Context.UnknownAnyTy;
11164 
11165     if (PTy->getKind() == BuiltinType::BoundMember) {
11166       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11167         << OrigOp.get()->getSourceRange();
11168       return QualType();
11169     }
11170 
11171     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11172     if (OrigOp.isInvalid()) return QualType();
11173   }
11174 
11175   if (OrigOp.get()->isTypeDependent())
11176     return Context.DependentTy;
11177 
11178   assert(!OrigOp.get()->getType()->isPlaceholderType());
11179 
11180   // Make sure to ignore parentheses in subsequent checks
11181   Expr *op = OrigOp.get()->IgnoreParens();
11182 
11183   // In OpenCL captures for blocks called as lambda functions
11184   // are located in the private address space. Blocks used in
11185   // enqueue_kernel can be located in a different address space
11186   // depending on a vendor implementation. Thus preventing
11187   // taking an address of the capture to avoid invalid AS casts.
11188   if (LangOpts.OpenCL) {
11189     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11190     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11191       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11192       return QualType();
11193     }
11194   }
11195 
11196   if (getLangOpts().C99) {
11197     // Implement C99-only parts of addressof rules.
11198     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11199       if (uOp->getOpcode() == UO_Deref)
11200         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11201         // (assuming the deref expression is valid).
11202         return uOp->getSubExpr()->getType();
11203     }
11204     // Technically, there should be a check for array subscript
11205     // expressions here, but the result of one is always an lvalue anyway.
11206   }
11207   ValueDecl *dcl = getPrimaryDecl(op);
11208 
11209   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11210     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11211                                            op->getLocStart()))
11212       return QualType();
11213 
11214   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11215   unsigned AddressOfError = AO_No_Error;
11216 
11217   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11218     bool sfinae = (bool)isSFINAEContext();
11219     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11220                                   : diag::ext_typecheck_addrof_temporary)
11221       << op->getType() << op->getSourceRange();
11222     if (sfinae)
11223       return QualType();
11224     // Materialize the temporary as an lvalue so that we can take its address.
11225     OrigOp = op =
11226         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11227   } else if (isa<ObjCSelectorExpr>(op)) {
11228     return Context.getPointerType(op->getType());
11229   } else if (lval == Expr::LV_MemberFunction) {
11230     // If it's an instance method, make a member pointer.
11231     // The expression must have exactly the form &A::foo.
11232 
11233     // If the underlying expression isn't a decl ref, give up.
11234     if (!isa<DeclRefExpr>(op)) {
11235       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11236         << OrigOp.get()->getSourceRange();
11237       return QualType();
11238     }
11239     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11240     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11241 
11242     // The id-expression was parenthesized.
11243     if (OrigOp.get() != DRE) {
11244       Diag(OpLoc, diag::err_parens_pointer_member_function)
11245         << OrigOp.get()->getSourceRange();
11246 
11247     // The method was named without a qualifier.
11248     } else if (!DRE->getQualifier()) {
11249       if (MD->getParent()->getName().empty())
11250         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11251           << op->getSourceRange();
11252       else {
11253         SmallString<32> Str;
11254         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11255         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11256           << op->getSourceRange()
11257           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11258       }
11259     }
11260 
11261     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11262     if (isa<CXXDestructorDecl>(MD))
11263       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11264 
11265     QualType MPTy = Context.getMemberPointerType(
11266         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11267     // Under the MS ABI, lock down the inheritance model now.
11268     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11269       (void)isCompleteType(OpLoc, MPTy);
11270     return MPTy;
11271   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11272     // C99 6.5.3.2p1
11273     // The operand must be either an l-value or a function designator
11274     if (!op->getType()->isFunctionType()) {
11275       // Use a special diagnostic for loads from property references.
11276       if (isa<PseudoObjectExpr>(op)) {
11277         AddressOfError = AO_Property_Expansion;
11278       } else {
11279         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11280           << op->getType() << op->getSourceRange();
11281         return QualType();
11282       }
11283     }
11284   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11285     // The operand cannot be a bit-field
11286     AddressOfError = AO_Bit_Field;
11287   } else if (op->getObjectKind() == OK_VectorComponent) {
11288     // The operand cannot be an element of a vector
11289     AddressOfError = AO_Vector_Element;
11290   } else if (dcl) { // C99 6.5.3.2p1
11291     // We have an lvalue with a decl. Make sure the decl is not declared
11292     // with the register storage-class specifier.
11293     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11294       // in C++ it is not error to take address of a register
11295       // variable (c++03 7.1.1P3)
11296       if (vd->getStorageClass() == SC_Register &&
11297           !getLangOpts().CPlusPlus) {
11298         AddressOfError = AO_Register_Variable;
11299       }
11300     } else if (isa<MSPropertyDecl>(dcl)) {
11301       AddressOfError = AO_Property_Expansion;
11302     } else if (isa<FunctionTemplateDecl>(dcl)) {
11303       return Context.OverloadTy;
11304     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11305       // Okay: we can take the address of a field.
11306       // Could be a pointer to member, though, if there is an explicit
11307       // scope qualifier for the class.
11308       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11309         DeclContext *Ctx = dcl->getDeclContext();
11310         if (Ctx && Ctx->isRecord()) {
11311           if (dcl->getType()->isReferenceType()) {
11312             Diag(OpLoc,
11313                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11314               << dcl->getDeclName() << dcl->getType();
11315             return QualType();
11316           }
11317 
11318           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11319             Ctx = Ctx->getParent();
11320 
11321           QualType MPTy = Context.getMemberPointerType(
11322               op->getType(),
11323               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11324           // Under the MS ABI, lock down the inheritance model now.
11325           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11326             (void)isCompleteType(OpLoc, MPTy);
11327           return MPTy;
11328         }
11329       }
11330     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11331                !isa<BindingDecl>(dcl))
11332       llvm_unreachable("Unknown/unexpected decl type");
11333   }
11334 
11335   if (AddressOfError != AO_No_Error) {
11336     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11337     return QualType();
11338   }
11339 
11340   if (lval == Expr::LV_IncompleteVoidType) {
11341     // Taking the address of a void variable is technically illegal, but we
11342     // allow it in cases which are otherwise valid.
11343     // Example: "extern void x; void* y = &x;".
11344     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11345   }
11346 
11347   // If the operand has type "type", the result has type "pointer to type".
11348   if (op->getType()->isObjCObjectType())
11349     return Context.getObjCObjectPointerType(op->getType());
11350 
11351   CheckAddressOfPackedMember(op);
11352 
11353   return Context.getPointerType(op->getType());
11354 }
11355 
11356 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11357   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11358   if (!DRE)
11359     return;
11360   const Decl *D = DRE->getDecl();
11361   if (!D)
11362     return;
11363   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11364   if (!Param)
11365     return;
11366   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11367     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11368       return;
11369   if (FunctionScopeInfo *FD = S.getCurFunction())
11370     if (!FD->ModifiedNonNullParams.count(Param))
11371       FD->ModifiedNonNullParams.insert(Param);
11372 }
11373 
11374 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11375 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11376                                         SourceLocation OpLoc) {
11377   if (Op->isTypeDependent())
11378     return S.Context.DependentTy;
11379 
11380   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11381   if (ConvResult.isInvalid())
11382     return QualType();
11383   Op = ConvResult.get();
11384   QualType OpTy = Op->getType();
11385   QualType Result;
11386 
11387   if (isa<CXXReinterpretCastExpr>(Op)) {
11388     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11389     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11390                                      Op->getSourceRange());
11391   }
11392 
11393   if (const PointerType *PT = OpTy->getAs<PointerType>())
11394   {
11395     Result = PT->getPointeeType();
11396   }
11397   else if (const ObjCObjectPointerType *OPT =
11398              OpTy->getAs<ObjCObjectPointerType>())
11399     Result = OPT->getPointeeType();
11400   else {
11401     ExprResult PR = S.CheckPlaceholderExpr(Op);
11402     if (PR.isInvalid()) return QualType();
11403     if (PR.get() != Op)
11404       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11405   }
11406 
11407   if (Result.isNull()) {
11408     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11409       << OpTy << Op->getSourceRange();
11410     return QualType();
11411   }
11412 
11413   // Note that per both C89 and C99, indirection is always legal, even if Result
11414   // is an incomplete type or void.  It would be possible to warn about
11415   // dereferencing a void pointer, but it's completely well-defined, and such a
11416   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11417   // for pointers to 'void' but is fine for any other pointer type:
11418   //
11419   // C++ [expr.unary.op]p1:
11420   //   [...] the expression to which [the unary * operator] is applied shall
11421   //   be a pointer to an object type, or a pointer to a function type
11422   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11423     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11424       << OpTy << Op->getSourceRange();
11425 
11426   // Dereferences are usually l-values...
11427   VK = VK_LValue;
11428 
11429   // ...except that certain expressions are never l-values in C.
11430   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11431     VK = VK_RValue;
11432 
11433   return Result;
11434 }
11435 
11436 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11437   BinaryOperatorKind Opc;
11438   switch (Kind) {
11439   default: llvm_unreachable("Unknown binop!");
11440   case tok::periodstar:           Opc = BO_PtrMemD; break;
11441   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11442   case tok::star:                 Opc = BO_Mul; break;
11443   case tok::slash:                Opc = BO_Div; break;
11444   case tok::percent:              Opc = BO_Rem; break;
11445   case tok::plus:                 Opc = BO_Add; break;
11446   case tok::minus:                Opc = BO_Sub; break;
11447   case tok::lessless:             Opc = BO_Shl; break;
11448   case tok::greatergreater:       Opc = BO_Shr; break;
11449   case tok::lessequal:            Opc = BO_LE; break;
11450   case tok::less:                 Opc = BO_LT; break;
11451   case tok::greaterequal:         Opc = BO_GE; break;
11452   case tok::greater:              Opc = BO_GT; break;
11453   case tok::exclaimequal:         Opc = BO_NE; break;
11454   case tok::equalequal:           Opc = BO_EQ; break;
11455   case tok::spaceship:            Opc = BO_Cmp; break;
11456   case tok::amp:                  Opc = BO_And; break;
11457   case tok::caret:                Opc = BO_Xor; break;
11458   case tok::pipe:                 Opc = BO_Or; break;
11459   case tok::ampamp:               Opc = BO_LAnd; break;
11460   case tok::pipepipe:             Opc = BO_LOr; break;
11461   case tok::equal:                Opc = BO_Assign; break;
11462   case tok::starequal:            Opc = BO_MulAssign; break;
11463   case tok::slashequal:           Opc = BO_DivAssign; break;
11464   case tok::percentequal:         Opc = BO_RemAssign; break;
11465   case tok::plusequal:            Opc = BO_AddAssign; break;
11466   case tok::minusequal:           Opc = BO_SubAssign; break;
11467   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11468   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11469   case tok::ampequal:             Opc = BO_AndAssign; break;
11470   case tok::caretequal:           Opc = BO_XorAssign; break;
11471   case tok::pipeequal:            Opc = BO_OrAssign; break;
11472   case tok::comma:                Opc = BO_Comma; break;
11473   }
11474   return Opc;
11475 }
11476 
11477 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11478   tok::TokenKind Kind) {
11479   UnaryOperatorKind Opc;
11480   switch (Kind) {
11481   default: llvm_unreachable("Unknown unary op!");
11482   case tok::plusplus:     Opc = UO_PreInc; break;
11483   case tok::minusminus:   Opc = UO_PreDec; break;
11484   case tok::amp:          Opc = UO_AddrOf; break;
11485   case tok::star:         Opc = UO_Deref; break;
11486   case tok::plus:         Opc = UO_Plus; break;
11487   case tok::minus:        Opc = UO_Minus; break;
11488   case tok::tilde:        Opc = UO_Not; break;
11489   case tok::exclaim:      Opc = UO_LNot; break;
11490   case tok::kw___real:    Opc = UO_Real; break;
11491   case tok::kw___imag:    Opc = UO_Imag; break;
11492   case tok::kw___extension__: Opc = UO_Extension; break;
11493   }
11494   return Opc;
11495 }
11496 
11497 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11498 /// This warning suppressed in the event of macro expansions.
11499 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11500                                    SourceLocation OpLoc, bool IsBuiltin) {
11501   if (S.inTemplateInstantiation())
11502     return;
11503   if (S.isUnevaluatedContext())
11504     return;
11505   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11506     return;
11507   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11508   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11509   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11510   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11511   if (!LHSDeclRef || !RHSDeclRef ||
11512       LHSDeclRef->getLocation().isMacroID() ||
11513       RHSDeclRef->getLocation().isMacroID())
11514     return;
11515   const ValueDecl *LHSDecl =
11516     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11517   const ValueDecl *RHSDecl =
11518     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11519   if (LHSDecl != RHSDecl)
11520     return;
11521   if (LHSDecl->getType().isVolatileQualified())
11522     return;
11523   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11524     if (RefTy->getPointeeType().isVolatileQualified())
11525       return;
11526 
11527   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11528                           : diag::warn_self_assignment_overloaded)
11529       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11530       << RHSExpr->getSourceRange();
11531 }
11532 
11533 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11534 /// is usually indicative of introspection within the Objective-C pointer.
11535 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11536                                           SourceLocation OpLoc) {
11537   if (!S.getLangOpts().ObjC1)
11538     return;
11539 
11540   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11541   const Expr *LHS = L.get();
11542   const Expr *RHS = R.get();
11543 
11544   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11545     ObjCPointerExpr = LHS;
11546     OtherExpr = RHS;
11547   }
11548   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11549     ObjCPointerExpr = RHS;
11550     OtherExpr = LHS;
11551   }
11552 
11553   // This warning is deliberately made very specific to reduce false
11554   // positives with logic that uses '&' for hashing.  This logic mainly
11555   // looks for code trying to introspect into tagged pointers, which
11556   // code should generally never do.
11557   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11558     unsigned Diag = diag::warn_objc_pointer_masking;
11559     // Determine if we are introspecting the result of performSelectorXXX.
11560     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11561     // Special case messages to -performSelector and friends, which
11562     // can return non-pointer values boxed in a pointer value.
11563     // Some clients may wish to silence warnings in this subcase.
11564     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11565       Selector S = ME->getSelector();
11566       StringRef SelArg0 = S.getNameForSlot(0);
11567       if (SelArg0.startswith("performSelector"))
11568         Diag = diag::warn_objc_pointer_masking_performSelector;
11569     }
11570 
11571     S.Diag(OpLoc, Diag)
11572       << ObjCPointerExpr->getSourceRange();
11573   }
11574 }
11575 
11576 static NamedDecl *getDeclFromExpr(Expr *E) {
11577   if (!E)
11578     return nullptr;
11579   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11580     return DRE->getDecl();
11581   if (auto *ME = dyn_cast<MemberExpr>(E))
11582     return ME->getMemberDecl();
11583   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11584     return IRE->getDecl();
11585   return nullptr;
11586 }
11587 
11588 // This helper function promotes a binary operator's operands (which are of a
11589 // half vector type) to a vector of floats and then truncates the result to
11590 // a vector of either half or short.
11591 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11592                                       BinaryOperatorKind Opc, QualType ResultTy,
11593                                       ExprValueKind VK, ExprObjectKind OK,
11594                                       bool IsCompAssign, SourceLocation OpLoc,
11595                                       FPOptions FPFeatures) {
11596   auto &Context = S.getASTContext();
11597   assert((isVector(ResultTy, Context.HalfTy) ||
11598           isVector(ResultTy, Context.ShortTy)) &&
11599          "Result must be a vector of half or short");
11600   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11601          isVector(RHS.get()->getType(), Context.HalfTy) &&
11602          "both operands expected to be a half vector");
11603 
11604   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11605   QualType BinOpResTy = RHS.get()->getType();
11606 
11607   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11608   // change BinOpResTy to a vector of ints.
11609   if (isVector(ResultTy, Context.ShortTy))
11610     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11611 
11612   if (IsCompAssign)
11613     return new (Context) CompoundAssignOperator(
11614         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11615         OpLoc, FPFeatures);
11616 
11617   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11618   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11619                                           VK, OK, OpLoc, FPFeatures);
11620   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11621 }
11622 
11623 static std::pair<ExprResult, ExprResult>
11624 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11625                            Expr *RHSExpr) {
11626   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11627   if (!S.getLangOpts().CPlusPlus) {
11628     // C cannot handle TypoExpr nodes on either side of a binop because it
11629     // doesn't handle dependent types properly, so make sure any TypoExprs have
11630     // been dealt with before checking the operands.
11631     LHS = S.CorrectDelayedTyposInExpr(LHS);
11632     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11633       if (Opc != BO_Assign)
11634         return ExprResult(E);
11635       // Avoid correcting the RHS to the same Expr as the LHS.
11636       Decl *D = getDeclFromExpr(E);
11637       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11638     });
11639   }
11640   return std::make_pair(LHS, RHS);
11641 }
11642 
11643 /// Returns true if conversion between vectors of halfs and vectors of floats
11644 /// is needed.
11645 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11646                                      QualType SrcType) {
11647   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11648          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11649          isVector(SrcType, Ctx.HalfTy);
11650 }
11651 
11652 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11653 /// operator @p Opc at location @c TokLoc. This routine only supports
11654 /// built-in operations; ActOnBinOp handles overloaded operators.
11655 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11656                                     BinaryOperatorKind Opc,
11657                                     Expr *LHSExpr, Expr *RHSExpr) {
11658   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11659     // The syntax only allows initializer lists on the RHS of assignment,
11660     // so we don't need to worry about accepting invalid code for
11661     // non-assignment operators.
11662     // C++11 5.17p9:
11663     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11664     //   of x = {} is x = T().
11665     InitializationKind Kind = InitializationKind::CreateDirectList(
11666         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
11667     InitializedEntity Entity =
11668         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11669     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11670     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11671     if (Init.isInvalid())
11672       return Init;
11673     RHSExpr = Init.get();
11674   }
11675 
11676   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11677   QualType ResultTy;     // Result type of the binary operator.
11678   // The following two variables are used for compound assignment operators
11679   QualType CompLHSTy;    // Type of LHS after promotions for computation
11680   QualType CompResultTy; // Type of computation result
11681   ExprValueKind VK = VK_RValue;
11682   ExprObjectKind OK = OK_Ordinary;
11683   bool ConvertHalfVec = false;
11684 
11685   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11686   if (!LHS.isUsable() || !RHS.isUsable())
11687     return ExprError();
11688 
11689   if (getLangOpts().OpenCL) {
11690     QualType LHSTy = LHSExpr->getType();
11691     QualType RHSTy = RHSExpr->getType();
11692     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11693     // the ATOMIC_VAR_INIT macro.
11694     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11695       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11696       if (BO_Assign == Opc)
11697         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11698       else
11699         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11700       return ExprError();
11701     }
11702 
11703     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11704     // only with a builtin functions and therefore should be disallowed here.
11705     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11706         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11707         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11708         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11709       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11710       return ExprError();
11711     }
11712   }
11713 
11714   switch (Opc) {
11715   case BO_Assign:
11716     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11717     if (getLangOpts().CPlusPlus &&
11718         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11719       VK = LHS.get()->getValueKind();
11720       OK = LHS.get()->getObjectKind();
11721     }
11722     if (!ResultTy.isNull()) {
11723       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11724       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11725     }
11726     RecordModifiableNonNullParam(*this, LHS.get());
11727     break;
11728   case BO_PtrMemD:
11729   case BO_PtrMemI:
11730     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11731                                             Opc == BO_PtrMemI);
11732     break;
11733   case BO_Mul:
11734   case BO_Div:
11735     ConvertHalfVec = true;
11736     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11737                                            Opc == BO_Div);
11738     break;
11739   case BO_Rem:
11740     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11741     break;
11742   case BO_Add:
11743     ConvertHalfVec = true;
11744     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11745     break;
11746   case BO_Sub:
11747     ConvertHalfVec = true;
11748     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11749     break;
11750   case BO_Shl:
11751   case BO_Shr:
11752     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11753     break;
11754   case BO_LE:
11755   case BO_LT:
11756   case BO_GE:
11757   case BO_GT:
11758     ConvertHalfVec = true;
11759     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11760     break;
11761   case BO_EQ:
11762   case BO_NE:
11763     ConvertHalfVec = true;
11764     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11765     break;
11766   case BO_Cmp:
11767     // FIXME: Implement proper semantic checking of '<=>'.
11768     ConvertHalfVec = true;
11769     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11770     if (!ResultTy.isNull())
11771       ResultTy = Context.VoidTy;
11772     break;
11773   case BO_And:
11774     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11775     LLVM_FALLTHROUGH;
11776   case BO_Xor:
11777   case BO_Or:
11778     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11779     break;
11780   case BO_LAnd:
11781   case BO_LOr:
11782     ConvertHalfVec = true;
11783     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11784     break;
11785   case BO_MulAssign:
11786   case BO_DivAssign:
11787     ConvertHalfVec = true;
11788     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11789                                                Opc == BO_DivAssign);
11790     CompLHSTy = CompResultTy;
11791     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11792       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11793     break;
11794   case BO_RemAssign:
11795     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11796     CompLHSTy = CompResultTy;
11797     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11798       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11799     break;
11800   case BO_AddAssign:
11801     ConvertHalfVec = true;
11802     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11803     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11804       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11805     break;
11806   case BO_SubAssign:
11807     ConvertHalfVec = true;
11808     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11809     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11810       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11811     break;
11812   case BO_ShlAssign:
11813   case BO_ShrAssign:
11814     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11815     CompLHSTy = CompResultTy;
11816     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11817       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11818     break;
11819   case BO_AndAssign:
11820   case BO_OrAssign: // fallthrough
11821     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11822     LLVM_FALLTHROUGH;
11823   case BO_XorAssign:
11824     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11825     CompLHSTy = CompResultTy;
11826     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11827       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11828     break;
11829   case BO_Comma:
11830     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11831     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11832       VK = RHS.get()->getValueKind();
11833       OK = RHS.get()->getObjectKind();
11834     }
11835     break;
11836   }
11837   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11838     return ExprError();
11839 
11840   // Some of the binary operations require promoting operands of half vector to
11841   // float vectors and truncating the result back to half vector. For now, we do
11842   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
11843   // arm64).
11844   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
11845          isVector(LHS.get()->getType(), Context.HalfTy) &&
11846          "both sides are half vectors or neither sides are");
11847   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
11848                                             LHS.get()->getType());
11849 
11850   // Check for array bounds violations for both sides of the BinaryOperator
11851   CheckArrayAccess(LHS.get());
11852   CheckArrayAccess(RHS.get());
11853 
11854   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11855     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11856                                                  &Context.Idents.get("object_setClass"),
11857                                                  SourceLocation(), LookupOrdinaryName);
11858     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11859       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11860       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11861       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11862       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11863       FixItHint::CreateInsertion(RHSLocEnd, ")");
11864     }
11865     else
11866       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11867   }
11868   else if (const ObjCIvarRefExpr *OIRE =
11869            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11870     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11871 
11872   // Opc is not a compound assignment if CompResultTy is null.
11873   if (CompResultTy.isNull()) {
11874     if (ConvertHalfVec)
11875       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
11876                                  OpLoc, FPFeatures);
11877     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11878                                         OK, OpLoc, FPFeatures);
11879   }
11880 
11881   // Handle compound assignments.
11882   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11883       OK_ObjCProperty) {
11884     VK = VK_LValue;
11885     OK = LHS.get()->getObjectKind();
11886   }
11887 
11888   if (ConvertHalfVec)
11889     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
11890                                OpLoc, FPFeatures);
11891 
11892   return new (Context) CompoundAssignOperator(
11893       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11894       OpLoc, FPFeatures);
11895 }
11896 
11897 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11898 /// operators are mixed in a way that suggests that the programmer forgot that
11899 /// comparison operators have higher precedence. The most typical example of
11900 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11901 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11902                                       SourceLocation OpLoc, Expr *LHSExpr,
11903                                       Expr *RHSExpr) {
11904   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11905   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11906 
11907   // Check that one of the sides is a comparison operator and the other isn't.
11908   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11909   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11910   if (isLeftComp == isRightComp)
11911     return;
11912 
11913   // Bitwise operations are sometimes used as eager logical ops.
11914   // Don't diagnose this.
11915   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11916   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11917   if (isLeftBitwise || isRightBitwise)
11918     return;
11919 
11920   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11921                                                    OpLoc)
11922                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11923   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11924   SourceRange ParensRange = isLeftComp ?
11925       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11926     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11927 
11928   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11929     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11930   SuggestParentheses(Self, OpLoc,
11931     Self.PDiag(diag::note_precedence_silence) << OpStr,
11932     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11933   SuggestParentheses(Self, OpLoc,
11934     Self.PDiag(diag::note_precedence_bitwise_first)
11935       << BinaryOperator::getOpcodeStr(Opc),
11936     ParensRange);
11937 }
11938 
11939 /// \brief It accepts a '&&' expr that is inside a '||' one.
11940 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11941 /// in parentheses.
11942 static void
11943 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11944                                        BinaryOperator *Bop) {
11945   assert(Bop->getOpcode() == BO_LAnd);
11946   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11947       << Bop->getSourceRange() << OpLoc;
11948   SuggestParentheses(Self, Bop->getOperatorLoc(),
11949     Self.PDiag(diag::note_precedence_silence)
11950       << Bop->getOpcodeStr(),
11951     Bop->getSourceRange());
11952 }
11953 
11954 /// \brief Returns true if the given expression can be evaluated as a constant
11955 /// 'true'.
11956 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11957   bool Res;
11958   return !E->isValueDependent() &&
11959          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11960 }
11961 
11962 /// \brief Returns true if the given expression can be evaluated as a constant
11963 /// 'false'.
11964 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11965   bool Res;
11966   return !E->isValueDependent() &&
11967          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11968 }
11969 
11970 /// \brief Look for '&&' in the left hand of a '||' expr.
11971 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11972                                              Expr *LHSExpr, Expr *RHSExpr) {
11973   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11974     if (Bop->getOpcode() == BO_LAnd) {
11975       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11976       if (EvaluatesAsFalse(S, RHSExpr))
11977         return;
11978       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11979       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11980         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11981     } else if (Bop->getOpcode() == BO_LOr) {
11982       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11983         // If it's "a || b && 1 || c" we didn't warn earlier for
11984         // "a || b && 1", but warn now.
11985         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11986           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11987       }
11988     }
11989   }
11990 }
11991 
11992 /// \brief Look for '&&' in the right hand of a '||' expr.
11993 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11994                                              Expr *LHSExpr, Expr *RHSExpr) {
11995   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11996     if (Bop->getOpcode() == BO_LAnd) {
11997       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11998       if (EvaluatesAsFalse(S, LHSExpr))
11999         return;
12000       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12001       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12002         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12003     }
12004   }
12005 }
12006 
12007 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
12008 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12009 /// the '&' expression in parentheses.
12010 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12011                                          SourceLocation OpLoc, Expr *SubExpr) {
12012   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12013     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12014       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12015         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12016         << Bop->getSourceRange() << OpLoc;
12017       SuggestParentheses(S, Bop->getOperatorLoc(),
12018         S.PDiag(diag::note_precedence_silence)
12019           << Bop->getOpcodeStr(),
12020         Bop->getSourceRange());
12021     }
12022   }
12023 }
12024 
12025 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12026                                     Expr *SubExpr, StringRef Shift) {
12027   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12028     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12029       StringRef Op = Bop->getOpcodeStr();
12030       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12031           << Bop->getSourceRange() << OpLoc << Shift << Op;
12032       SuggestParentheses(S, Bop->getOperatorLoc(),
12033           S.PDiag(diag::note_precedence_silence) << Op,
12034           Bop->getSourceRange());
12035     }
12036   }
12037 }
12038 
12039 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12040                                  Expr *LHSExpr, Expr *RHSExpr) {
12041   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12042   if (!OCE)
12043     return;
12044 
12045   FunctionDecl *FD = OCE->getDirectCallee();
12046   if (!FD || !FD->isOverloadedOperator())
12047     return;
12048 
12049   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12050   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12051     return;
12052 
12053   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12054       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12055       << (Kind == OO_LessLess);
12056   SuggestParentheses(S, OCE->getOperatorLoc(),
12057                      S.PDiag(diag::note_precedence_silence)
12058                          << (Kind == OO_LessLess ? "<<" : ">>"),
12059                      OCE->getSourceRange());
12060   SuggestParentheses(S, OpLoc,
12061                      S.PDiag(diag::note_evaluate_comparison_first),
12062                      SourceRange(OCE->getArg(1)->getLocStart(),
12063                                  RHSExpr->getLocEnd()));
12064 }
12065 
12066 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12067 /// precedence.
12068 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12069                                     SourceLocation OpLoc, Expr *LHSExpr,
12070                                     Expr *RHSExpr){
12071   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12072   if (BinaryOperator::isBitwiseOp(Opc))
12073     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12074 
12075   // Diagnose "arg1 & arg2 | arg3"
12076   if ((Opc == BO_Or || Opc == BO_Xor) &&
12077       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12078     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12079     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12080   }
12081 
12082   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12083   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12084   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12085     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12086     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12087   }
12088 
12089   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12090       || Opc == BO_Shr) {
12091     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12092     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12093     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12094   }
12095 
12096   // Warn on overloaded shift operators and comparisons, such as:
12097   // cout << 5 == 4;
12098   if (BinaryOperator::isComparisonOp(Opc))
12099     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12100 }
12101 
12102 // Binary Operators.  'Tok' is the token for the operator.
12103 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12104                             tok::TokenKind Kind,
12105                             Expr *LHSExpr, Expr *RHSExpr) {
12106   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12107   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12108   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12109 
12110   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12111   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12112 
12113   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12114 }
12115 
12116 /// Build an overloaded binary operator expression in the given scope.
12117 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12118                                        BinaryOperatorKind Opc,
12119                                        Expr *LHS, Expr *RHS) {
12120   switch (Opc) {
12121   case BO_Assign:
12122   case BO_DivAssign:
12123   case BO_RemAssign:
12124   case BO_SubAssign:
12125   case BO_AndAssign:
12126   case BO_OrAssign:
12127   case BO_XorAssign:
12128     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12129     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12130     break;
12131   default:
12132     break;
12133   }
12134 
12135   // Find all of the overloaded operators visible from this
12136   // point. We perform both an operator-name lookup from the local
12137   // scope and an argument-dependent lookup based on the types of
12138   // the arguments.
12139   UnresolvedSet<16> Functions;
12140   OverloadedOperatorKind OverOp
12141     = BinaryOperator::getOverloadedOperator(Opc);
12142   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12143     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12144                                    RHS->getType(), Functions);
12145 
12146   // Build the (potentially-overloaded, potentially-dependent)
12147   // binary operation.
12148   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12149 }
12150 
12151 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12152                             BinaryOperatorKind Opc,
12153                             Expr *LHSExpr, Expr *RHSExpr) {
12154   ExprResult LHS, RHS;
12155   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12156   if (!LHS.isUsable() || !RHS.isUsable())
12157     return ExprError();
12158   LHSExpr = LHS.get();
12159   RHSExpr = RHS.get();
12160 
12161   // We want to end up calling one of checkPseudoObjectAssignment
12162   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12163   // both expressions are overloadable or either is type-dependent),
12164   // or CreateBuiltinBinOp (in any other case).  We also want to get
12165   // any placeholder types out of the way.
12166 
12167   // Handle pseudo-objects in the LHS.
12168   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12169     // Assignments with a pseudo-object l-value need special analysis.
12170     if (pty->getKind() == BuiltinType::PseudoObject &&
12171         BinaryOperator::isAssignmentOp(Opc))
12172       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12173 
12174     // Don't resolve overloads if the other type is overloadable.
12175     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12176       // We can't actually test that if we still have a placeholder,
12177       // though.  Fortunately, none of the exceptions we see in that
12178       // code below are valid when the LHS is an overload set.  Note
12179       // that an overload set can be dependently-typed, but it never
12180       // instantiates to having an overloadable type.
12181       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12182       if (resolvedRHS.isInvalid()) return ExprError();
12183       RHSExpr = resolvedRHS.get();
12184 
12185       if (RHSExpr->isTypeDependent() ||
12186           RHSExpr->getType()->isOverloadableType())
12187         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12188     }
12189 
12190     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12191     // template, diagnose the missing 'template' keyword instead of diagnosing
12192     // an invalid use of a bound member function.
12193     //
12194     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12195     // to C++1z [over.over]/1.4, but we already checked for that case above.
12196     if (Opc == BO_LT && inTemplateInstantiation() &&
12197         (pty->getKind() == BuiltinType::BoundMember ||
12198          pty->getKind() == BuiltinType::Overload)) {
12199       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12200       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12201           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12202             return isa<FunctionTemplateDecl>(ND);
12203           })) {
12204         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12205                                 : OE->getNameLoc(),
12206              diag::err_template_kw_missing)
12207           << OE->getName().getAsString() << "";
12208         return ExprError();
12209       }
12210     }
12211 
12212     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12213     if (LHS.isInvalid()) return ExprError();
12214     LHSExpr = LHS.get();
12215   }
12216 
12217   // Handle pseudo-objects in the RHS.
12218   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12219     // An overload in the RHS can potentially be resolved by the type
12220     // being assigned to.
12221     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12222       if (getLangOpts().CPlusPlus &&
12223           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12224            LHSExpr->getType()->isOverloadableType()))
12225         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12226 
12227       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12228     }
12229 
12230     // Don't resolve overloads if the other type is overloadable.
12231     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12232         LHSExpr->getType()->isOverloadableType())
12233       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12234 
12235     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12236     if (!resolvedRHS.isUsable()) return ExprError();
12237     RHSExpr = resolvedRHS.get();
12238   }
12239 
12240   if (getLangOpts().CPlusPlus) {
12241     // If either expression is type-dependent, always build an
12242     // overloaded op.
12243     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12244       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12245 
12246     // Otherwise, build an overloaded op if either expression has an
12247     // overloadable type.
12248     if (LHSExpr->getType()->isOverloadableType() ||
12249         RHSExpr->getType()->isOverloadableType())
12250       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12251   }
12252 
12253   // Build a built-in binary operation.
12254   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12255 }
12256 
12257 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12258   if (T.isNull() || T->isDependentType())
12259     return false;
12260 
12261   if (!T->isPromotableIntegerType())
12262     return true;
12263 
12264   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12265 }
12266 
12267 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12268                                       UnaryOperatorKind Opc,
12269                                       Expr *InputExpr) {
12270   ExprResult Input = InputExpr;
12271   ExprValueKind VK = VK_RValue;
12272   ExprObjectKind OK = OK_Ordinary;
12273   QualType resultType;
12274   bool CanOverflow = false;
12275 
12276   bool ConvertHalfVec = false;
12277   if (getLangOpts().OpenCL) {
12278     QualType Ty = InputExpr->getType();
12279     // The only legal unary operation for atomics is '&'.
12280     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12281     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12282     // only with a builtin functions and therefore should be disallowed here.
12283         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12284         || Ty->isBlockPointerType())) {
12285       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12286                        << InputExpr->getType()
12287                        << Input.get()->getSourceRange());
12288     }
12289   }
12290   switch (Opc) {
12291   case UO_PreInc:
12292   case UO_PreDec:
12293   case UO_PostInc:
12294   case UO_PostDec:
12295     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12296                                                 OpLoc,
12297                                                 Opc == UO_PreInc ||
12298                                                 Opc == UO_PostInc,
12299                                                 Opc == UO_PreInc ||
12300                                                 Opc == UO_PreDec);
12301     CanOverflow = isOverflowingIntegerType(Context, resultType);
12302     break;
12303   case UO_AddrOf:
12304     resultType = CheckAddressOfOperand(Input, OpLoc);
12305     RecordModifiableNonNullParam(*this, InputExpr);
12306     break;
12307   case UO_Deref: {
12308     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12309     if (Input.isInvalid()) return ExprError();
12310     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12311     break;
12312   }
12313   case UO_Plus:
12314   case UO_Minus:
12315     CanOverflow = Opc == UO_Minus &&
12316                   isOverflowingIntegerType(Context, Input.get()->getType());
12317     Input = UsualUnaryConversions(Input.get());
12318     if (Input.isInvalid()) return ExprError();
12319     // Unary plus and minus require promoting an operand of half vector to a
12320     // float vector and truncating the result back to a half vector. For now, we
12321     // do this only when HalfArgsAndReturns is set (that is, when the target is
12322     // arm or arm64).
12323     ConvertHalfVec =
12324         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12325 
12326     // If the operand is a half vector, promote it to a float vector.
12327     if (ConvertHalfVec)
12328       Input = convertVector(Input.get(), Context.FloatTy, *this);
12329     resultType = Input.get()->getType();
12330     if (resultType->isDependentType())
12331       break;
12332     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12333       break;
12334     else if (resultType->isVectorType() &&
12335              // The z vector extensions don't allow + or - with bool vectors.
12336              (!Context.getLangOpts().ZVector ||
12337               resultType->getAs<VectorType>()->getVectorKind() !=
12338               VectorType::AltiVecBool))
12339       break;
12340     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12341              Opc == UO_Plus &&
12342              resultType->isPointerType())
12343       break;
12344 
12345     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12346       << resultType << Input.get()->getSourceRange());
12347 
12348   case UO_Not: // bitwise complement
12349     Input = UsualUnaryConversions(Input.get());
12350     if (Input.isInvalid())
12351       return ExprError();
12352     resultType = Input.get()->getType();
12353 
12354     if (resultType->isDependentType())
12355       break;
12356     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12357     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12358       // C99 does not support '~' for complex conjugation.
12359       Diag(OpLoc, diag::ext_integer_complement_complex)
12360           << resultType << Input.get()->getSourceRange();
12361     else if (resultType->hasIntegerRepresentation())
12362       break;
12363     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12364       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12365       // on vector float types.
12366       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12367       if (!T->isIntegerType())
12368         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12369                           << resultType << Input.get()->getSourceRange());
12370     } else {
12371       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12372                        << resultType << Input.get()->getSourceRange());
12373     }
12374     break;
12375 
12376   case UO_LNot: // logical negation
12377     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12378     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12379     if (Input.isInvalid()) return ExprError();
12380     resultType = Input.get()->getType();
12381 
12382     // Though we still have to promote half FP to float...
12383     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12384       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12385       resultType = Context.FloatTy;
12386     }
12387 
12388     if (resultType->isDependentType())
12389       break;
12390     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12391       // C99 6.5.3.3p1: ok, fallthrough;
12392       if (Context.getLangOpts().CPlusPlus) {
12393         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12394         // operand contextually converted to bool.
12395         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12396                                   ScalarTypeToBooleanCastKind(resultType));
12397       } else if (Context.getLangOpts().OpenCL &&
12398                  Context.getLangOpts().OpenCLVersion < 120) {
12399         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12400         // operate on scalar float types.
12401         if (!resultType->isIntegerType() && !resultType->isPointerType())
12402           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12403                            << resultType << Input.get()->getSourceRange());
12404       }
12405     } else if (resultType->isExtVectorType()) {
12406       if (Context.getLangOpts().OpenCL &&
12407           Context.getLangOpts().OpenCLVersion < 120) {
12408         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12409         // operate on vector float types.
12410         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12411         if (!T->isIntegerType())
12412           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12413                            << resultType << Input.get()->getSourceRange());
12414       }
12415       // Vector logical not returns the signed variant of the operand type.
12416       resultType = GetSignedVectorType(resultType);
12417       break;
12418     } else {
12419       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12420       //        type in C++. We should allow that here too.
12421       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12422         << resultType << Input.get()->getSourceRange());
12423     }
12424 
12425     // LNot always has type int. C99 6.5.3.3p5.
12426     // In C++, it's bool. C++ 5.3.1p8
12427     resultType = Context.getLogicalOperationType();
12428     break;
12429   case UO_Real:
12430   case UO_Imag:
12431     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12432     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12433     // complex l-values to ordinary l-values and all other values to r-values.
12434     if (Input.isInvalid()) return ExprError();
12435     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12436       if (Input.get()->getValueKind() != VK_RValue &&
12437           Input.get()->getObjectKind() == OK_Ordinary)
12438         VK = Input.get()->getValueKind();
12439     } else if (!getLangOpts().CPlusPlus) {
12440       // In C, a volatile scalar is read by __imag. In C++, it is not.
12441       Input = DefaultLvalueConversion(Input.get());
12442     }
12443     break;
12444   case UO_Extension:
12445     resultType = Input.get()->getType();
12446     VK = Input.get()->getValueKind();
12447     OK = Input.get()->getObjectKind();
12448     break;
12449   case UO_Coawait:
12450     // It's unnecessary to represent the pass-through operator co_await in the
12451     // AST; just return the input expression instead.
12452     assert(!Input.get()->getType()->isDependentType() &&
12453                    "the co_await expression must be non-dependant before "
12454                    "building operator co_await");
12455     return Input;
12456   }
12457   if (resultType.isNull() || Input.isInvalid())
12458     return ExprError();
12459 
12460   // Check for array bounds violations in the operand of the UnaryOperator,
12461   // except for the '*' and '&' operators that have to be handled specially
12462   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12463   // that are explicitly defined as valid by the standard).
12464   if (Opc != UO_AddrOf && Opc != UO_Deref)
12465     CheckArrayAccess(Input.get());
12466 
12467   auto *UO = new (Context)
12468       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12469   // Convert the result back to a half vector.
12470   if (ConvertHalfVec)
12471     return convertVector(UO, Context.HalfTy, *this);
12472   return UO;
12473 }
12474 
12475 /// \brief Determine whether the given expression is a qualified member
12476 /// access expression, of a form that could be turned into a pointer to member
12477 /// with the address-of operator.
12478 static bool isQualifiedMemberAccess(Expr *E) {
12479   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12480     if (!DRE->getQualifier())
12481       return false;
12482 
12483     ValueDecl *VD = DRE->getDecl();
12484     if (!VD->isCXXClassMember())
12485       return false;
12486 
12487     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12488       return true;
12489     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12490       return Method->isInstance();
12491 
12492     return false;
12493   }
12494 
12495   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12496     if (!ULE->getQualifier())
12497       return false;
12498 
12499     for (NamedDecl *D : ULE->decls()) {
12500       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12501         if (Method->isInstance())
12502           return true;
12503       } else {
12504         // Overload set does not contain methods.
12505         break;
12506       }
12507     }
12508 
12509     return false;
12510   }
12511 
12512   return false;
12513 }
12514 
12515 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12516                               UnaryOperatorKind Opc, Expr *Input) {
12517   // First things first: handle placeholders so that the
12518   // overloaded-operator check considers the right type.
12519   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12520     // Increment and decrement of pseudo-object references.
12521     if (pty->getKind() == BuiltinType::PseudoObject &&
12522         UnaryOperator::isIncrementDecrementOp(Opc))
12523       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12524 
12525     // extension is always a builtin operator.
12526     if (Opc == UO_Extension)
12527       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12528 
12529     // & gets special logic for several kinds of placeholder.
12530     // The builtin code knows what to do.
12531     if (Opc == UO_AddrOf &&
12532         (pty->getKind() == BuiltinType::Overload ||
12533          pty->getKind() == BuiltinType::UnknownAny ||
12534          pty->getKind() == BuiltinType::BoundMember))
12535       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12536 
12537     // Anything else needs to be handled now.
12538     ExprResult Result = CheckPlaceholderExpr(Input);
12539     if (Result.isInvalid()) return ExprError();
12540     Input = Result.get();
12541   }
12542 
12543   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12544       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12545       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12546     // Find all of the overloaded operators visible from this
12547     // point. We perform both an operator-name lookup from the local
12548     // scope and an argument-dependent lookup based on the types of
12549     // the arguments.
12550     UnresolvedSet<16> Functions;
12551     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12552     if (S && OverOp != OO_None)
12553       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12554                                    Functions);
12555 
12556     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12557   }
12558 
12559   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12560 }
12561 
12562 // Unary Operators.  'Tok' is the token for the operator.
12563 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12564                               tok::TokenKind Op, Expr *Input) {
12565   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12566 }
12567 
12568 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12569 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12570                                 LabelDecl *TheDecl) {
12571   TheDecl->markUsed(Context);
12572   // Create the AST node.  The address of a label always has type 'void*'.
12573   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12574                                      Context.getPointerType(Context.VoidTy));
12575 }
12576 
12577 /// Given the last statement in a statement-expression, check whether
12578 /// the result is a producing expression (like a call to an
12579 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12580 /// release out of the full-expression.  Otherwise, return null.
12581 /// Cannot fail.
12582 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12583   // Should always be wrapped with one of these.
12584   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12585   if (!cleanups) return nullptr;
12586 
12587   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12588   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12589     return nullptr;
12590 
12591   // Splice out the cast.  This shouldn't modify any interesting
12592   // features of the statement.
12593   Expr *producer = cast->getSubExpr();
12594   assert(producer->getType() == cast->getType());
12595   assert(producer->getValueKind() == cast->getValueKind());
12596   cleanups->setSubExpr(producer);
12597   return cleanups;
12598 }
12599 
12600 void Sema::ActOnStartStmtExpr() {
12601   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12602 }
12603 
12604 void Sema::ActOnStmtExprError() {
12605   // Note that function is also called by TreeTransform when leaving a
12606   // StmtExpr scope without rebuilding anything.
12607 
12608   DiscardCleanupsInEvaluationContext();
12609   PopExpressionEvaluationContext();
12610 }
12611 
12612 ExprResult
12613 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12614                     SourceLocation RPLoc) { // "({..})"
12615   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12616   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12617 
12618   if (hasAnyUnrecoverableErrorsInThisFunction())
12619     DiscardCleanupsInEvaluationContext();
12620   assert(!Cleanup.exprNeedsCleanups() &&
12621          "cleanups within StmtExpr not correctly bound!");
12622   PopExpressionEvaluationContext();
12623 
12624   // FIXME: there are a variety of strange constraints to enforce here, for
12625   // example, it is not possible to goto into a stmt expression apparently.
12626   // More semantic analysis is needed.
12627 
12628   // If there are sub-stmts in the compound stmt, take the type of the last one
12629   // as the type of the stmtexpr.
12630   QualType Ty = Context.VoidTy;
12631   bool StmtExprMayBindToTemp = false;
12632   if (!Compound->body_empty()) {
12633     Stmt *LastStmt = Compound->body_back();
12634     LabelStmt *LastLabelStmt = nullptr;
12635     // If LastStmt is a label, skip down through into the body.
12636     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12637       LastLabelStmt = Label;
12638       LastStmt = Label->getSubStmt();
12639     }
12640 
12641     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12642       // Do function/array conversion on the last expression, but not
12643       // lvalue-to-rvalue.  However, initialize an unqualified type.
12644       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12645       if (LastExpr.isInvalid())
12646         return ExprError();
12647       Ty = LastExpr.get()->getType().getUnqualifiedType();
12648 
12649       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12650         // In ARC, if the final expression ends in a consume, splice
12651         // the consume out and bind it later.  In the alternate case
12652         // (when dealing with a retainable type), the result
12653         // initialization will create a produce.  In both cases the
12654         // result will be +1, and we'll need to balance that out with
12655         // a bind.
12656         if (Expr *rebuiltLastStmt
12657               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12658           LastExpr = rebuiltLastStmt;
12659         } else {
12660           LastExpr = PerformCopyInitialization(
12661                             InitializedEntity::InitializeResult(LPLoc,
12662                                                                 Ty,
12663                                                                 false),
12664                                                    SourceLocation(),
12665                                                LastExpr);
12666         }
12667 
12668         if (LastExpr.isInvalid())
12669           return ExprError();
12670         if (LastExpr.get() != nullptr) {
12671           if (!LastLabelStmt)
12672             Compound->setLastStmt(LastExpr.get());
12673           else
12674             LastLabelStmt->setSubStmt(LastExpr.get());
12675           StmtExprMayBindToTemp = true;
12676         }
12677       }
12678     }
12679   }
12680 
12681   // FIXME: Check that expression type is complete/non-abstract; statement
12682   // expressions are not lvalues.
12683   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12684   if (StmtExprMayBindToTemp)
12685     return MaybeBindToTemporary(ResStmtExpr);
12686   return ResStmtExpr;
12687 }
12688 
12689 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12690                                       TypeSourceInfo *TInfo,
12691                                       ArrayRef<OffsetOfComponent> Components,
12692                                       SourceLocation RParenLoc) {
12693   QualType ArgTy = TInfo->getType();
12694   bool Dependent = ArgTy->isDependentType();
12695   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12696 
12697   // We must have at least one component that refers to the type, and the first
12698   // one is known to be a field designator.  Verify that the ArgTy represents
12699   // a struct/union/class.
12700   if (!Dependent && !ArgTy->isRecordType())
12701     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12702                        << ArgTy << TypeRange);
12703 
12704   // Type must be complete per C99 7.17p3 because a declaring a variable
12705   // with an incomplete type would be ill-formed.
12706   if (!Dependent
12707       && RequireCompleteType(BuiltinLoc, ArgTy,
12708                              diag::err_offsetof_incomplete_type, TypeRange))
12709     return ExprError();
12710 
12711   bool DidWarnAboutNonPOD = false;
12712   QualType CurrentType = ArgTy;
12713   SmallVector<OffsetOfNode, 4> Comps;
12714   SmallVector<Expr*, 4> Exprs;
12715   for (const OffsetOfComponent &OC : Components) {
12716     if (OC.isBrackets) {
12717       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12718       if (!CurrentType->isDependentType()) {
12719         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12720         if(!AT)
12721           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12722                            << CurrentType);
12723         CurrentType = AT->getElementType();
12724       } else
12725         CurrentType = Context.DependentTy;
12726 
12727       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12728       if (IdxRval.isInvalid())
12729         return ExprError();
12730       Expr *Idx = IdxRval.get();
12731 
12732       // The expression must be an integral expression.
12733       // FIXME: An integral constant expression?
12734       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12735           !Idx->getType()->isIntegerType())
12736         return ExprError(Diag(Idx->getLocStart(),
12737                               diag::err_typecheck_subscript_not_integer)
12738                          << Idx->getSourceRange());
12739 
12740       // Record this array index.
12741       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12742       Exprs.push_back(Idx);
12743       continue;
12744     }
12745 
12746     // Offset of a field.
12747     if (CurrentType->isDependentType()) {
12748       // We have the offset of a field, but we can't look into the dependent
12749       // type. Just record the identifier of the field.
12750       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12751       CurrentType = Context.DependentTy;
12752       continue;
12753     }
12754 
12755     // We need to have a complete type to look into.
12756     if (RequireCompleteType(OC.LocStart, CurrentType,
12757                             diag::err_offsetof_incomplete_type))
12758       return ExprError();
12759 
12760     // Look for the designated field.
12761     const RecordType *RC = CurrentType->getAs<RecordType>();
12762     if (!RC)
12763       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12764                        << CurrentType);
12765     RecordDecl *RD = RC->getDecl();
12766 
12767     // C++ [lib.support.types]p5:
12768     //   The macro offsetof accepts a restricted set of type arguments in this
12769     //   International Standard. type shall be a POD structure or a POD union
12770     //   (clause 9).
12771     // C++11 [support.types]p4:
12772     //   If type is not a standard-layout class (Clause 9), the results are
12773     //   undefined.
12774     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12775       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12776       unsigned DiagID =
12777         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12778                             : diag::ext_offsetof_non_pod_type;
12779 
12780       if (!IsSafe && !DidWarnAboutNonPOD &&
12781           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12782                               PDiag(DiagID)
12783                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12784                               << CurrentType))
12785         DidWarnAboutNonPOD = true;
12786     }
12787 
12788     // Look for the field.
12789     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12790     LookupQualifiedName(R, RD);
12791     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12792     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12793     if (!MemberDecl) {
12794       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12795         MemberDecl = IndirectMemberDecl->getAnonField();
12796     }
12797 
12798     if (!MemberDecl)
12799       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12800                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12801                                                               OC.LocEnd));
12802 
12803     // C99 7.17p3:
12804     //   (If the specified member is a bit-field, the behavior is undefined.)
12805     //
12806     // We diagnose this as an error.
12807     if (MemberDecl->isBitField()) {
12808       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12809         << MemberDecl->getDeclName()
12810         << SourceRange(BuiltinLoc, RParenLoc);
12811       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12812       return ExprError();
12813     }
12814 
12815     RecordDecl *Parent = MemberDecl->getParent();
12816     if (IndirectMemberDecl)
12817       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12818 
12819     // If the member was found in a base class, introduce OffsetOfNodes for
12820     // the base class indirections.
12821     CXXBasePaths Paths;
12822     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12823                       Paths)) {
12824       if (Paths.getDetectedVirtual()) {
12825         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12826           << MemberDecl->getDeclName()
12827           << SourceRange(BuiltinLoc, RParenLoc);
12828         return ExprError();
12829       }
12830 
12831       CXXBasePath &Path = Paths.front();
12832       for (const CXXBasePathElement &B : Path)
12833         Comps.push_back(OffsetOfNode(B.Base));
12834     }
12835 
12836     if (IndirectMemberDecl) {
12837       for (auto *FI : IndirectMemberDecl->chain()) {
12838         assert(isa<FieldDecl>(FI));
12839         Comps.push_back(OffsetOfNode(OC.LocStart,
12840                                      cast<FieldDecl>(FI), OC.LocEnd));
12841       }
12842     } else
12843       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12844 
12845     CurrentType = MemberDecl->getType().getNonReferenceType();
12846   }
12847 
12848   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12849                               Comps, Exprs, RParenLoc);
12850 }
12851 
12852 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12853                                       SourceLocation BuiltinLoc,
12854                                       SourceLocation TypeLoc,
12855                                       ParsedType ParsedArgTy,
12856                                       ArrayRef<OffsetOfComponent> Components,
12857                                       SourceLocation RParenLoc) {
12858 
12859   TypeSourceInfo *ArgTInfo;
12860   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12861   if (ArgTy.isNull())
12862     return ExprError();
12863 
12864   if (!ArgTInfo)
12865     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12866 
12867   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12868 }
12869 
12870 
12871 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12872                                  Expr *CondExpr,
12873                                  Expr *LHSExpr, Expr *RHSExpr,
12874                                  SourceLocation RPLoc) {
12875   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12876 
12877   ExprValueKind VK = VK_RValue;
12878   ExprObjectKind OK = OK_Ordinary;
12879   QualType resType;
12880   bool ValueDependent = false;
12881   bool CondIsTrue = false;
12882   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12883     resType = Context.DependentTy;
12884     ValueDependent = true;
12885   } else {
12886     // The conditional expression is required to be a constant expression.
12887     llvm::APSInt condEval(32);
12888     ExprResult CondICE
12889       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12890           diag::err_typecheck_choose_expr_requires_constant, false);
12891     if (CondICE.isInvalid())
12892       return ExprError();
12893     CondExpr = CondICE.get();
12894     CondIsTrue = condEval.getZExtValue();
12895 
12896     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12897     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12898 
12899     resType = ActiveExpr->getType();
12900     ValueDependent = ActiveExpr->isValueDependent();
12901     VK = ActiveExpr->getValueKind();
12902     OK = ActiveExpr->getObjectKind();
12903   }
12904 
12905   return new (Context)
12906       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12907                  CondIsTrue, resType->isDependentType(), ValueDependent);
12908 }
12909 
12910 //===----------------------------------------------------------------------===//
12911 // Clang Extensions.
12912 //===----------------------------------------------------------------------===//
12913 
12914 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12915 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12916   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12917 
12918   if (LangOpts.CPlusPlus) {
12919     Decl *ManglingContextDecl;
12920     if (MangleNumberingContext *MCtx =
12921             getCurrentMangleNumberContext(Block->getDeclContext(),
12922                                           ManglingContextDecl)) {
12923       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12924       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12925     }
12926   }
12927 
12928   PushBlockScope(CurScope, Block);
12929   CurContext->addDecl(Block);
12930   if (CurScope)
12931     PushDeclContext(CurScope, Block);
12932   else
12933     CurContext = Block;
12934 
12935   getCurBlock()->HasImplicitReturnType = true;
12936 
12937   // Enter a new evaluation context to insulate the block from any
12938   // cleanups from the enclosing full-expression.
12939   PushExpressionEvaluationContext(
12940       ExpressionEvaluationContext::PotentiallyEvaluated);
12941 }
12942 
12943 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12944                                Scope *CurScope) {
12945   assert(ParamInfo.getIdentifier() == nullptr &&
12946          "block-id should have no identifier!");
12947   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
12948   BlockScopeInfo *CurBlock = getCurBlock();
12949 
12950   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12951   QualType T = Sig->getType();
12952 
12953   // FIXME: We should allow unexpanded parameter packs here, but that would,
12954   // in turn, make the block expression contain unexpanded parameter packs.
12955   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12956     // Drop the parameters.
12957     FunctionProtoType::ExtProtoInfo EPI;
12958     EPI.HasTrailingReturn = false;
12959     EPI.TypeQuals |= DeclSpec::TQ_const;
12960     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12961     Sig = Context.getTrivialTypeSourceInfo(T);
12962   }
12963 
12964   // GetTypeForDeclarator always produces a function type for a block
12965   // literal signature.  Furthermore, it is always a FunctionProtoType
12966   // unless the function was written with a typedef.
12967   assert(T->isFunctionType() &&
12968          "GetTypeForDeclarator made a non-function block signature");
12969 
12970   // Look for an explicit signature in that function type.
12971   FunctionProtoTypeLoc ExplicitSignature;
12972 
12973   if ((ExplicitSignature =
12974            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
12975 
12976     // Check whether that explicit signature was synthesized by
12977     // GetTypeForDeclarator.  If so, don't save that as part of the
12978     // written signature.
12979     if (ExplicitSignature.getLocalRangeBegin() ==
12980         ExplicitSignature.getLocalRangeEnd()) {
12981       // This would be much cheaper if we stored TypeLocs instead of
12982       // TypeSourceInfos.
12983       TypeLoc Result = ExplicitSignature.getReturnLoc();
12984       unsigned Size = Result.getFullDataSize();
12985       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12986       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12987 
12988       ExplicitSignature = FunctionProtoTypeLoc();
12989     }
12990   }
12991 
12992   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12993   CurBlock->FunctionType = T;
12994 
12995   const FunctionType *Fn = T->getAs<FunctionType>();
12996   QualType RetTy = Fn->getReturnType();
12997   bool isVariadic =
12998     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12999 
13000   CurBlock->TheDecl->setIsVariadic(isVariadic);
13001 
13002   // Context.DependentTy is used as a placeholder for a missing block
13003   // return type.  TODO:  what should we do with declarators like:
13004   //   ^ * { ... }
13005   // If the answer is "apply template argument deduction"....
13006   if (RetTy != Context.DependentTy) {
13007     CurBlock->ReturnType = RetTy;
13008     CurBlock->TheDecl->setBlockMissingReturnType(false);
13009     CurBlock->HasImplicitReturnType = false;
13010   }
13011 
13012   // Push block parameters from the declarator if we had them.
13013   SmallVector<ParmVarDecl*, 8> Params;
13014   if (ExplicitSignature) {
13015     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13016       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13017       if (Param->getIdentifier() == nullptr &&
13018           !Param->isImplicit() &&
13019           !Param->isInvalidDecl() &&
13020           !getLangOpts().CPlusPlus)
13021         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13022       Params.push_back(Param);
13023     }
13024 
13025   // Fake up parameter variables if we have a typedef, like
13026   //   ^ fntype { ... }
13027   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13028     for (const auto &I : Fn->param_types()) {
13029       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13030           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13031       Params.push_back(Param);
13032     }
13033   }
13034 
13035   // Set the parameters on the block decl.
13036   if (!Params.empty()) {
13037     CurBlock->TheDecl->setParams(Params);
13038     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13039                              /*CheckParameterNames=*/false);
13040   }
13041 
13042   // Finally we can process decl attributes.
13043   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13044 
13045   // Put the parameter variables in scope.
13046   for (auto AI : CurBlock->TheDecl->parameters()) {
13047     AI->setOwningFunction(CurBlock->TheDecl);
13048 
13049     // If this has an identifier, add it to the scope stack.
13050     if (AI->getIdentifier()) {
13051       CheckShadow(CurBlock->TheScope, AI);
13052 
13053       PushOnScopeChains(AI, CurBlock->TheScope);
13054     }
13055   }
13056 }
13057 
13058 /// ActOnBlockError - If there is an error parsing a block, this callback
13059 /// is invoked to pop the information about the block from the action impl.
13060 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13061   // Leave the expression-evaluation context.
13062   DiscardCleanupsInEvaluationContext();
13063   PopExpressionEvaluationContext();
13064 
13065   // Pop off CurBlock, handle nested blocks.
13066   PopDeclContext();
13067   PopFunctionScopeInfo();
13068 }
13069 
13070 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13071 /// literal was successfully completed.  ^(int x){...}
13072 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13073                                     Stmt *Body, Scope *CurScope) {
13074   // If blocks are disabled, emit an error.
13075   if (!LangOpts.Blocks)
13076     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13077 
13078   // Leave the expression-evaluation context.
13079   if (hasAnyUnrecoverableErrorsInThisFunction())
13080     DiscardCleanupsInEvaluationContext();
13081   assert(!Cleanup.exprNeedsCleanups() &&
13082          "cleanups within block not correctly bound!");
13083   PopExpressionEvaluationContext();
13084 
13085   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13086 
13087   if (BSI->HasImplicitReturnType)
13088     deduceClosureReturnType(*BSI);
13089 
13090   PopDeclContext();
13091 
13092   QualType RetTy = Context.VoidTy;
13093   if (!BSI->ReturnType.isNull())
13094     RetTy = BSI->ReturnType;
13095 
13096   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13097   QualType BlockTy;
13098 
13099   // Set the captured variables on the block.
13100   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13101   SmallVector<BlockDecl::Capture, 4> Captures;
13102   for (Capture &Cap : BSI->Captures) {
13103     if (Cap.isThisCapture())
13104       continue;
13105     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13106                               Cap.isNested(), Cap.getInitExpr());
13107     Captures.push_back(NewCap);
13108   }
13109   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13110 
13111   // If the user wrote a function type in some form, try to use that.
13112   if (!BSI->FunctionType.isNull()) {
13113     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13114 
13115     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13116     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13117 
13118     // Turn protoless block types into nullary block types.
13119     if (isa<FunctionNoProtoType>(FTy)) {
13120       FunctionProtoType::ExtProtoInfo EPI;
13121       EPI.ExtInfo = Ext;
13122       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13123 
13124     // Otherwise, if we don't need to change anything about the function type,
13125     // preserve its sugar structure.
13126     } else if (FTy->getReturnType() == RetTy &&
13127                (!NoReturn || FTy->getNoReturnAttr())) {
13128       BlockTy = BSI->FunctionType;
13129 
13130     // Otherwise, make the minimal modifications to the function type.
13131     } else {
13132       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13133       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13134       EPI.TypeQuals = 0; // FIXME: silently?
13135       EPI.ExtInfo = Ext;
13136       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13137     }
13138 
13139   // If we don't have a function type, just build one from nothing.
13140   } else {
13141     FunctionProtoType::ExtProtoInfo EPI;
13142     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13143     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13144   }
13145 
13146   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13147   BlockTy = Context.getBlockPointerType(BlockTy);
13148 
13149   // If needed, diagnose invalid gotos and switches in the block.
13150   if (getCurFunction()->NeedsScopeChecking() &&
13151       !PP.isCodeCompletionEnabled())
13152     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13153 
13154   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13155 
13156   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13157     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13158 
13159   // Try to apply the named return value optimization. We have to check again
13160   // if we can do this, though, because blocks keep return statements around
13161   // to deduce an implicit return type.
13162   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13163       !BSI->TheDecl->isDependentContext())
13164     computeNRVO(Body, BSI);
13165 
13166   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13167   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13168   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13169 
13170   // If the block isn't obviously global, i.e. it captures anything at
13171   // all, then we need to do a few things in the surrounding context:
13172   if (Result->getBlockDecl()->hasCaptures()) {
13173     // First, this expression has a new cleanup object.
13174     ExprCleanupObjects.push_back(Result->getBlockDecl());
13175     Cleanup.setExprNeedsCleanups(true);
13176 
13177     // It also gets a branch-protected scope if any of the captured
13178     // variables needs destruction.
13179     for (const auto &CI : Result->getBlockDecl()->captures()) {
13180       const VarDecl *var = CI.getVariable();
13181       if (var->getType().isDestructedType() != QualType::DK_none) {
13182         setFunctionHasBranchProtectedScope();
13183         break;
13184       }
13185     }
13186   }
13187 
13188   return Result;
13189 }
13190 
13191 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13192                             SourceLocation RPLoc) {
13193   TypeSourceInfo *TInfo;
13194   GetTypeFromParser(Ty, &TInfo);
13195   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13196 }
13197 
13198 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13199                                 Expr *E, TypeSourceInfo *TInfo,
13200                                 SourceLocation RPLoc) {
13201   Expr *OrigExpr = E;
13202   bool IsMS = false;
13203 
13204   // CUDA device code does not support varargs.
13205   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13206     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13207       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13208       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13209         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13210     }
13211   }
13212 
13213   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13214   // as Microsoft ABI on an actual Microsoft platform, where
13215   // __builtin_ms_va_list and __builtin_va_list are the same.)
13216   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13217       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13218     QualType MSVaListType = Context.getBuiltinMSVaListType();
13219     if (Context.hasSameType(MSVaListType, E->getType())) {
13220       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13221         return ExprError();
13222       IsMS = true;
13223     }
13224   }
13225 
13226   // Get the va_list type
13227   QualType VaListType = Context.getBuiltinVaListType();
13228   if (!IsMS) {
13229     if (VaListType->isArrayType()) {
13230       // Deal with implicit array decay; for example, on x86-64,
13231       // va_list is an array, but it's supposed to decay to
13232       // a pointer for va_arg.
13233       VaListType = Context.getArrayDecayedType(VaListType);
13234       // Make sure the input expression also decays appropriately.
13235       ExprResult Result = UsualUnaryConversions(E);
13236       if (Result.isInvalid())
13237         return ExprError();
13238       E = Result.get();
13239     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13240       // If va_list is a record type and we are compiling in C++ mode,
13241       // check the argument using reference binding.
13242       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13243           Context, Context.getLValueReferenceType(VaListType), false);
13244       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13245       if (Init.isInvalid())
13246         return ExprError();
13247       E = Init.getAs<Expr>();
13248     } else {
13249       // Otherwise, the va_list argument must be an l-value because
13250       // it is modified by va_arg.
13251       if (!E->isTypeDependent() &&
13252           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13253         return ExprError();
13254     }
13255   }
13256 
13257   if (!IsMS && !E->isTypeDependent() &&
13258       !Context.hasSameType(VaListType, E->getType()))
13259     return ExprError(Diag(E->getLocStart(),
13260                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13261       << OrigExpr->getType() << E->getSourceRange());
13262 
13263   if (!TInfo->getType()->isDependentType()) {
13264     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13265                             diag::err_second_parameter_to_va_arg_incomplete,
13266                             TInfo->getTypeLoc()))
13267       return ExprError();
13268 
13269     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13270                                TInfo->getType(),
13271                                diag::err_second_parameter_to_va_arg_abstract,
13272                                TInfo->getTypeLoc()))
13273       return ExprError();
13274 
13275     if (!TInfo->getType().isPODType(Context)) {
13276       Diag(TInfo->getTypeLoc().getBeginLoc(),
13277            TInfo->getType()->isObjCLifetimeType()
13278              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13279              : diag::warn_second_parameter_to_va_arg_not_pod)
13280         << TInfo->getType()
13281         << TInfo->getTypeLoc().getSourceRange();
13282     }
13283 
13284     // Check for va_arg where arguments of the given type will be promoted
13285     // (i.e. this va_arg is guaranteed to have undefined behavior).
13286     QualType PromoteType;
13287     if (TInfo->getType()->isPromotableIntegerType()) {
13288       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13289       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13290         PromoteType = QualType();
13291     }
13292     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13293       PromoteType = Context.DoubleTy;
13294     if (!PromoteType.isNull())
13295       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13296                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13297                           << TInfo->getType()
13298                           << PromoteType
13299                           << TInfo->getTypeLoc().getSourceRange());
13300   }
13301 
13302   QualType T = TInfo->getType().getNonLValueExprType(Context);
13303   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13304 }
13305 
13306 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13307   // The type of __null will be int or long, depending on the size of
13308   // pointers on the target.
13309   QualType Ty;
13310   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13311   if (pw == Context.getTargetInfo().getIntWidth())
13312     Ty = Context.IntTy;
13313   else if (pw == Context.getTargetInfo().getLongWidth())
13314     Ty = Context.LongTy;
13315   else if (pw == Context.getTargetInfo().getLongLongWidth())
13316     Ty = Context.LongLongTy;
13317   else {
13318     llvm_unreachable("I don't know size of pointer!");
13319   }
13320 
13321   return new (Context) GNUNullExpr(Ty, TokenLoc);
13322 }
13323 
13324 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13325                                               bool Diagnose) {
13326   if (!getLangOpts().ObjC1)
13327     return false;
13328 
13329   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13330   if (!PT)
13331     return false;
13332 
13333   if (!PT->isObjCIdType()) {
13334     // Check if the destination is the 'NSString' interface.
13335     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13336     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13337       return false;
13338   }
13339 
13340   // Ignore any parens, implicit casts (should only be
13341   // array-to-pointer decays), and not-so-opaque values.  The last is
13342   // important for making this trigger for property assignments.
13343   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13344   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13345     if (OV->getSourceExpr())
13346       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13347 
13348   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13349   if (!SL || !SL->isAscii())
13350     return false;
13351   if (Diagnose) {
13352     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13353       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13354     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13355   }
13356   return true;
13357 }
13358 
13359 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13360                                               const Expr *SrcExpr) {
13361   if (!DstType->isFunctionPointerType() ||
13362       !SrcExpr->getType()->isFunctionType())
13363     return false;
13364 
13365   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13366   if (!DRE)
13367     return false;
13368 
13369   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13370   if (!FD)
13371     return false;
13372 
13373   return !S.checkAddressOfFunctionIsAvailable(FD,
13374                                               /*Complain=*/true,
13375                                               SrcExpr->getLocStart());
13376 }
13377 
13378 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13379                                     SourceLocation Loc,
13380                                     QualType DstType, QualType SrcType,
13381                                     Expr *SrcExpr, AssignmentAction Action,
13382                                     bool *Complained) {
13383   if (Complained)
13384     *Complained = false;
13385 
13386   // Decode the result (notice that AST's are still created for extensions).
13387   bool CheckInferredResultType = false;
13388   bool isInvalid = false;
13389   unsigned DiagKind = 0;
13390   FixItHint Hint;
13391   ConversionFixItGenerator ConvHints;
13392   bool MayHaveConvFixit = false;
13393   bool MayHaveFunctionDiff = false;
13394   const ObjCInterfaceDecl *IFace = nullptr;
13395   const ObjCProtocolDecl *PDecl = nullptr;
13396 
13397   switch (ConvTy) {
13398   case Compatible:
13399       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13400       return false;
13401 
13402   case PointerToInt:
13403     DiagKind = diag::ext_typecheck_convert_pointer_int;
13404     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13405     MayHaveConvFixit = true;
13406     break;
13407   case IntToPointer:
13408     DiagKind = diag::ext_typecheck_convert_int_pointer;
13409     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13410     MayHaveConvFixit = true;
13411     break;
13412   case IncompatiblePointer:
13413     if (Action == AA_Passing_CFAudited)
13414       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13415     else if (SrcType->isFunctionPointerType() &&
13416              DstType->isFunctionPointerType())
13417       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13418     else
13419       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13420 
13421     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13422       SrcType->isObjCObjectPointerType();
13423     if (Hint.isNull() && !CheckInferredResultType) {
13424       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13425     }
13426     else if (CheckInferredResultType) {
13427       SrcType = SrcType.getUnqualifiedType();
13428       DstType = DstType.getUnqualifiedType();
13429     }
13430     MayHaveConvFixit = true;
13431     break;
13432   case IncompatiblePointerSign:
13433     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13434     break;
13435   case FunctionVoidPointer:
13436     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13437     break;
13438   case IncompatiblePointerDiscardsQualifiers: {
13439     // Perform array-to-pointer decay if necessary.
13440     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13441 
13442     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13443     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13444     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13445       DiagKind = diag::err_typecheck_incompatible_address_space;
13446       break;
13447 
13448 
13449     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13450       DiagKind = diag::err_typecheck_incompatible_ownership;
13451       break;
13452     }
13453 
13454     llvm_unreachable("unknown error case for discarding qualifiers!");
13455     // fallthrough
13456   }
13457   case CompatiblePointerDiscardsQualifiers:
13458     // If the qualifiers lost were because we were applying the
13459     // (deprecated) C++ conversion from a string literal to a char*
13460     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13461     // Ideally, this check would be performed in
13462     // checkPointerTypesForAssignment. However, that would require a
13463     // bit of refactoring (so that the second argument is an
13464     // expression, rather than a type), which should be done as part
13465     // of a larger effort to fix checkPointerTypesForAssignment for
13466     // C++ semantics.
13467     if (getLangOpts().CPlusPlus &&
13468         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13469       return false;
13470     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13471     break;
13472   case IncompatibleNestedPointerQualifiers:
13473     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13474     break;
13475   case IntToBlockPointer:
13476     DiagKind = diag::err_int_to_block_pointer;
13477     break;
13478   case IncompatibleBlockPointer:
13479     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13480     break;
13481   case IncompatibleObjCQualifiedId: {
13482     if (SrcType->isObjCQualifiedIdType()) {
13483       const ObjCObjectPointerType *srcOPT =
13484                 SrcType->getAs<ObjCObjectPointerType>();
13485       for (auto *srcProto : srcOPT->quals()) {
13486         PDecl = srcProto;
13487         break;
13488       }
13489       if (const ObjCInterfaceType *IFaceT =
13490             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13491         IFace = IFaceT->getDecl();
13492     }
13493     else if (DstType->isObjCQualifiedIdType()) {
13494       const ObjCObjectPointerType *dstOPT =
13495         DstType->getAs<ObjCObjectPointerType>();
13496       for (auto *dstProto : dstOPT->quals()) {
13497         PDecl = dstProto;
13498         break;
13499       }
13500       if (const ObjCInterfaceType *IFaceT =
13501             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13502         IFace = IFaceT->getDecl();
13503     }
13504     DiagKind = diag::warn_incompatible_qualified_id;
13505     break;
13506   }
13507   case IncompatibleVectors:
13508     DiagKind = diag::warn_incompatible_vectors;
13509     break;
13510   case IncompatibleObjCWeakRef:
13511     DiagKind = diag::err_arc_weak_unavailable_assign;
13512     break;
13513   case Incompatible:
13514     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13515       if (Complained)
13516         *Complained = true;
13517       return true;
13518     }
13519 
13520     DiagKind = diag::err_typecheck_convert_incompatible;
13521     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13522     MayHaveConvFixit = true;
13523     isInvalid = true;
13524     MayHaveFunctionDiff = true;
13525     break;
13526   }
13527 
13528   QualType FirstType, SecondType;
13529   switch (Action) {
13530   case AA_Assigning:
13531   case AA_Initializing:
13532     // The destination type comes first.
13533     FirstType = DstType;
13534     SecondType = SrcType;
13535     break;
13536 
13537   case AA_Returning:
13538   case AA_Passing:
13539   case AA_Passing_CFAudited:
13540   case AA_Converting:
13541   case AA_Sending:
13542   case AA_Casting:
13543     // The source type comes first.
13544     FirstType = SrcType;
13545     SecondType = DstType;
13546     break;
13547   }
13548 
13549   PartialDiagnostic FDiag = PDiag(DiagKind);
13550   if (Action == AA_Passing_CFAudited)
13551     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13552   else
13553     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13554 
13555   // If we can fix the conversion, suggest the FixIts.
13556   assert(ConvHints.isNull() || Hint.isNull());
13557   if (!ConvHints.isNull()) {
13558     for (FixItHint &H : ConvHints.Hints)
13559       FDiag << H;
13560   } else {
13561     FDiag << Hint;
13562   }
13563   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13564 
13565   if (MayHaveFunctionDiff)
13566     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13567 
13568   Diag(Loc, FDiag);
13569   if (DiagKind == diag::warn_incompatible_qualified_id &&
13570       PDecl && IFace && !IFace->hasDefinition())
13571       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13572         << IFace << PDecl;
13573 
13574   if (SecondType == Context.OverloadTy)
13575     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13576                               FirstType, /*TakingAddress=*/true);
13577 
13578   if (CheckInferredResultType)
13579     EmitRelatedResultTypeNote(SrcExpr);
13580 
13581   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13582     EmitRelatedResultTypeNoteForReturn(DstType);
13583 
13584   if (Complained)
13585     *Complained = true;
13586   return isInvalid;
13587 }
13588 
13589 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13590                                                  llvm::APSInt *Result) {
13591   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13592   public:
13593     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13594       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13595     }
13596   } Diagnoser;
13597 
13598   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13599 }
13600 
13601 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13602                                                  llvm::APSInt *Result,
13603                                                  unsigned DiagID,
13604                                                  bool AllowFold) {
13605   class IDDiagnoser : public VerifyICEDiagnoser {
13606     unsigned DiagID;
13607 
13608   public:
13609     IDDiagnoser(unsigned DiagID)
13610       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13611 
13612     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13613       S.Diag(Loc, DiagID) << SR;
13614     }
13615   } Diagnoser(DiagID);
13616 
13617   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13618 }
13619 
13620 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13621                                             SourceRange SR) {
13622   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13623 }
13624 
13625 ExprResult
13626 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13627                                       VerifyICEDiagnoser &Diagnoser,
13628                                       bool AllowFold) {
13629   SourceLocation DiagLoc = E->getLocStart();
13630 
13631   if (getLangOpts().CPlusPlus11) {
13632     // C++11 [expr.const]p5:
13633     //   If an expression of literal class type is used in a context where an
13634     //   integral constant expression is required, then that class type shall
13635     //   have a single non-explicit conversion function to an integral or
13636     //   unscoped enumeration type
13637     ExprResult Converted;
13638     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13639     public:
13640       CXX11ConvertDiagnoser(bool Silent)
13641           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13642                                 Silent, true) {}
13643 
13644       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13645                                            QualType T) override {
13646         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13647       }
13648 
13649       SemaDiagnosticBuilder diagnoseIncomplete(
13650           Sema &S, SourceLocation Loc, QualType T) override {
13651         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13652       }
13653 
13654       SemaDiagnosticBuilder diagnoseExplicitConv(
13655           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13656         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13657       }
13658 
13659       SemaDiagnosticBuilder noteExplicitConv(
13660           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13661         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13662                  << ConvTy->isEnumeralType() << ConvTy;
13663       }
13664 
13665       SemaDiagnosticBuilder diagnoseAmbiguous(
13666           Sema &S, SourceLocation Loc, QualType T) override {
13667         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13668       }
13669 
13670       SemaDiagnosticBuilder noteAmbiguous(
13671           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13672         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13673                  << ConvTy->isEnumeralType() << ConvTy;
13674       }
13675 
13676       SemaDiagnosticBuilder diagnoseConversion(
13677           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13678         llvm_unreachable("conversion functions are permitted");
13679       }
13680     } ConvertDiagnoser(Diagnoser.Suppress);
13681 
13682     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13683                                                     ConvertDiagnoser);
13684     if (Converted.isInvalid())
13685       return Converted;
13686     E = Converted.get();
13687     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13688       return ExprError();
13689   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13690     // An ICE must be of integral or unscoped enumeration type.
13691     if (!Diagnoser.Suppress)
13692       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13693     return ExprError();
13694   }
13695 
13696   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13697   // in the non-ICE case.
13698   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13699     if (Result)
13700       *Result = E->EvaluateKnownConstInt(Context);
13701     return E;
13702   }
13703 
13704   Expr::EvalResult EvalResult;
13705   SmallVector<PartialDiagnosticAt, 8> Notes;
13706   EvalResult.Diag = &Notes;
13707 
13708   // Try to evaluate the expression, and produce diagnostics explaining why it's
13709   // not a constant expression as a side-effect.
13710   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13711                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13712 
13713   // In C++11, we can rely on diagnostics being produced for any expression
13714   // which is not a constant expression. If no diagnostics were produced, then
13715   // this is a constant expression.
13716   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13717     if (Result)
13718       *Result = EvalResult.Val.getInt();
13719     return E;
13720   }
13721 
13722   // If our only note is the usual "invalid subexpression" note, just point
13723   // the caret at its location rather than producing an essentially
13724   // redundant note.
13725   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13726         diag::note_invalid_subexpr_in_const_expr) {
13727     DiagLoc = Notes[0].first;
13728     Notes.clear();
13729   }
13730 
13731   if (!Folded || !AllowFold) {
13732     if (!Diagnoser.Suppress) {
13733       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13734       for (const PartialDiagnosticAt &Note : Notes)
13735         Diag(Note.first, Note.second);
13736     }
13737 
13738     return ExprError();
13739   }
13740 
13741   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13742   for (const PartialDiagnosticAt &Note : Notes)
13743     Diag(Note.first, Note.second);
13744 
13745   if (Result)
13746     *Result = EvalResult.Val.getInt();
13747   return E;
13748 }
13749 
13750 namespace {
13751   // Handle the case where we conclude a expression which we speculatively
13752   // considered to be unevaluated is actually evaluated.
13753   class TransformToPE : public TreeTransform<TransformToPE> {
13754     typedef TreeTransform<TransformToPE> BaseTransform;
13755 
13756   public:
13757     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13758 
13759     // Make sure we redo semantic analysis
13760     bool AlwaysRebuild() { return true; }
13761 
13762     // Make sure we handle LabelStmts correctly.
13763     // FIXME: This does the right thing, but maybe we need a more general
13764     // fix to TreeTransform?
13765     StmtResult TransformLabelStmt(LabelStmt *S) {
13766       S->getDecl()->setStmt(nullptr);
13767       return BaseTransform::TransformLabelStmt(S);
13768     }
13769 
13770     // We need to special-case DeclRefExprs referring to FieldDecls which
13771     // are not part of a member pointer formation; normal TreeTransforming
13772     // doesn't catch this case because of the way we represent them in the AST.
13773     // FIXME: This is a bit ugly; is it really the best way to handle this
13774     // case?
13775     //
13776     // Error on DeclRefExprs referring to FieldDecls.
13777     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13778       if (isa<FieldDecl>(E->getDecl()) &&
13779           !SemaRef.isUnevaluatedContext())
13780         return SemaRef.Diag(E->getLocation(),
13781                             diag::err_invalid_non_static_member_use)
13782             << E->getDecl() << E->getSourceRange();
13783 
13784       return BaseTransform::TransformDeclRefExpr(E);
13785     }
13786 
13787     // Exception: filter out member pointer formation
13788     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13789       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13790         return E;
13791 
13792       return BaseTransform::TransformUnaryOperator(E);
13793     }
13794 
13795     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13796       // Lambdas never need to be transformed.
13797       return E;
13798     }
13799   };
13800 }
13801 
13802 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13803   assert(isUnevaluatedContext() &&
13804          "Should only transform unevaluated expressions");
13805   ExprEvalContexts.back().Context =
13806       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13807   if (isUnevaluatedContext())
13808     return E;
13809   return TransformToPE(*this).TransformExpr(E);
13810 }
13811 
13812 void
13813 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13814                                       Decl *LambdaContextDecl,
13815                                       bool IsDecltype) {
13816   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13817                                 LambdaContextDecl, IsDecltype);
13818   Cleanup.reset();
13819   if (!MaybeODRUseExprs.empty())
13820     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13821 }
13822 
13823 void
13824 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13825                                       ReuseLambdaContextDecl_t,
13826                                       bool IsDecltype) {
13827   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13828   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13829 }
13830 
13831 void Sema::PopExpressionEvaluationContext() {
13832   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13833   unsigned NumTypos = Rec.NumTypos;
13834 
13835   if (!Rec.Lambdas.empty()) {
13836     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13837       unsigned D;
13838       if (Rec.isUnevaluated()) {
13839         // C++11 [expr.prim.lambda]p2:
13840         //   A lambda-expression shall not appear in an unevaluated operand
13841         //   (Clause 5).
13842         D = diag::err_lambda_unevaluated_operand;
13843       } else {
13844         // C++1y [expr.const]p2:
13845         //   A conditional-expression e is a core constant expression unless the
13846         //   evaluation of e, following the rules of the abstract machine, would
13847         //   evaluate [...] a lambda-expression.
13848         D = diag::err_lambda_in_constant_expression;
13849       }
13850 
13851       // C++1z allows lambda expressions as core constant expressions.
13852       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13853       // 1607) from appearing within template-arguments and array-bounds that
13854       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13855       // unevaluated contexts) might lift some of these restrictions in a
13856       // future version.
13857       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
13858         for (const auto *L : Rec.Lambdas)
13859           Diag(L->getLocStart(), D);
13860     } else {
13861       // Mark the capture expressions odr-used. This was deferred
13862       // during lambda expression creation.
13863       for (auto *Lambda : Rec.Lambdas) {
13864         for (auto *C : Lambda->capture_inits())
13865           MarkDeclarationsReferencedInExpr(C);
13866       }
13867     }
13868   }
13869 
13870   // When are coming out of an unevaluated context, clear out any
13871   // temporaries that we may have created as part of the evaluation of
13872   // the expression in that context: they aren't relevant because they
13873   // will never be constructed.
13874   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13875     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13876                              ExprCleanupObjects.end());
13877     Cleanup = Rec.ParentCleanup;
13878     CleanupVarDeclMarking();
13879     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13880   // Otherwise, merge the contexts together.
13881   } else {
13882     Cleanup.mergeFrom(Rec.ParentCleanup);
13883     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13884                             Rec.SavedMaybeODRUseExprs.end());
13885   }
13886 
13887   // Pop the current expression evaluation context off the stack.
13888   ExprEvalContexts.pop_back();
13889 
13890   if (!ExprEvalContexts.empty())
13891     ExprEvalContexts.back().NumTypos += NumTypos;
13892   else
13893     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13894                             "last ExpressionEvaluationContextRecord");
13895 }
13896 
13897 void Sema::DiscardCleanupsInEvaluationContext() {
13898   ExprCleanupObjects.erase(
13899          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13900          ExprCleanupObjects.end());
13901   Cleanup.reset();
13902   MaybeODRUseExprs.clear();
13903 }
13904 
13905 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13906   if (!E->getType()->isVariablyModifiedType())
13907     return E;
13908   return TransformToPotentiallyEvaluated(E);
13909 }
13910 
13911 /// Are we within a context in which some evaluation could be performed (be it
13912 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13913 /// captured by C++'s idea of an "unevaluated context".
13914 static bool isEvaluatableContext(Sema &SemaRef) {
13915   switch (SemaRef.ExprEvalContexts.back().Context) {
13916     case Sema::ExpressionEvaluationContext::Unevaluated:
13917     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13918     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13919       // Expressions in this context are never evaluated.
13920       return false;
13921 
13922     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13923     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13924     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13925       // Expressions in this context could be evaluated.
13926       return true;
13927 
13928     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13929       // Referenced declarations will only be used if the construct in the
13930       // containing expression is used, at which point we'll be given another
13931       // turn to mark them.
13932       return false;
13933   }
13934   llvm_unreachable("Invalid context");
13935 }
13936 
13937 /// Are we within a context in which references to resolved functions or to
13938 /// variables result in odr-use?
13939 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13940   // An expression in a template is not really an expression until it's been
13941   // instantiated, so it doesn't trigger odr-use.
13942   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13943     return false;
13944 
13945   switch (SemaRef.ExprEvalContexts.back().Context) {
13946     case Sema::ExpressionEvaluationContext::Unevaluated:
13947     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13948     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13949     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13950       return false;
13951 
13952     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13953     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13954       return true;
13955 
13956     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13957       return false;
13958   }
13959   llvm_unreachable("Invalid context");
13960 }
13961 
13962 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13963   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13964   return Func->isConstexpr() &&
13965          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13966 }
13967 
13968 /// \brief Mark a function referenced, and check whether it is odr-used
13969 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13970 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13971                                   bool MightBeOdrUse) {
13972   assert(Func && "No function?");
13973 
13974   Func->setReferenced();
13975 
13976   // C++11 [basic.def.odr]p3:
13977   //   A function whose name appears as a potentially-evaluated expression is
13978   //   odr-used if it is the unique lookup result or the selected member of a
13979   //   set of overloaded functions [...].
13980   //
13981   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13982   // can just check that here.
13983   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13984 
13985   // Determine whether we require a function definition to exist, per
13986   // C++11 [temp.inst]p3:
13987   //   Unless a function template specialization has been explicitly
13988   //   instantiated or explicitly specialized, the function template
13989   //   specialization is implicitly instantiated when the specialization is
13990   //   referenced in a context that requires a function definition to exist.
13991   //
13992   // That is either when this is an odr-use, or when a usage of a constexpr
13993   // function occurs within an evaluatable context.
13994   bool NeedDefinition =
13995       OdrUse || (isEvaluatableContext(*this) &&
13996                  isImplicitlyDefinableConstexprFunction(Func));
13997 
13998   // C++14 [temp.expl.spec]p6:
13999   //   If a template [...] is explicitly specialized then that specialization
14000   //   shall be declared before the first use of that specialization that would
14001   //   cause an implicit instantiation to take place, in every translation unit
14002   //   in which such a use occurs
14003   if (NeedDefinition &&
14004       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14005        Func->getMemberSpecializationInfo()))
14006     checkSpecializationVisibility(Loc, Func);
14007 
14008   // C++14 [except.spec]p17:
14009   //   An exception-specification is considered to be needed when:
14010   //   - the function is odr-used or, if it appears in an unevaluated operand,
14011   //     would be odr-used if the expression were potentially-evaluated;
14012   //
14013   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14014   // function is a pure virtual function we're calling, and in that case the
14015   // function was selected by overload resolution and we need to resolve its
14016   // exception specification for a different reason.
14017   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14018   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14019     ResolveExceptionSpec(Loc, FPT);
14020 
14021   // If we don't need to mark the function as used, and we don't need to
14022   // try to provide a definition, there's nothing more to do.
14023   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14024       (!NeedDefinition || Func->getBody()))
14025     return;
14026 
14027   // Note that this declaration has been used.
14028   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14029     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14030     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14031       if (Constructor->isDefaultConstructor()) {
14032         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14033           return;
14034         DefineImplicitDefaultConstructor(Loc, Constructor);
14035       } else if (Constructor->isCopyConstructor()) {
14036         DefineImplicitCopyConstructor(Loc, Constructor);
14037       } else if (Constructor->isMoveConstructor()) {
14038         DefineImplicitMoveConstructor(Loc, Constructor);
14039       }
14040     } else if (Constructor->getInheritedConstructor()) {
14041       DefineInheritingConstructor(Loc, Constructor);
14042     }
14043   } else if (CXXDestructorDecl *Destructor =
14044                  dyn_cast<CXXDestructorDecl>(Func)) {
14045     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14046     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14047       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14048         return;
14049       DefineImplicitDestructor(Loc, Destructor);
14050     }
14051     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14052       MarkVTableUsed(Loc, Destructor->getParent());
14053   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14054     if (MethodDecl->isOverloadedOperator() &&
14055         MethodDecl->getOverloadedOperator() == OO_Equal) {
14056       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14057       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14058         if (MethodDecl->isCopyAssignmentOperator())
14059           DefineImplicitCopyAssignment(Loc, MethodDecl);
14060         else if (MethodDecl->isMoveAssignmentOperator())
14061           DefineImplicitMoveAssignment(Loc, MethodDecl);
14062       }
14063     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14064                MethodDecl->getParent()->isLambda()) {
14065       CXXConversionDecl *Conversion =
14066           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14067       if (Conversion->isLambdaToBlockPointerConversion())
14068         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14069       else
14070         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14071     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14072       MarkVTableUsed(Loc, MethodDecl->getParent());
14073   }
14074 
14075   // Recursive functions should be marked when used from another function.
14076   // FIXME: Is this really right?
14077   if (CurContext == Func) return;
14078 
14079   // Implicit instantiation of function templates and member functions of
14080   // class templates.
14081   if (Func->isImplicitlyInstantiable()) {
14082     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14083     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14084     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14085     if (FirstInstantiation) {
14086       PointOfInstantiation = Loc;
14087       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14088     } else if (TSK != TSK_ImplicitInstantiation) {
14089       // Use the point of use as the point of instantiation, instead of the
14090       // point of explicit instantiation (which we track as the actual point of
14091       // instantiation). This gives better backtraces in diagnostics.
14092       PointOfInstantiation = Loc;
14093     }
14094 
14095     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14096         Func->isConstexpr()) {
14097       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14098           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14099           CodeSynthesisContexts.size())
14100         PendingLocalImplicitInstantiations.push_back(
14101             std::make_pair(Func, PointOfInstantiation));
14102       else if (Func->isConstexpr())
14103         // Do not defer instantiations of constexpr functions, to avoid the
14104         // expression evaluator needing to call back into Sema if it sees a
14105         // call to such a function.
14106         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14107       else {
14108         Func->setInstantiationIsPending(true);
14109         PendingInstantiations.push_back(std::make_pair(Func,
14110                                                        PointOfInstantiation));
14111         // Notify the consumer that a function was implicitly instantiated.
14112         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14113       }
14114     }
14115   } else {
14116     // Walk redefinitions, as some of them may be instantiable.
14117     for (auto i : Func->redecls()) {
14118       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14119         MarkFunctionReferenced(Loc, i, OdrUse);
14120     }
14121   }
14122 
14123   if (!OdrUse) return;
14124 
14125   // Keep track of used but undefined functions.
14126   if (!Func->isDefined()) {
14127     if (mightHaveNonExternalLinkage(Func))
14128       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14129     else if (Func->getMostRecentDecl()->isInlined() &&
14130              !LangOpts.GNUInline &&
14131              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14132       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14133     else if (isExternalWithNoLinkageType(Func))
14134       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14135   }
14136 
14137   Func->markUsed(Context);
14138 }
14139 
14140 static void
14141 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14142                                    ValueDecl *var, DeclContext *DC) {
14143   DeclContext *VarDC = var->getDeclContext();
14144 
14145   //  If the parameter still belongs to the translation unit, then
14146   //  we're actually just using one parameter in the declaration of
14147   //  the next.
14148   if (isa<ParmVarDecl>(var) &&
14149       isa<TranslationUnitDecl>(VarDC))
14150     return;
14151 
14152   // For C code, don't diagnose about capture if we're not actually in code
14153   // right now; it's impossible to write a non-constant expression outside of
14154   // function context, so we'll get other (more useful) diagnostics later.
14155   //
14156   // For C++, things get a bit more nasty... it would be nice to suppress this
14157   // diagnostic for certain cases like using a local variable in an array bound
14158   // for a member of a local class, but the correct predicate is not obvious.
14159   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14160     return;
14161 
14162   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14163   unsigned ContextKind = 3; // unknown
14164   if (isa<CXXMethodDecl>(VarDC) &&
14165       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14166     ContextKind = 2;
14167   } else if (isa<FunctionDecl>(VarDC)) {
14168     ContextKind = 0;
14169   } else if (isa<BlockDecl>(VarDC)) {
14170     ContextKind = 1;
14171   }
14172 
14173   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14174     << var << ValueKind << ContextKind << VarDC;
14175   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14176       << var;
14177 
14178   // FIXME: Add additional diagnostic info about class etc. which prevents
14179   // capture.
14180 }
14181 
14182 
14183 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14184                                       bool &SubCapturesAreNested,
14185                                       QualType &CaptureType,
14186                                       QualType &DeclRefType) {
14187    // Check whether we've already captured it.
14188   if (CSI->CaptureMap.count(Var)) {
14189     // If we found a capture, any subcaptures are nested.
14190     SubCapturesAreNested = true;
14191 
14192     // Retrieve the capture type for this variable.
14193     CaptureType = CSI->getCapture(Var).getCaptureType();
14194 
14195     // Compute the type of an expression that refers to this variable.
14196     DeclRefType = CaptureType.getNonReferenceType();
14197 
14198     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14199     // are mutable in the sense that user can change their value - they are
14200     // private instances of the captured declarations.
14201     const Capture &Cap = CSI->getCapture(Var);
14202     if (Cap.isCopyCapture() &&
14203         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14204         !(isa<CapturedRegionScopeInfo>(CSI) &&
14205           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14206       DeclRefType.addConst();
14207     return true;
14208   }
14209   return false;
14210 }
14211 
14212 // Only block literals, captured statements, and lambda expressions can
14213 // capture; other scopes don't work.
14214 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14215                                  SourceLocation Loc,
14216                                  const bool Diagnose, Sema &S) {
14217   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14218     return getLambdaAwareParentOfDeclContext(DC);
14219   else if (Var->hasLocalStorage()) {
14220     if (Diagnose)
14221        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14222   }
14223   return nullptr;
14224 }
14225 
14226 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14227 // certain types of variables (unnamed, variably modified types etc.)
14228 // so check for eligibility.
14229 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14230                                  SourceLocation Loc,
14231                                  const bool Diagnose, Sema &S) {
14232 
14233   bool IsBlock = isa<BlockScopeInfo>(CSI);
14234   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14235 
14236   // Lambdas are not allowed to capture unnamed variables
14237   // (e.g. anonymous unions).
14238   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14239   // assuming that's the intent.
14240   if (IsLambda && !Var->getDeclName()) {
14241     if (Diagnose) {
14242       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14243       S.Diag(Var->getLocation(), diag::note_declared_at);
14244     }
14245     return false;
14246   }
14247 
14248   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14249   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14250     if (Diagnose) {
14251       S.Diag(Loc, diag::err_ref_vm_type);
14252       S.Diag(Var->getLocation(), diag::note_previous_decl)
14253         << Var->getDeclName();
14254     }
14255     return false;
14256   }
14257   // Prohibit structs with flexible array members too.
14258   // We cannot capture what is in the tail end of the struct.
14259   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14260     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14261       if (Diagnose) {
14262         if (IsBlock)
14263           S.Diag(Loc, diag::err_ref_flexarray_type);
14264         else
14265           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14266             << Var->getDeclName();
14267         S.Diag(Var->getLocation(), diag::note_previous_decl)
14268           << Var->getDeclName();
14269       }
14270       return false;
14271     }
14272   }
14273   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14274   // Lambdas and captured statements are not allowed to capture __block
14275   // variables; they don't support the expected semantics.
14276   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14277     if (Diagnose) {
14278       S.Diag(Loc, diag::err_capture_block_variable)
14279         << Var->getDeclName() << !IsLambda;
14280       S.Diag(Var->getLocation(), diag::note_previous_decl)
14281         << Var->getDeclName();
14282     }
14283     return false;
14284   }
14285   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14286   if (S.getLangOpts().OpenCL && IsBlock &&
14287       Var->getType()->isBlockPointerType()) {
14288     if (Diagnose)
14289       S.Diag(Loc, diag::err_opencl_block_ref_block);
14290     return false;
14291   }
14292 
14293   return true;
14294 }
14295 
14296 // Returns true if the capture by block was successful.
14297 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14298                                  SourceLocation Loc,
14299                                  const bool BuildAndDiagnose,
14300                                  QualType &CaptureType,
14301                                  QualType &DeclRefType,
14302                                  const bool Nested,
14303                                  Sema &S) {
14304   Expr *CopyExpr = nullptr;
14305   bool ByRef = false;
14306 
14307   // Blocks are not allowed to capture arrays.
14308   if (CaptureType->isArrayType()) {
14309     if (BuildAndDiagnose) {
14310       S.Diag(Loc, diag::err_ref_array_type);
14311       S.Diag(Var->getLocation(), diag::note_previous_decl)
14312       << Var->getDeclName();
14313     }
14314     return false;
14315   }
14316 
14317   // Forbid the block-capture of autoreleasing variables.
14318   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14319     if (BuildAndDiagnose) {
14320       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14321         << /*block*/ 0;
14322       S.Diag(Var->getLocation(), diag::note_previous_decl)
14323         << Var->getDeclName();
14324     }
14325     return false;
14326   }
14327 
14328   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14329   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14330     // This function finds out whether there is an AttributedType of kind
14331     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14332     // attr_objc_ownership implies __autoreleasing was explicitly specified
14333     // rather than being added implicitly by the compiler.
14334     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14335       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14336         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14337           return true;
14338 
14339         // Peel off AttributedTypes that are not of kind objc_ownership.
14340         Ty = AttrTy->getModifiedType();
14341       }
14342 
14343       return false;
14344     };
14345 
14346     QualType PointeeTy = PT->getPointeeType();
14347 
14348     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14349         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14350         !IsObjCOwnershipAttributedType(PointeeTy)) {
14351       if (BuildAndDiagnose) {
14352         SourceLocation VarLoc = Var->getLocation();
14353         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14354         {
14355           auto AddAutoreleaseNote =
14356               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
14357           // Provide a fix-it for the '__autoreleasing' keyword at the
14358           // appropriate location in the variable's type.
14359           if (const auto *TSI = Var->getTypeSourceInfo()) {
14360             PointerTypeLoc PTL =
14361                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
14362             if (PTL) {
14363               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
14364               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
14365                                                S.getLangOpts());
14366               if (Loc.isValid()) {
14367                 StringRef CharAtLoc = Lexer::getSourceText(
14368                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
14369                     S.getSourceManager(), S.getLangOpts());
14370                 AddAutoreleaseNote << FixItHint::CreateInsertion(
14371                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
14372                              ? " __autoreleasing "
14373                              : " __autoreleasing");
14374               }
14375             }
14376           }
14377         }
14378         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14379       }
14380     }
14381   }
14382 
14383   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14384   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14385       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14386     // Block capture by reference does not change the capture or
14387     // declaration reference types.
14388     ByRef = true;
14389   } else {
14390     // Block capture by copy introduces 'const'.
14391     CaptureType = CaptureType.getNonReferenceType().withConst();
14392     DeclRefType = CaptureType;
14393 
14394     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14395       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14396         // The capture logic needs the destructor, so make sure we mark it.
14397         // Usually this is unnecessary because most local variables have
14398         // their destructors marked at declaration time, but parameters are
14399         // an exception because it's technically only the call site that
14400         // actually requires the destructor.
14401         if (isa<ParmVarDecl>(Var))
14402           S.FinalizeVarWithDestructor(Var, Record);
14403 
14404         // Enter a new evaluation context to insulate the copy
14405         // full-expression.
14406         EnterExpressionEvaluationContext scope(
14407             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14408 
14409         // According to the blocks spec, the capture of a variable from
14410         // the stack requires a const copy constructor.  This is not true
14411         // of the copy/move done to move a __block variable to the heap.
14412         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14413                                                   DeclRefType.withConst(),
14414                                                   VK_LValue, Loc);
14415 
14416         ExprResult Result
14417           = S.PerformCopyInitialization(
14418               InitializedEntity::InitializeBlock(Var->getLocation(),
14419                                                   CaptureType, false),
14420               Loc, DeclRef);
14421 
14422         // Build a full-expression copy expression if initialization
14423         // succeeded and used a non-trivial constructor.  Recover from
14424         // errors by pretending that the copy isn't necessary.
14425         if (!Result.isInvalid() &&
14426             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14427                 ->isTrivial()) {
14428           Result = S.MaybeCreateExprWithCleanups(Result);
14429           CopyExpr = Result.get();
14430         }
14431       }
14432     }
14433   }
14434 
14435   // Actually capture the variable.
14436   if (BuildAndDiagnose)
14437     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14438                     SourceLocation(), CaptureType, CopyExpr);
14439 
14440   return true;
14441 
14442 }
14443 
14444 
14445 /// \brief Capture the given variable in the captured region.
14446 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14447                                     VarDecl *Var,
14448                                     SourceLocation Loc,
14449                                     const bool BuildAndDiagnose,
14450                                     QualType &CaptureType,
14451                                     QualType &DeclRefType,
14452                                     const bool RefersToCapturedVariable,
14453                                     Sema &S) {
14454   // By default, capture variables by reference.
14455   bool ByRef = true;
14456   // Using an LValue reference type is consistent with Lambdas (see below).
14457   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14458     if (S.isOpenMPCapturedDecl(Var)) {
14459       bool HasConst = DeclRefType.isConstQualified();
14460       DeclRefType = DeclRefType.getUnqualifiedType();
14461       // Don't lose diagnostics about assignments to const.
14462       if (HasConst)
14463         DeclRefType.addConst();
14464     }
14465     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14466   }
14467 
14468   if (ByRef)
14469     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14470   else
14471     CaptureType = DeclRefType;
14472 
14473   Expr *CopyExpr = nullptr;
14474   if (BuildAndDiagnose) {
14475     // The current implementation assumes that all variables are captured
14476     // by references. Since there is no capture by copy, no expression
14477     // evaluation will be needed.
14478     RecordDecl *RD = RSI->TheRecordDecl;
14479 
14480     FieldDecl *Field
14481       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14482                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14483                           nullptr, false, ICIS_NoInit);
14484     Field->setImplicit(true);
14485     Field->setAccess(AS_private);
14486     RD->addDecl(Field);
14487     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14488       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14489 
14490     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14491                                             DeclRefType, VK_LValue, Loc);
14492     Var->setReferenced(true);
14493     Var->markUsed(S.Context);
14494   }
14495 
14496   // Actually capture the variable.
14497   if (BuildAndDiagnose)
14498     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14499                     SourceLocation(), CaptureType, CopyExpr);
14500 
14501 
14502   return true;
14503 }
14504 
14505 /// \brief Create a field within the lambda class for the variable
14506 /// being captured.
14507 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14508                                     QualType FieldType, QualType DeclRefType,
14509                                     SourceLocation Loc,
14510                                     bool RefersToCapturedVariable) {
14511   CXXRecordDecl *Lambda = LSI->Lambda;
14512 
14513   // Build the non-static data member.
14514   FieldDecl *Field
14515     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14516                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14517                         nullptr, false, ICIS_NoInit);
14518   Field->setImplicit(true);
14519   Field->setAccess(AS_private);
14520   Lambda->addDecl(Field);
14521 }
14522 
14523 /// \brief Capture the given variable in the lambda.
14524 static bool captureInLambda(LambdaScopeInfo *LSI,
14525                             VarDecl *Var,
14526                             SourceLocation Loc,
14527                             const bool BuildAndDiagnose,
14528                             QualType &CaptureType,
14529                             QualType &DeclRefType,
14530                             const bool RefersToCapturedVariable,
14531                             const Sema::TryCaptureKind Kind,
14532                             SourceLocation EllipsisLoc,
14533                             const bool IsTopScope,
14534                             Sema &S) {
14535 
14536   // Determine whether we are capturing by reference or by value.
14537   bool ByRef = false;
14538   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14539     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14540   } else {
14541     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14542   }
14543 
14544   // Compute the type of the field that will capture this variable.
14545   if (ByRef) {
14546     // C++11 [expr.prim.lambda]p15:
14547     //   An entity is captured by reference if it is implicitly or
14548     //   explicitly captured but not captured by copy. It is
14549     //   unspecified whether additional unnamed non-static data
14550     //   members are declared in the closure type for entities
14551     //   captured by reference.
14552     //
14553     // FIXME: It is not clear whether we want to build an lvalue reference
14554     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14555     // to do the former, while EDG does the latter. Core issue 1249 will
14556     // clarify, but for now we follow GCC because it's a more permissive and
14557     // easily defensible position.
14558     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14559   } else {
14560     // C++11 [expr.prim.lambda]p14:
14561     //   For each entity captured by copy, an unnamed non-static
14562     //   data member is declared in the closure type. The
14563     //   declaration order of these members is unspecified. The type
14564     //   of such a data member is the type of the corresponding
14565     //   captured entity if the entity is not a reference to an
14566     //   object, or the referenced type otherwise. [Note: If the
14567     //   captured entity is a reference to a function, the
14568     //   corresponding data member is also a reference to a
14569     //   function. - end note ]
14570     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14571       if (!RefType->getPointeeType()->isFunctionType())
14572         CaptureType = RefType->getPointeeType();
14573     }
14574 
14575     // Forbid the lambda copy-capture of autoreleasing variables.
14576     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14577       if (BuildAndDiagnose) {
14578         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14579         S.Diag(Var->getLocation(), diag::note_previous_decl)
14580           << Var->getDeclName();
14581       }
14582       return false;
14583     }
14584 
14585     // Make sure that by-copy captures are of a complete and non-abstract type.
14586     if (BuildAndDiagnose) {
14587       if (!CaptureType->isDependentType() &&
14588           S.RequireCompleteType(Loc, CaptureType,
14589                                 diag::err_capture_of_incomplete_type,
14590                                 Var->getDeclName()))
14591         return false;
14592 
14593       if (S.RequireNonAbstractType(Loc, CaptureType,
14594                                    diag::err_capture_of_abstract_type))
14595         return false;
14596     }
14597   }
14598 
14599   // Capture this variable in the lambda.
14600   if (BuildAndDiagnose)
14601     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14602                             RefersToCapturedVariable);
14603 
14604   // Compute the type of a reference to this captured variable.
14605   if (ByRef)
14606     DeclRefType = CaptureType.getNonReferenceType();
14607   else {
14608     // C++ [expr.prim.lambda]p5:
14609     //   The closure type for a lambda-expression has a public inline
14610     //   function call operator [...]. This function call operator is
14611     //   declared const (9.3.1) if and only if the lambda-expression's
14612     //   parameter-declaration-clause is not followed by mutable.
14613     DeclRefType = CaptureType.getNonReferenceType();
14614     if (!LSI->Mutable && !CaptureType->isReferenceType())
14615       DeclRefType.addConst();
14616   }
14617 
14618   // Add the capture.
14619   if (BuildAndDiagnose)
14620     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14621                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14622 
14623   return true;
14624 }
14625 
14626 bool Sema::tryCaptureVariable(
14627     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14628     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14629     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14630   // An init-capture is notionally from the context surrounding its
14631   // declaration, but its parent DC is the lambda class.
14632   DeclContext *VarDC = Var->getDeclContext();
14633   if (Var->isInitCapture())
14634     VarDC = VarDC->getParent();
14635 
14636   DeclContext *DC = CurContext;
14637   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14638       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14639   // We need to sync up the Declaration Context with the
14640   // FunctionScopeIndexToStopAt
14641   if (FunctionScopeIndexToStopAt) {
14642     unsigned FSIndex = FunctionScopes.size() - 1;
14643     while (FSIndex != MaxFunctionScopesIndex) {
14644       DC = getLambdaAwareParentOfDeclContext(DC);
14645       --FSIndex;
14646     }
14647   }
14648 
14649 
14650   // If the variable is declared in the current context, there is no need to
14651   // capture it.
14652   if (VarDC == DC) return true;
14653 
14654   // Capture global variables if it is required to use private copy of this
14655   // variable.
14656   bool IsGlobal = !Var->hasLocalStorage();
14657   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14658     return true;
14659   Var = Var->getCanonicalDecl();
14660 
14661   // Walk up the stack to determine whether we can capture the variable,
14662   // performing the "simple" checks that don't depend on type. We stop when
14663   // we've either hit the declared scope of the variable or find an existing
14664   // capture of that variable.  We start from the innermost capturing-entity
14665   // (the DC) and ensure that all intervening capturing-entities
14666   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14667   // declcontext can either capture the variable or have already captured
14668   // the variable.
14669   CaptureType = Var->getType();
14670   DeclRefType = CaptureType.getNonReferenceType();
14671   bool Nested = false;
14672   bool Explicit = (Kind != TryCapture_Implicit);
14673   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14674   do {
14675     // Only block literals, captured statements, and lambda expressions can
14676     // capture; other scopes don't work.
14677     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14678                                                               ExprLoc,
14679                                                               BuildAndDiagnose,
14680                                                               *this);
14681     // We need to check for the parent *first* because, if we *have*
14682     // private-captured a global variable, we need to recursively capture it in
14683     // intermediate blocks, lambdas, etc.
14684     if (!ParentDC) {
14685       if (IsGlobal) {
14686         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14687         break;
14688       }
14689       return true;
14690     }
14691 
14692     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14693     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14694 
14695 
14696     // Check whether we've already captured it.
14697     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14698                                              DeclRefType)) {
14699       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14700       break;
14701     }
14702     // If we are instantiating a generic lambda call operator body,
14703     // we do not want to capture new variables.  What was captured
14704     // during either a lambdas transformation or initial parsing
14705     // should be used.
14706     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14707       if (BuildAndDiagnose) {
14708         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14709         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14710           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14711           Diag(Var->getLocation(), diag::note_previous_decl)
14712              << Var->getDeclName();
14713           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14714         } else
14715           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14716       }
14717       return true;
14718     }
14719     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14720     // certain types of variables (unnamed, variably modified types etc.)
14721     // so check for eligibility.
14722     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14723        return true;
14724 
14725     // Try to capture variable-length arrays types.
14726     if (Var->getType()->isVariablyModifiedType()) {
14727       // We're going to walk down into the type and look for VLA
14728       // expressions.
14729       QualType QTy = Var->getType();
14730       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14731         QTy = PVD->getOriginalType();
14732       captureVariablyModifiedType(Context, QTy, CSI);
14733     }
14734 
14735     if (getLangOpts().OpenMP) {
14736       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14737         // OpenMP private variables should not be captured in outer scope, so
14738         // just break here. Similarly, global variables that are captured in a
14739         // target region should not be captured outside the scope of the region.
14740         if (RSI->CapRegionKind == CR_OpenMP) {
14741           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
14742           auto IsTargetCap = !IsOpenMPPrivateDecl &&
14743                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14744           // When we detect target captures we are looking from inside the
14745           // target region, therefore we need to propagate the capture from the
14746           // enclosing region. Therefore, the capture is not initially nested.
14747           if (IsTargetCap)
14748             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
14749 
14750           if (IsTargetCap || IsOpenMPPrivateDecl) {
14751             Nested = !IsTargetCap;
14752             DeclRefType = DeclRefType.getUnqualifiedType();
14753             CaptureType = Context.getLValueReferenceType(DeclRefType);
14754             break;
14755           }
14756         }
14757       }
14758     }
14759     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14760       // No capture-default, and this is not an explicit capture
14761       // so cannot capture this variable.
14762       if (BuildAndDiagnose) {
14763         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14764         Diag(Var->getLocation(), diag::note_previous_decl)
14765           << Var->getDeclName();
14766         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14767           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14768                diag::note_lambda_decl);
14769         // FIXME: If we error out because an outer lambda can not implicitly
14770         // capture a variable that an inner lambda explicitly captures, we
14771         // should have the inner lambda do the explicit capture - because
14772         // it makes for cleaner diagnostics later.  This would purely be done
14773         // so that the diagnostic does not misleadingly claim that a variable
14774         // can not be captured by a lambda implicitly even though it is captured
14775         // explicitly.  Suggestion:
14776         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14777         //    at the function head
14778         //  - cache the StartingDeclContext - this must be a lambda
14779         //  - captureInLambda in the innermost lambda the variable.
14780       }
14781       return true;
14782     }
14783 
14784     FunctionScopesIndex--;
14785     DC = ParentDC;
14786     Explicit = false;
14787   } while (!VarDC->Equals(DC));
14788 
14789   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14790   // computing the type of the capture at each step, checking type-specific
14791   // requirements, and adding captures if requested.
14792   // If the variable had already been captured previously, we start capturing
14793   // at the lambda nested within that one.
14794   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14795        ++I) {
14796     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14797 
14798     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14799       if (!captureInBlock(BSI, Var, ExprLoc,
14800                           BuildAndDiagnose, CaptureType,
14801                           DeclRefType, Nested, *this))
14802         return true;
14803       Nested = true;
14804     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14805       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14806                                    BuildAndDiagnose, CaptureType,
14807                                    DeclRefType, Nested, *this))
14808         return true;
14809       Nested = true;
14810     } else {
14811       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14812       if (!captureInLambda(LSI, Var, ExprLoc,
14813                            BuildAndDiagnose, CaptureType,
14814                            DeclRefType, Nested, Kind, EllipsisLoc,
14815                             /*IsTopScope*/I == N - 1, *this))
14816         return true;
14817       Nested = true;
14818     }
14819   }
14820   return false;
14821 }
14822 
14823 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14824                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14825   QualType CaptureType;
14826   QualType DeclRefType;
14827   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14828                             /*BuildAndDiagnose=*/true, CaptureType,
14829                             DeclRefType, nullptr);
14830 }
14831 
14832 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14833   QualType CaptureType;
14834   QualType DeclRefType;
14835   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14836                              /*BuildAndDiagnose=*/false, CaptureType,
14837                              DeclRefType, nullptr);
14838 }
14839 
14840 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14841   QualType CaptureType;
14842   QualType DeclRefType;
14843 
14844   // Determine whether we can capture this variable.
14845   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14846                          /*BuildAndDiagnose=*/false, CaptureType,
14847                          DeclRefType, nullptr))
14848     return QualType();
14849 
14850   return DeclRefType;
14851 }
14852 
14853 
14854 
14855 // If either the type of the variable or the initializer is dependent,
14856 // return false. Otherwise, determine whether the variable is a constant
14857 // expression. Use this if you need to know if a variable that might or
14858 // might not be dependent is truly a constant expression.
14859 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14860     ASTContext &Context) {
14861 
14862   if (Var->getType()->isDependentType())
14863     return false;
14864   const VarDecl *DefVD = nullptr;
14865   Var->getAnyInitializer(DefVD);
14866   if (!DefVD)
14867     return false;
14868   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14869   Expr *Init = cast<Expr>(Eval->Value);
14870   if (Init->isValueDependent())
14871     return false;
14872   return IsVariableAConstantExpression(Var, Context);
14873 }
14874 
14875 
14876 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14877   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14878   // an object that satisfies the requirements for appearing in a
14879   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14880   // is immediately applied."  This function handles the lvalue-to-rvalue
14881   // conversion part.
14882   MaybeODRUseExprs.erase(E->IgnoreParens());
14883 
14884   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14885   // to a variable that is a constant expression, and if so, identify it as
14886   // a reference to a variable that does not involve an odr-use of that
14887   // variable.
14888   if (LambdaScopeInfo *LSI = getCurLambda()) {
14889     Expr *SansParensExpr = E->IgnoreParens();
14890     VarDecl *Var = nullptr;
14891     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14892       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14893     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14894       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14895 
14896     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14897       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14898   }
14899 }
14900 
14901 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14902   Res = CorrectDelayedTyposInExpr(Res);
14903 
14904   if (!Res.isUsable())
14905     return Res;
14906 
14907   // If a constant-expression is a reference to a variable where we delay
14908   // deciding whether it is an odr-use, just assume we will apply the
14909   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14910   // (a non-type template argument), we have special handling anyway.
14911   UpdateMarkingForLValueToRValue(Res.get());
14912   return Res;
14913 }
14914 
14915 void Sema::CleanupVarDeclMarking() {
14916   for (Expr *E : MaybeODRUseExprs) {
14917     VarDecl *Var;
14918     SourceLocation Loc;
14919     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14920       Var = cast<VarDecl>(DRE->getDecl());
14921       Loc = DRE->getLocation();
14922     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14923       Var = cast<VarDecl>(ME->getMemberDecl());
14924       Loc = ME->getMemberLoc();
14925     } else {
14926       llvm_unreachable("Unexpected expression");
14927     }
14928 
14929     MarkVarDeclODRUsed(Var, Loc, *this,
14930                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14931   }
14932 
14933   MaybeODRUseExprs.clear();
14934 }
14935 
14936 
14937 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14938                                     VarDecl *Var, Expr *E) {
14939   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14940          "Invalid Expr argument to DoMarkVarDeclReferenced");
14941   Var->setReferenced();
14942 
14943   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14944 
14945   bool OdrUseContext = isOdrUseContext(SemaRef);
14946   bool UsableInConstantExpr =
14947       Var->isUsableInConstantExpressions(SemaRef.Context);
14948   bool NeedDefinition =
14949       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
14950 
14951   VarTemplateSpecializationDecl *VarSpec =
14952       dyn_cast<VarTemplateSpecializationDecl>(Var);
14953   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14954          "Can't instantiate a partial template specialization.");
14955 
14956   // If this might be a member specialization of a static data member, check
14957   // the specialization is visible. We already did the checks for variable
14958   // template specializations when we created them.
14959   if (NeedDefinition && TSK != TSK_Undeclared &&
14960       !isa<VarTemplateSpecializationDecl>(Var))
14961     SemaRef.checkSpecializationVisibility(Loc, Var);
14962 
14963   // Perform implicit instantiation of static data members, static data member
14964   // templates of class templates, and variable template specializations. Delay
14965   // instantiations of variable templates, except for those that could be used
14966   // in a constant expression.
14967   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14968     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
14969     // instantiation declaration if a variable is usable in a constant
14970     // expression (among other cases).
14971     bool TryInstantiating =
14972         TSK == TSK_ImplicitInstantiation ||
14973         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
14974 
14975     if (TryInstantiating) {
14976       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14977       bool FirstInstantiation = PointOfInstantiation.isInvalid();
14978       if (FirstInstantiation) {
14979         PointOfInstantiation = Loc;
14980         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14981       }
14982 
14983       bool InstantiationDependent = false;
14984       bool IsNonDependent =
14985           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14986                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14987                   : true;
14988 
14989       // Do not instantiate specializations that are still type-dependent.
14990       if (IsNonDependent) {
14991         if (UsableInConstantExpr) {
14992           // Do not defer instantiations of variables that could be used in a
14993           // constant expression.
14994           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14995         } else if (FirstInstantiation ||
14996                    isa<VarTemplateSpecializationDecl>(Var)) {
14997           // FIXME: For a specialization of a variable template, we don't
14998           // distinguish between "declaration and type implicitly instantiated"
14999           // and "implicit instantiation of definition requested", so we have
15000           // no direct way to avoid enqueueing the pending instantiation
15001           // multiple times.
15002           SemaRef.PendingInstantiations
15003               .push_back(std::make_pair(Var, PointOfInstantiation));
15004         }
15005       }
15006     }
15007   }
15008 
15009   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15010   // the requirements for appearing in a constant expression (5.19) and, if
15011   // it is an object, the lvalue-to-rvalue conversion (4.1)
15012   // is immediately applied."  We check the first part here, and
15013   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15014   // Note that we use the C++11 definition everywhere because nothing in
15015   // C++03 depends on whether we get the C++03 version correct. The second
15016   // part does not apply to references, since they are not objects.
15017   if (OdrUseContext && E &&
15018       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15019     // A reference initialized by a constant expression can never be
15020     // odr-used, so simply ignore it.
15021     if (!Var->getType()->isReferenceType() ||
15022         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15023       SemaRef.MaybeODRUseExprs.insert(E);
15024   } else if (OdrUseContext) {
15025     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15026                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15027   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15028     // If this is a dependent context, we don't need to mark variables as
15029     // odr-used, but we may still need to track them for lambda capture.
15030     // FIXME: Do we also need to do this inside dependent typeid expressions
15031     // (which are modeled as unevaluated at this point)?
15032     const bool RefersToEnclosingScope =
15033         (SemaRef.CurContext != Var->getDeclContext() &&
15034          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15035     if (RefersToEnclosingScope) {
15036       LambdaScopeInfo *const LSI =
15037           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15038       if (LSI && (!LSI->CallOperator ||
15039                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15040         // If a variable could potentially be odr-used, defer marking it so
15041         // until we finish analyzing the full expression for any
15042         // lvalue-to-rvalue
15043         // or discarded value conversions that would obviate odr-use.
15044         // Add it to the list of potential captures that will be analyzed
15045         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15046         // unless the variable is a reference that was initialized by a constant
15047         // expression (this will never need to be captured or odr-used).
15048         assert(E && "Capture variable should be used in an expression.");
15049         if (!Var->getType()->isReferenceType() ||
15050             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15051           LSI->addPotentialCapture(E->IgnoreParens());
15052       }
15053     }
15054   }
15055 }
15056 
15057 /// \brief Mark a variable referenced, and check whether it is odr-used
15058 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15059 /// used directly for normal expressions referring to VarDecl.
15060 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15061   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15062 }
15063 
15064 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15065                                Decl *D, Expr *E, bool MightBeOdrUse) {
15066   if (SemaRef.isInOpenMPDeclareTargetContext())
15067     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15068 
15069   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15070     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15071     return;
15072   }
15073 
15074   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15075 
15076   // If this is a call to a method via a cast, also mark the method in the
15077   // derived class used in case codegen can devirtualize the call.
15078   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15079   if (!ME)
15080     return;
15081   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15082   if (!MD)
15083     return;
15084   // Only attempt to devirtualize if this is truly a virtual call.
15085   bool IsVirtualCall = MD->isVirtual() &&
15086                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15087   if (!IsVirtualCall)
15088     return;
15089 
15090   // If it's possible to devirtualize the call, mark the called function
15091   // referenced.
15092   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15093       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15094   if (DM)
15095     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15096 }
15097 
15098 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
15099 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15100   // TODO: update this with DR# once a defect report is filed.
15101   // C++11 defect. The address of a pure member should not be an ODR use, even
15102   // if it's a qualified reference.
15103   bool OdrUse = true;
15104   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15105     if (Method->isVirtual() &&
15106         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15107       OdrUse = false;
15108   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15109 }
15110 
15111 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
15112 void Sema::MarkMemberReferenced(MemberExpr *E) {
15113   // C++11 [basic.def.odr]p2:
15114   //   A non-overloaded function whose name appears as a potentially-evaluated
15115   //   expression or a member of a set of candidate functions, if selected by
15116   //   overload resolution when referred to from a potentially-evaluated
15117   //   expression, is odr-used, unless it is a pure virtual function and its
15118   //   name is not explicitly qualified.
15119   bool MightBeOdrUse = true;
15120   if (E->performsVirtualDispatch(getLangOpts())) {
15121     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15122       if (Method->isPure())
15123         MightBeOdrUse = false;
15124   }
15125   SourceLocation Loc = E->getMemberLoc().isValid() ?
15126                             E->getMemberLoc() : E->getLocStart();
15127   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15128 }
15129 
15130 /// \brief Perform marking for a reference to an arbitrary declaration.  It
15131 /// marks the declaration referenced, and performs odr-use checking for
15132 /// functions and variables. This method should not be used when building a
15133 /// normal expression which refers to a variable.
15134 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15135                                  bool MightBeOdrUse) {
15136   if (MightBeOdrUse) {
15137     if (auto *VD = dyn_cast<VarDecl>(D)) {
15138       MarkVariableReferenced(Loc, VD);
15139       return;
15140     }
15141   }
15142   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15143     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15144     return;
15145   }
15146   D->setReferenced();
15147 }
15148 
15149 namespace {
15150   // Mark all of the declarations used by a type as referenced.
15151   // FIXME: Not fully implemented yet! We need to have a better understanding
15152   // of when we're entering a context we should not recurse into.
15153   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15154   // TreeTransforms rebuilding the type in a new context. Rather than
15155   // duplicating the TreeTransform logic, we should consider reusing it here.
15156   // Currently that causes problems when rebuilding LambdaExprs.
15157   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15158     Sema &S;
15159     SourceLocation Loc;
15160 
15161   public:
15162     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15163 
15164     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15165 
15166     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15167   };
15168 }
15169 
15170 bool MarkReferencedDecls::TraverseTemplateArgument(
15171     const TemplateArgument &Arg) {
15172   {
15173     // A non-type template argument is a constant-evaluated context.
15174     EnterExpressionEvaluationContext Evaluated(
15175         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15176     if (Arg.getKind() == TemplateArgument::Declaration) {
15177       if (Decl *D = Arg.getAsDecl())
15178         S.MarkAnyDeclReferenced(Loc, D, true);
15179     } else if (Arg.getKind() == TemplateArgument::Expression) {
15180       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15181     }
15182   }
15183 
15184   return Inherited::TraverseTemplateArgument(Arg);
15185 }
15186 
15187 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15188   MarkReferencedDecls Marker(*this, Loc);
15189   Marker.TraverseType(T);
15190 }
15191 
15192 namespace {
15193   /// \brief Helper class that marks all of the declarations referenced by
15194   /// potentially-evaluated subexpressions as "referenced".
15195   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15196     Sema &S;
15197     bool SkipLocalVariables;
15198 
15199   public:
15200     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15201 
15202     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15203       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15204 
15205     void VisitDeclRefExpr(DeclRefExpr *E) {
15206       // If we were asked not to visit local variables, don't.
15207       if (SkipLocalVariables) {
15208         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15209           if (VD->hasLocalStorage())
15210             return;
15211       }
15212 
15213       S.MarkDeclRefReferenced(E);
15214     }
15215 
15216     void VisitMemberExpr(MemberExpr *E) {
15217       S.MarkMemberReferenced(E);
15218       Inherited::VisitMemberExpr(E);
15219     }
15220 
15221     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15222       S.MarkFunctionReferenced(E->getLocStart(),
15223             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15224       Visit(E->getSubExpr());
15225     }
15226 
15227     void VisitCXXNewExpr(CXXNewExpr *E) {
15228       if (E->getOperatorNew())
15229         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15230       if (E->getOperatorDelete())
15231         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15232       Inherited::VisitCXXNewExpr(E);
15233     }
15234 
15235     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15236       if (E->getOperatorDelete())
15237         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15238       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15239       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15240         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15241         S.MarkFunctionReferenced(E->getLocStart(),
15242                                     S.LookupDestructor(Record));
15243       }
15244 
15245       Inherited::VisitCXXDeleteExpr(E);
15246     }
15247 
15248     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15249       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15250       Inherited::VisitCXXConstructExpr(E);
15251     }
15252 
15253     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15254       Visit(E->getExpr());
15255     }
15256 
15257     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15258       Inherited::VisitImplicitCastExpr(E);
15259 
15260       if (E->getCastKind() == CK_LValueToRValue)
15261         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15262     }
15263   };
15264 }
15265 
15266 /// \brief Mark any declarations that appear within this expression or any
15267 /// potentially-evaluated subexpressions as "referenced".
15268 ///
15269 /// \param SkipLocalVariables If true, don't mark local variables as
15270 /// 'referenced'.
15271 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15272                                             bool SkipLocalVariables) {
15273   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15274 }
15275 
15276 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
15277 /// of the program being compiled.
15278 ///
15279 /// This routine emits the given diagnostic when the code currently being
15280 /// type-checked is "potentially evaluated", meaning that there is a
15281 /// possibility that the code will actually be executable. Code in sizeof()
15282 /// expressions, code used only during overload resolution, etc., are not
15283 /// potentially evaluated. This routine will suppress such diagnostics or,
15284 /// in the absolutely nutty case of potentially potentially evaluated
15285 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15286 /// later.
15287 ///
15288 /// This routine should be used for all diagnostics that describe the run-time
15289 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15290 /// Failure to do so will likely result in spurious diagnostics or failures
15291 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15292 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15293                                const PartialDiagnostic &PD) {
15294   switch (ExprEvalContexts.back().Context) {
15295   case ExpressionEvaluationContext::Unevaluated:
15296   case ExpressionEvaluationContext::UnevaluatedList:
15297   case ExpressionEvaluationContext::UnevaluatedAbstract:
15298   case ExpressionEvaluationContext::DiscardedStatement:
15299     // The argument will never be evaluated, so don't complain.
15300     break;
15301 
15302   case ExpressionEvaluationContext::ConstantEvaluated:
15303     // Relevant diagnostics should be produced by constant evaluation.
15304     break;
15305 
15306   case ExpressionEvaluationContext::PotentiallyEvaluated:
15307   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15308     if (Statement && getCurFunctionOrMethodDecl()) {
15309       FunctionScopes.back()->PossiblyUnreachableDiags.
15310         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15311       return true;
15312     }
15313 
15314     // The initializer of a constexpr variable or of the first declaration of a
15315     // static data member is not syntactically a constant evaluated constant,
15316     // but nonetheless is always required to be a constant expression, so we
15317     // can skip diagnosing.
15318     // FIXME: Using the mangling context here is a hack.
15319     if (auto *VD = dyn_cast_or_null<VarDecl>(
15320             ExprEvalContexts.back().ManglingContextDecl)) {
15321       if (VD->isConstexpr() ||
15322           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15323         break;
15324       // FIXME: For any other kind of variable, we should build a CFG for its
15325       // initializer and check whether the context in question is reachable.
15326     }
15327 
15328     Diag(Loc, PD);
15329     return true;
15330   }
15331 
15332   return false;
15333 }
15334 
15335 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15336                                CallExpr *CE, FunctionDecl *FD) {
15337   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15338     return false;
15339 
15340   // If we're inside a decltype's expression, don't check for a valid return
15341   // type or construct temporaries until we know whether this is the last call.
15342   if (ExprEvalContexts.back().IsDecltype) {
15343     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15344     return false;
15345   }
15346 
15347   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15348     FunctionDecl *FD;
15349     CallExpr *CE;
15350 
15351   public:
15352     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15353       : FD(FD), CE(CE) { }
15354 
15355     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15356       if (!FD) {
15357         S.Diag(Loc, diag::err_call_incomplete_return)
15358           << T << CE->getSourceRange();
15359         return;
15360       }
15361 
15362       S.Diag(Loc, diag::err_call_function_incomplete_return)
15363         << CE->getSourceRange() << FD->getDeclName() << T;
15364       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15365           << FD->getDeclName();
15366     }
15367   } Diagnoser(FD, CE);
15368 
15369   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15370     return true;
15371 
15372   return false;
15373 }
15374 
15375 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15376 // will prevent this condition from triggering, which is what we want.
15377 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15378   SourceLocation Loc;
15379 
15380   unsigned diagnostic = diag::warn_condition_is_assignment;
15381   bool IsOrAssign = false;
15382 
15383   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15384     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15385       return;
15386 
15387     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15388 
15389     // Greylist some idioms by putting them into a warning subcategory.
15390     if (ObjCMessageExpr *ME
15391           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15392       Selector Sel = ME->getSelector();
15393 
15394       // self = [<foo> init...]
15395       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15396         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15397 
15398       // <foo> = [<bar> nextObject]
15399       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15400         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15401     }
15402 
15403     Loc = Op->getOperatorLoc();
15404   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15405     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15406       return;
15407 
15408     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15409     Loc = Op->getOperatorLoc();
15410   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15411     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15412   else {
15413     // Not an assignment.
15414     return;
15415   }
15416 
15417   Diag(Loc, diagnostic) << E->getSourceRange();
15418 
15419   SourceLocation Open = E->getLocStart();
15420   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15421   Diag(Loc, diag::note_condition_assign_silence)
15422         << FixItHint::CreateInsertion(Open, "(")
15423         << FixItHint::CreateInsertion(Close, ")");
15424 
15425   if (IsOrAssign)
15426     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15427       << FixItHint::CreateReplacement(Loc, "!=");
15428   else
15429     Diag(Loc, diag::note_condition_assign_to_comparison)
15430       << FixItHint::CreateReplacement(Loc, "==");
15431 }
15432 
15433 /// \brief Redundant parentheses over an equality comparison can indicate
15434 /// that the user intended an assignment used as condition.
15435 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15436   // Don't warn if the parens came from a macro.
15437   SourceLocation parenLoc = ParenE->getLocStart();
15438   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15439     return;
15440   // Don't warn for dependent expressions.
15441   if (ParenE->isTypeDependent())
15442     return;
15443 
15444   Expr *E = ParenE->IgnoreParens();
15445 
15446   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15447     if (opE->getOpcode() == BO_EQ &&
15448         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15449                                                            == Expr::MLV_Valid) {
15450       SourceLocation Loc = opE->getOperatorLoc();
15451 
15452       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15453       SourceRange ParenERange = ParenE->getSourceRange();
15454       Diag(Loc, diag::note_equality_comparison_silence)
15455         << FixItHint::CreateRemoval(ParenERange.getBegin())
15456         << FixItHint::CreateRemoval(ParenERange.getEnd());
15457       Diag(Loc, diag::note_equality_comparison_to_assign)
15458         << FixItHint::CreateReplacement(Loc, "=");
15459     }
15460 }
15461 
15462 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15463                                        bool IsConstexpr) {
15464   DiagnoseAssignmentAsCondition(E);
15465   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15466     DiagnoseEqualityWithExtraParens(parenE);
15467 
15468   ExprResult result = CheckPlaceholderExpr(E);
15469   if (result.isInvalid()) return ExprError();
15470   E = result.get();
15471 
15472   if (!E->isTypeDependent()) {
15473     if (getLangOpts().CPlusPlus)
15474       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15475 
15476     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15477     if (ERes.isInvalid())
15478       return ExprError();
15479     E = ERes.get();
15480 
15481     QualType T = E->getType();
15482     if (!T->isScalarType()) { // C99 6.8.4.1p1
15483       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15484         << T << E->getSourceRange();
15485       return ExprError();
15486     }
15487     CheckBoolLikeConversion(E, Loc);
15488   }
15489 
15490   return E;
15491 }
15492 
15493 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15494                                            Expr *SubExpr, ConditionKind CK) {
15495   // Empty conditions are valid in for-statements.
15496   if (!SubExpr)
15497     return ConditionResult();
15498 
15499   ExprResult Cond;
15500   switch (CK) {
15501   case ConditionKind::Boolean:
15502     Cond = CheckBooleanCondition(Loc, SubExpr);
15503     break;
15504 
15505   case ConditionKind::ConstexprIf:
15506     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15507     break;
15508 
15509   case ConditionKind::Switch:
15510     Cond = CheckSwitchCondition(Loc, SubExpr);
15511     break;
15512   }
15513   if (Cond.isInvalid())
15514     return ConditionError();
15515 
15516   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15517   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15518   if (!FullExpr.get())
15519     return ConditionError();
15520 
15521   return ConditionResult(*this, nullptr, FullExpr,
15522                          CK == ConditionKind::ConstexprIf);
15523 }
15524 
15525 namespace {
15526   /// A visitor for rebuilding a call to an __unknown_any expression
15527   /// to have an appropriate type.
15528   struct RebuildUnknownAnyFunction
15529     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15530 
15531     Sema &S;
15532 
15533     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15534 
15535     ExprResult VisitStmt(Stmt *S) {
15536       llvm_unreachable("unexpected statement!");
15537     }
15538 
15539     ExprResult VisitExpr(Expr *E) {
15540       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15541         << E->getSourceRange();
15542       return ExprError();
15543     }
15544 
15545     /// Rebuild an expression which simply semantically wraps another
15546     /// expression which it shares the type and value kind of.
15547     template <class T> ExprResult rebuildSugarExpr(T *E) {
15548       ExprResult SubResult = Visit(E->getSubExpr());
15549       if (SubResult.isInvalid()) return ExprError();
15550 
15551       Expr *SubExpr = SubResult.get();
15552       E->setSubExpr(SubExpr);
15553       E->setType(SubExpr->getType());
15554       E->setValueKind(SubExpr->getValueKind());
15555       assert(E->getObjectKind() == OK_Ordinary);
15556       return E;
15557     }
15558 
15559     ExprResult VisitParenExpr(ParenExpr *E) {
15560       return rebuildSugarExpr(E);
15561     }
15562 
15563     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15564       return rebuildSugarExpr(E);
15565     }
15566 
15567     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15568       ExprResult SubResult = Visit(E->getSubExpr());
15569       if (SubResult.isInvalid()) return ExprError();
15570 
15571       Expr *SubExpr = SubResult.get();
15572       E->setSubExpr(SubExpr);
15573       E->setType(S.Context.getPointerType(SubExpr->getType()));
15574       assert(E->getValueKind() == VK_RValue);
15575       assert(E->getObjectKind() == OK_Ordinary);
15576       return E;
15577     }
15578 
15579     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15580       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15581 
15582       E->setType(VD->getType());
15583 
15584       assert(E->getValueKind() == VK_RValue);
15585       if (S.getLangOpts().CPlusPlus &&
15586           !(isa<CXXMethodDecl>(VD) &&
15587             cast<CXXMethodDecl>(VD)->isInstance()))
15588         E->setValueKind(VK_LValue);
15589 
15590       return E;
15591     }
15592 
15593     ExprResult VisitMemberExpr(MemberExpr *E) {
15594       return resolveDecl(E, E->getMemberDecl());
15595     }
15596 
15597     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15598       return resolveDecl(E, E->getDecl());
15599     }
15600   };
15601 }
15602 
15603 /// Given a function expression of unknown-any type, try to rebuild it
15604 /// to have a function type.
15605 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15606   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15607   if (Result.isInvalid()) return ExprError();
15608   return S.DefaultFunctionArrayConversion(Result.get());
15609 }
15610 
15611 namespace {
15612   /// A visitor for rebuilding an expression of type __unknown_anytype
15613   /// into one which resolves the type directly on the referring
15614   /// expression.  Strict preservation of the original source
15615   /// structure is not a goal.
15616   struct RebuildUnknownAnyExpr
15617     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15618 
15619     Sema &S;
15620 
15621     /// The current destination type.
15622     QualType DestType;
15623 
15624     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15625       : S(S), DestType(CastType) {}
15626 
15627     ExprResult VisitStmt(Stmt *S) {
15628       llvm_unreachable("unexpected statement!");
15629     }
15630 
15631     ExprResult VisitExpr(Expr *E) {
15632       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15633         << E->getSourceRange();
15634       return ExprError();
15635     }
15636 
15637     ExprResult VisitCallExpr(CallExpr *E);
15638     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15639 
15640     /// Rebuild an expression which simply semantically wraps another
15641     /// expression which it shares the type and value kind of.
15642     template <class T> ExprResult rebuildSugarExpr(T *E) {
15643       ExprResult SubResult = Visit(E->getSubExpr());
15644       if (SubResult.isInvalid()) return ExprError();
15645       Expr *SubExpr = SubResult.get();
15646       E->setSubExpr(SubExpr);
15647       E->setType(SubExpr->getType());
15648       E->setValueKind(SubExpr->getValueKind());
15649       assert(E->getObjectKind() == OK_Ordinary);
15650       return E;
15651     }
15652 
15653     ExprResult VisitParenExpr(ParenExpr *E) {
15654       return rebuildSugarExpr(E);
15655     }
15656 
15657     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15658       return rebuildSugarExpr(E);
15659     }
15660 
15661     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15662       const PointerType *Ptr = DestType->getAs<PointerType>();
15663       if (!Ptr) {
15664         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15665           << E->getSourceRange();
15666         return ExprError();
15667       }
15668 
15669       if (isa<CallExpr>(E->getSubExpr())) {
15670         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15671           << E->getSourceRange();
15672         return ExprError();
15673       }
15674 
15675       assert(E->getValueKind() == VK_RValue);
15676       assert(E->getObjectKind() == OK_Ordinary);
15677       E->setType(DestType);
15678 
15679       // Build the sub-expression as if it were an object of the pointee type.
15680       DestType = Ptr->getPointeeType();
15681       ExprResult SubResult = Visit(E->getSubExpr());
15682       if (SubResult.isInvalid()) return ExprError();
15683       E->setSubExpr(SubResult.get());
15684       return E;
15685     }
15686 
15687     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15688 
15689     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15690 
15691     ExprResult VisitMemberExpr(MemberExpr *E) {
15692       return resolveDecl(E, E->getMemberDecl());
15693     }
15694 
15695     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15696       return resolveDecl(E, E->getDecl());
15697     }
15698   };
15699 }
15700 
15701 /// Rebuilds a call expression which yielded __unknown_anytype.
15702 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15703   Expr *CalleeExpr = E->getCallee();
15704 
15705   enum FnKind {
15706     FK_MemberFunction,
15707     FK_FunctionPointer,
15708     FK_BlockPointer
15709   };
15710 
15711   FnKind Kind;
15712   QualType CalleeType = CalleeExpr->getType();
15713   if (CalleeType == S.Context.BoundMemberTy) {
15714     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15715     Kind = FK_MemberFunction;
15716     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15717   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15718     CalleeType = Ptr->getPointeeType();
15719     Kind = FK_FunctionPointer;
15720   } else {
15721     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15722     Kind = FK_BlockPointer;
15723   }
15724   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15725 
15726   // Verify that this is a legal result type of a function.
15727   if (DestType->isArrayType() || DestType->isFunctionType()) {
15728     unsigned diagID = diag::err_func_returning_array_function;
15729     if (Kind == FK_BlockPointer)
15730       diagID = diag::err_block_returning_array_function;
15731 
15732     S.Diag(E->getExprLoc(), diagID)
15733       << DestType->isFunctionType() << DestType;
15734     return ExprError();
15735   }
15736 
15737   // Otherwise, go ahead and set DestType as the call's result.
15738   E->setType(DestType.getNonLValueExprType(S.Context));
15739   E->setValueKind(Expr::getValueKindForType(DestType));
15740   assert(E->getObjectKind() == OK_Ordinary);
15741 
15742   // Rebuild the function type, replacing the result type with DestType.
15743   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15744   if (Proto) {
15745     // __unknown_anytype(...) is a special case used by the debugger when
15746     // it has no idea what a function's signature is.
15747     //
15748     // We want to build this call essentially under the K&R
15749     // unprototyped rules, but making a FunctionNoProtoType in C++
15750     // would foul up all sorts of assumptions.  However, we cannot
15751     // simply pass all arguments as variadic arguments, nor can we
15752     // portably just call the function under a non-variadic type; see
15753     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15754     // However, it turns out that in practice it is generally safe to
15755     // call a function declared as "A foo(B,C,D);" under the prototype
15756     // "A foo(B,C,D,...);".  The only known exception is with the
15757     // Windows ABI, where any variadic function is implicitly cdecl
15758     // regardless of its normal CC.  Therefore we change the parameter
15759     // types to match the types of the arguments.
15760     //
15761     // This is a hack, but it is far superior to moving the
15762     // corresponding target-specific code from IR-gen to Sema/AST.
15763 
15764     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15765     SmallVector<QualType, 8> ArgTypes;
15766     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15767       ArgTypes.reserve(E->getNumArgs());
15768       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15769         Expr *Arg = E->getArg(i);
15770         QualType ArgType = Arg->getType();
15771         if (E->isLValue()) {
15772           ArgType = S.Context.getLValueReferenceType(ArgType);
15773         } else if (E->isXValue()) {
15774           ArgType = S.Context.getRValueReferenceType(ArgType);
15775         }
15776         ArgTypes.push_back(ArgType);
15777       }
15778       ParamTypes = ArgTypes;
15779     }
15780     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15781                                          Proto->getExtProtoInfo());
15782   } else {
15783     DestType = S.Context.getFunctionNoProtoType(DestType,
15784                                                 FnType->getExtInfo());
15785   }
15786 
15787   // Rebuild the appropriate pointer-to-function type.
15788   switch (Kind) {
15789   case FK_MemberFunction:
15790     // Nothing to do.
15791     break;
15792 
15793   case FK_FunctionPointer:
15794     DestType = S.Context.getPointerType(DestType);
15795     break;
15796 
15797   case FK_BlockPointer:
15798     DestType = S.Context.getBlockPointerType(DestType);
15799     break;
15800   }
15801 
15802   // Finally, we can recurse.
15803   ExprResult CalleeResult = Visit(CalleeExpr);
15804   if (!CalleeResult.isUsable()) return ExprError();
15805   E->setCallee(CalleeResult.get());
15806 
15807   // Bind a temporary if necessary.
15808   return S.MaybeBindToTemporary(E);
15809 }
15810 
15811 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15812   // Verify that this is a legal result type of a call.
15813   if (DestType->isArrayType() || DestType->isFunctionType()) {
15814     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15815       << DestType->isFunctionType() << DestType;
15816     return ExprError();
15817   }
15818 
15819   // Rewrite the method result type if available.
15820   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15821     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15822     Method->setReturnType(DestType);
15823   }
15824 
15825   // Change the type of the message.
15826   E->setType(DestType.getNonReferenceType());
15827   E->setValueKind(Expr::getValueKindForType(DestType));
15828 
15829   return S.MaybeBindToTemporary(E);
15830 }
15831 
15832 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15833   // The only case we should ever see here is a function-to-pointer decay.
15834   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15835     assert(E->getValueKind() == VK_RValue);
15836     assert(E->getObjectKind() == OK_Ordinary);
15837 
15838     E->setType(DestType);
15839 
15840     // Rebuild the sub-expression as the pointee (function) type.
15841     DestType = DestType->castAs<PointerType>()->getPointeeType();
15842 
15843     ExprResult Result = Visit(E->getSubExpr());
15844     if (!Result.isUsable()) return ExprError();
15845 
15846     E->setSubExpr(Result.get());
15847     return E;
15848   } else if (E->getCastKind() == CK_LValueToRValue) {
15849     assert(E->getValueKind() == VK_RValue);
15850     assert(E->getObjectKind() == OK_Ordinary);
15851 
15852     assert(isa<BlockPointerType>(E->getType()));
15853 
15854     E->setType(DestType);
15855 
15856     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15857     DestType = S.Context.getLValueReferenceType(DestType);
15858 
15859     ExprResult Result = Visit(E->getSubExpr());
15860     if (!Result.isUsable()) return ExprError();
15861 
15862     E->setSubExpr(Result.get());
15863     return E;
15864   } else {
15865     llvm_unreachable("Unhandled cast type!");
15866   }
15867 }
15868 
15869 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15870   ExprValueKind ValueKind = VK_LValue;
15871   QualType Type = DestType;
15872 
15873   // We know how to make this work for certain kinds of decls:
15874 
15875   //  - functions
15876   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15877     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15878       DestType = Ptr->getPointeeType();
15879       ExprResult Result = resolveDecl(E, VD);
15880       if (Result.isInvalid()) return ExprError();
15881       return S.ImpCastExprToType(Result.get(), Type,
15882                                  CK_FunctionToPointerDecay, VK_RValue);
15883     }
15884 
15885     if (!Type->isFunctionType()) {
15886       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15887         << VD << E->getSourceRange();
15888       return ExprError();
15889     }
15890     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15891       // We must match the FunctionDecl's type to the hack introduced in
15892       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15893       // type. See the lengthy commentary in that routine.
15894       QualType FDT = FD->getType();
15895       const FunctionType *FnType = FDT->castAs<FunctionType>();
15896       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15897       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15898       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15899         SourceLocation Loc = FD->getLocation();
15900         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15901                                       FD->getDeclContext(),
15902                                       Loc, Loc, FD->getNameInfo().getName(),
15903                                       DestType, FD->getTypeSourceInfo(),
15904                                       SC_None, false/*isInlineSpecified*/,
15905                                       FD->hasPrototype(),
15906                                       false/*isConstexprSpecified*/);
15907 
15908         if (FD->getQualifier())
15909           NewFD->setQualifierInfo(FD->getQualifierLoc());
15910 
15911         SmallVector<ParmVarDecl*, 16> Params;
15912         for (const auto &AI : FT->param_types()) {
15913           ParmVarDecl *Param =
15914             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15915           Param->setScopeInfo(0, Params.size());
15916           Params.push_back(Param);
15917         }
15918         NewFD->setParams(Params);
15919         DRE->setDecl(NewFD);
15920         VD = DRE->getDecl();
15921       }
15922     }
15923 
15924     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15925       if (MD->isInstance()) {
15926         ValueKind = VK_RValue;
15927         Type = S.Context.BoundMemberTy;
15928       }
15929 
15930     // Function references aren't l-values in C.
15931     if (!S.getLangOpts().CPlusPlus)
15932       ValueKind = VK_RValue;
15933 
15934   //  - variables
15935   } else if (isa<VarDecl>(VD)) {
15936     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15937       Type = RefTy->getPointeeType();
15938     } else if (Type->isFunctionType()) {
15939       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15940         << VD << E->getSourceRange();
15941       return ExprError();
15942     }
15943 
15944   //  - nothing else
15945   } else {
15946     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15947       << VD << E->getSourceRange();
15948     return ExprError();
15949   }
15950 
15951   // Modifying the declaration like this is friendly to IR-gen but
15952   // also really dangerous.
15953   VD->setType(DestType);
15954   E->setType(Type);
15955   E->setValueKind(ValueKind);
15956   return E;
15957 }
15958 
15959 /// Check a cast of an unknown-any type.  We intentionally only
15960 /// trigger this for C-style casts.
15961 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15962                                      Expr *CastExpr, CastKind &CastKind,
15963                                      ExprValueKind &VK, CXXCastPath &Path) {
15964   // The type we're casting to must be either void or complete.
15965   if (!CastType->isVoidType() &&
15966       RequireCompleteType(TypeRange.getBegin(), CastType,
15967                           diag::err_typecheck_cast_to_incomplete))
15968     return ExprError();
15969 
15970   // Rewrite the casted expression from scratch.
15971   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15972   if (!result.isUsable()) return ExprError();
15973 
15974   CastExpr = result.get();
15975   VK = CastExpr->getValueKind();
15976   CastKind = CK_NoOp;
15977 
15978   return CastExpr;
15979 }
15980 
15981 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15982   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15983 }
15984 
15985 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15986                                     Expr *arg, QualType &paramType) {
15987   // If the syntactic form of the argument is not an explicit cast of
15988   // any sort, just do default argument promotion.
15989   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15990   if (!castArg) {
15991     ExprResult result = DefaultArgumentPromotion(arg);
15992     if (result.isInvalid()) return ExprError();
15993     paramType = result.get()->getType();
15994     return result;
15995   }
15996 
15997   // Otherwise, use the type that was written in the explicit cast.
15998   assert(!arg->hasPlaceholderType());
15999   paramType = castArg->getTypeAsWritten();
16000 
16001   // Copy-initialize a parameter of that type.
16002   InitializedEntity entity =
16003     InitializedEntity::InitializeParameter(Context, paramType,
16004                                            /*consumed*/ false);
16005   return PerformCopyInitialization(entity, callLoc, arg);
16006 }
16007 
16008 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16009   Expr *orig = E;
16010   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16011   while (true) {
16012     E = E->IgnoreParenImpCasts();
16013     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16014       E = call->getCallee();
16015       diagID = diag::err_uncasted_call_of_unknown_any;
16016     } else {
16017       break;
16018     }
16019   }
16020 
16021   SourceLocation loc;
16022   NamedDecl *d;
16023   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16024     loc = ref->getLocation();
16025     d = ref->getDecl();
16026   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16027     loc = mem->getMemberLoc();
16028     d = mem->getMemberDecl();
16029   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16030     diagID = diag::err_uncasted_call_of_unknown_any;
16031     loc = msg->getSelectorStartLoc();
16032     d = msg->getMethodDecl();
16033     if (!d) {
16034       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16035         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16036         << orig->getSourceRange();
16037       return ExprError();
16038     }
16039   } else {
16040     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16041       << E->getSourceRange();
16042     return ExprError();
16043   }
16044 
16045   S.Diag(loc, diagID) << d << orig->getSourceRange();
16046 
16047   // Never recoverable.
16048   return ExprError();
16049 }
16050 
16051 /// Check for operands with placeholder types and complain if found.
16052 /// Returns ExprError() if there was an error and no recovery was possible.
16053 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16054   if (!getLangOpts().CPlusPlus) {
16055     // C cannot handle TypoExpr nodes on either side of a binop because it
16056     // doesn't handle dependent types properly, so make sure any TypoExprs have
16057     // been dealt with before checking the operands.
16058     ExprResult Result = CorrectDelayedTyposInExpr(E);
16059     if (!Result.isUsable()) return ExprError();
16060     E = Result.get();
16061   }
16062 
16063   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16064   if (!placeholderType) return E;
16065 
16066   switch (placeholderType->getKind()) {
16067 
16068   // Overloaded expressions.
16069   case BuiltinType::Overload: {
16070     // Try to resolve a single function template specialization.
16071     // This is obligatory.
16072     ExprResult Result = E;
16073     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16074       return Result;
16075 
16076     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16077     // leaves Result unchanged on failure.
16078     Result = E;
16079     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16080       return Result;
16081 
16082     // If that failed, try to recover with a call.
16083     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16084                          /*complain*/ true);
16085     return Result;
16086   }
16087 
16088   // Bound member functions.
16089   case BuiltinType::BoundMember: {
16090     ExprResult result = E;
16091     const Expr *BME = E->IgnoreParens();
16092     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16093     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16094     if (isa<CXXPseudoDestructorExpr>(BME)) {
16095       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16096     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16097       if (ME->getMemberNameInfo().getName().getNameKind() ==
16098           DeclarationName::CXXDestructorName)
16099         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16100     }
16101     tryToRecoverWithCall(result, PD,
16102                          /*complain*/ true);
16103     return result;
16104   }
16105 
16106   // ARC unbridged casts.
16107   case BuiltinType::ARCUnbridgedCast: {
16108     Expr *realCast = stripARCUnbridgedCast(E);
16109     diagnoseARCUnbridgedCast(realCast);
16110     return realCast;
16111   }
16112 
16113   // Expressions of unknown type.
16114   case BuiltinType::UnknownAny:
16115     return diagnoseUnknownAnyExpr(*this, E);
16116 
16117   // Pseudo-objects.
16118   case BuiltinType::PseudoObject:
16119     return checkPseudoObjectRValue(E);
16120 
16121   case BuiltinType::BuiltinFn: {
16122     // Accept __noop without parens by implicitly converting it to a call expr.
16123     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16124     if (DRE) {
16125       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16126       if (FD->getBuiltinID() == Builtin::BI__noop) {
16127         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16128                               CK_BuiltinFnToFnPtr).get();
16129         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16130                                       VK_RValue, SourceLocation());
16131       }
16132     }
16133 
16134     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16135     return ExprError();
16136   }
16137 
16138   // Expressions of unknown type.
16139   case BuiltinType::OMPArraySection:
16140     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16141     return ExprError();
16142 
16143   // Everything else should be impossible.
16144 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16145   case BuiltinType::Id:
16146 #include "clang/Basic/OpenCLImageTypes.def"
16147 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16148 #define PLACEHOLDER_TYPE(Id, SingletonId)
16149 #include "clang/AST/BuiltinTypes.def"
16150     break;
16151   }
16152 
16153   llvm_unreachable("invalid placeholder type!");
16154 }
16155 
16156 bool Sema::CheckCaseExpression(Expr *E) {
16157   if (E->isTypeDependent())
16158     return true;
16159   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16160     return E->getType()->isIntegralOrEnumerationType();
16161   return false;
16162 }
16163 
16164 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16165 ExprResult
16166 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16167   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16168          "Unknown Objective-C Boolean value!");
16169   QualType BoolT = Context.ObjCBuiltinBoolTy;
16170   if (!Context.getBOOLDecl()) {
16171     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16172                         Sema::LookupOrdinaryName);
16173     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16174       NamedDecl *ND = Result.getFoundDecl();
16175       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16176         Context.setBOOLDecl(TD);
16177     }
16178   }
16179   if (Context.getBOOLDecl())
16180     BoolT = Context.getBOOLType();
16181   return new (Context)
16182       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16183 }
16184 
16185 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16186     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16187     SourceLocation RParen) {
16188 
16189   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16190 
16191   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16192                            [&](const AvailabilitySpec &Spec) {
16193                              return Spec.getPlatform() == Platform;
16194                            });
16195 
16196   VersionTuple Version;
16197   if (Spec != AvailSpecs.end())
16198     Version = Spec->getVersion();
16199 
16200   // The use of `@available` in the enclosing function should be analyzed to
16201   // warn when it's used inappropriately (i.e. not if(@available)).
16202   if (getCurFunctionOrMethodDecl())
16203     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16204   else if (getCurBlock() || getCurLambda())
16205     getCurFunction()->HasPotentialAvailabilityViolations = true;
16206 
16207   return new (Context)
16208       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16209 }
16210