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     if (getLangOpts().Char8)
1539       CharTy = Context.Char8Ty;
1540     Kind = StringLiteral::UTF8;
1541   } else if (Literal.isUTF16()) {
1542     CharTy = Context.Char16Ty;
1543     Kind = StringLiteral::UTF16;
1544   } else if (Literal.isUTF32()) {
1545     CharTy = Context.Char32Ty;
1546     Kind = StringLiteral::UTF32;
1547   } else if (Literal.isPascal()) {
1548     CharTy = Context.UnsignedCharTy;
1549   }
1550 
1551   QualType CharTyConst = CharTy;
1552   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1553   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1554     CharTyConst.addConst();
1555 
1556   // Get an array type for the string, according to C99 6.4.5.  This includes
1557   // the nul terminator character as well as the string length for pascal
1558   // strings.
1559   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1560                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1561                                  ArrayType::Normal, 0);
1562 
1563   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1564   if (getLangOpts().OpenCL) {
1565     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1566   }
1567 
1568   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1569   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1570                                              Kind, Literal.Pascal, StrTy,
1571                                              &StringTokLocs[0],
1572                                              StringTokLocs.size());
1573   if (Literal.getUDSuffix().empty())
1574     return Lit;
1575 
1576   // We're building a user-defined literal.
1577   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1578   SourceLocation UDSuffixLoc =
1579     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1580                    Literal.getUDSuffixOffset());
1581 
1582   // Make sure we're allowed user-defined literals here.
1583   if (!UDLScope)
1584     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1585 
1586   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1587   //   operator "" X (str, len)
1588   QualType SizeType = Context.getSizeType();
1589 
1590   DeclarationName OpName =
1591     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1592   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1593   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1594 
1595   QualType ArgTy[] = {
1596     Context.getArrayDecayedType(StrTy), SizeType
1597   };
1598 
1599   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1600   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1601                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1602                                 /*AllowStringTemplate*/ true,
1603                                 /*DiagnoseMissing*/ true)) {
1604 
1605   case LOLR_Cooked: {
1606     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1607     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1608                                                     StringTokLocs[0]);
1609     Expr *Args[] = { Lit, LenArg };
1610 
1611     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1612   }
1613 
1614   case LOLR_StringTemplate: {
1615     TemplateArgumentListInfo ExplicitArgs;
1616 
1617     unsigned CharBits = Context.getIntWidth(CharTy);
1618     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1619     llvm::APSInt Value(CharBits, CharIsUnsigned);
1620 
1621     TemplateArgument TypeArg(CharTy);
1622     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1623     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1624 
1625     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1626       Value = Lit->getCodeUnit(I);
1627       TemplateArgument Arg(Context, Value, CharTy);
1628       TemplateArgumentLocInfo ArgInfo;
1629       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1630     }
1631     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1632                                     &ExplicitArgs);
1633   }
1634   case LOLR_Raw:
1635   case LOLR_Template:
1636   case LOLR_ErrorNoDiagnostic:
1637     llvm_unreachable("unexpected literal operator lookup result");
1638   case LOLR_Error:
1639     return ExprError();
1640   }
1641   llvm_unreachable("unexpected literal operator lookup result");
1642 }
1643 
1644 ExprResult
1645 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1646                        SourceLocation Loc,
1647                        const CXXScopeSpec *SS) {
1648   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1649   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1650 }
1651 
1652 /// BuildDeclRefExpr - Build an expression that references a
1653 /// declaration that does not require a closure capture.
1654 ExprResult
1655 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1656                        const DeclarationNameInfo &NameInfo,
1657                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1658                        const TemplateArgumentListInfo *TemplateArgs) {
1659   bool RefersToCapturedVariable =
1660       isa<VarDecl>(D) &&
1661       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1662 
1663   DeclRefExpr *E;
1664   if (isa<VarTemplateSpecializationDecl>(D)) {
1665     VarTemplateSpecializationDecl *VarSpec =
1666         cast<VarTemplateSpecializationDecl>(D);
1667 
1668     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1669                                         : NestedNameSpecifierLoc(),
1670                             VarSpec->getTemplateKeywordLoc(), D,
1671                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1672                             FoundD, TemplateArgs);
1673   } else {
1674     assert(!TemplateArgs && "No template arguments for non-variable"
1675                             " template specialization references");
1676     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1677                                         : NestedNameSpecifierLoc(),
1678                             SourceLocation(), D, RefersToCapturedVariable,
1679                             NameInfo, Ty, VK, FoundD);
1680   }
1681 
1682   MarkDeclRefReferenced(E);
1683 
1684   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1685       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1686       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1687     getCurFunction()->recordUseOfWeak(E);
1688 
1689   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1690   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1691     FD = IFD->getAnonField();
1692   if (FD) {
1693     UnusedPrivateFields.remove(FD);
1694     // Just in case we're building an illegal pointer-to-member.
1695     if (FD->isBitField())
1696       E->setObjectKind(OK_BitField);
1697   }
1698 
1699   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1700   // designates a bit-field.
1701   if (auto *BD = dyn_cast<BindingDecl>(D))
1702     if (auto *BE = BD->getBinding())
1703       E->setObjectKind(BE->getObjectKind());
1704 
1705   return E;
1706 }
1707 
1708 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1709 /// possibly a list of template arguments.
1710 ///
1711 /// If this produces template arguments, it is permitted to call
1712 /// DecomposeTemplateName.
1713 ///
1714 /// This actually loses a lot of source location information for
1715 /// non-standard name kinds; we should consider preserving that in
1716 /// some way.
1717 void
1718 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1719                              TemplateArgumentListInfo &Buffer,
1720                              DeclarationNameInfo &NameInfo,
1721                              const TemplateArgumentListInfo *&TemplateArgs) {
1722   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1723     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1724     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1725 
1726     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1727                                        Id.TemplateId->NumArgs);
1728     translateTemplateArguments(TemplateArgsPtr, Buffer);
1729 
1730     TemplateName TName = Id.TemplateId->Template.get();
1731     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1732     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1733     TemplateArgs = &Buffer;
1734   } else {
1735     NameInfo = GetNameFromUnqualifiedId(Id);
1736     TemplateArgs = nullptr;
1737   }
1738 }
1739 
1740 static void emitEmptyLookupTypoDiagnostic(
1741     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1742     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1743     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1744   DeclContext *Ctx =
1745       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1746   if (!TC) {
1747     // Emit a special diagnostic for failed member lookups.
1748     // FIXME: computing the declaration context might fail here (?)
1749     if (Ctx)
1750       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1751                                                  << SS.getRange();
1752     else
1753       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1754     return;
1755   }
1756 
1757   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1758   bool DroppedSpecifier =
1759       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1760   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1761                         ? diag::note_implicit_param_decl
1762                         : diag::note_previous_decl;
1763   if (!Ctx)
1764     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1765                          SemaRef.PDiag(NoteID));
1766   else
1767     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1768                                  << Typo << Ctx << DroppedSpecifier
1769                                  << SS.getRange(),
1770                          SemaRef.PDiag(NoteID));
1771 }
1772 
1773 /// Diagnose an empty lookup.
1774 ///
1775 /// \return false if new lookup candidates were found
1776 bool
1777 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1778                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1779                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1780                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1781   DeclarationName Name = R.getLookupName();
1782 
1783   unsigned diagnostic = diag::err_undeclared_var_use;
1784   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1785   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1786       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1787       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1788     diagnostic = diag::err_undeclared_use;
1789     diagnostic_suggest = diag::err_undeclared_use_suggest;
1790   }
1791 
1792   // If the original lookup was an unqualified lookup, fake an
1793   // unqualified lookup.  This is useful when (for example) the
1794   // original lookup would not have found something because it was a
1795   // dependent name.
1796   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1797   while (DC) {
1798     if (isa<CXXRecordDecl>(DC)) {
1799       LookupQualifiedName(R, DC);
1800 
1801       if (!R.empty()) {
1802         // Don't give errors about ambiguities in this lookup.
1803         R.suppressDiagnostics();
1804 
1805         // During a default argument instantiation the CurContext points
1806         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1807         // function parameter list, hence add an explicit check.
1808         bool isDefaultArgument =
1809             !CodeSynthesisContexts.empty() &&
1810             CodeSynthesisContexts.back().Kind ==
1811                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1812         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1813         bool isInstance = CurMethod &&
1814                           CurMethod->isInstance() &&
1815                           DC == CurMethod->getParent() && !isDefaultArgument;
1816 
1817         // Give a code modification hint to insert 'this->'.
1818         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1819         // Actually quite difficult!
1820         if (getLangOpts().MSVCCompat)
1821           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1822         if (isInstance) {
1823           Diag(R.getNameLoc(), diagnostic) << Name
1824             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1825           CheckCXXThisCapture(R.getNameLoc());
1826         } else {
1827           Diag(R.getNameLoc(), diagnostic) << Name;
1828         }
1829 
1830         // Do we really want to note all of these?
1831         for (NamedDecl *D : R)
1832           Diag(D->getLocation(), diag::note_dependent_var_use);
1833 
1834         // Return true if we are inside a default argument instantiation
1835         // and the found name refers to an instance member function, otherwise
1836         // the function calling DiagnoseEmptyLookup will try to create an
1837         // implicit member call and this is wrong for default argument.
1838         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1839           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1840           return true;
1841         }
1842 
1843         // Tell the callee to try to recover.
1844         return false;
1845       }
1846 
1847       R.clear();
1848     }
1849 
1850     // In Microsoft mode, if we are performing lookup from within a friend
1851     // function definition declared at class scope then we must set
1852     // DC to the lexical parent to be able to search into the parent
1853     // class.
1854     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1855         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1856         DC->getLexicalParent()->isRecord())
1857       DC = DC->getLexicalParent();
1858     else
1859       DC = DC->getParent();
1860   }
1861 
1862   // We didn't find anything, so try to correct for a typo.
1863   TypoCorrection Corrected;
1864   if (S && Out) {
1865     SourceLocation TypoLoc = R.getNameLoc();
1866     assert(!ExplicitTemplateArgs &&
1867            "Diagnosing an empty lookup with explicit template args!");
1868     *Out = CorrectTypoDelayed(
1869         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1870         [=](const TypoCorrection &TC) {
1871           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1872                                         diagnostic, diagnostic_suggest);
1873         },
1874         nullptr, CTK_ErrorRecovery);
1875     if (*Out)
1876       return true;
1877   } else if (S && (Corrected =
1878                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1879                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1880     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1881     bool DroppedSpecifier =
1882         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1883     R.setLookupName(Corrected.getCorrection());
1884 
1885     bool AcceptableWithRecovery = false;
1886     bool AcceptableWithoutRecovery = false;
1887     NamedDecl *ND = Corrected.getFoundDecl();
1888     if (ND) {
1889       if (Corrected.isOverloaded()) {
1890         OverloadCandidateSet OCS(R.getNameLoc(),
1891                                  OverloadCandidateSet::CSK_Normal);
1892         OverloadCandidateSet::iterator Best;
1893         for (NamedDecl *CD : Corrected) {
1894           if (FunctionTemplateDecl *FTD =
1895                    dyn_cast<FunctionTemplateDecl>(CD))
1896             AddTemplateOverloadCandidate(
1897                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1898                 Args, OCS);
1899           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1900             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1901               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1902                                    Args, OCS);
1903         }
1904         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1905         case OR_Success:
1906           ND = Best->FoundDecl;
1907           Corrected.setCorrectionDecl(ND);
1908           break;
1909         default:
1910           // FIXME: Arbitrarily pick the first declaration for the note.
1911           Corrected.setCorrectionDecl(ND);
1912           break;
1913         }
1914       }
1915       R.addDecl(ND);
1916       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1917         CXXRecordDecl *Record = nullptr;
1918         if (Corrected.getCorrectionSpecifier()) {
1919           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1920           Record = Ty->getAsCXXRecordDecl();
1921         }
1922         if (!Record)
1923           Record = cast<CXXRecordDecl>(
1924               ND->getDeclContext()->getRedeclContext());
1925         R.setNamingClass(Record);
1926       }
1927 
1928       auto *UnderlyingND = ND->getUnderlyingDecl();
1929       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1930                                isa<FunctionTemplateDecl>(UnderlyingND);
1931       // FIXME: If we ended up with a typo for a type name or
1932       // Objective-C class name, we're in trouble because the parser
1933       // is in the wrong place to recover. Suggest the typo
1934       // correction, but don't make it a fix-it since we're not going
1935       // to recover well anyway.
1936       AcceptableWithoutRecovery =
1937           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1938     } else {
1939       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1940       // because we aren't able to recover.
1941       AcceptableWithoutRecovery = true;
1942     }
1943 
1944     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1945       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1946                             ? diag::note_implicit_param_decl
1947                             : diag::note_previous_decl;
1948       if (SS.isEmpty())
1949         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1950                      PDiag(NoteID), AcceptableWithRecovery);
1951       else
1952         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1953                                   << Name << computeDeclContext(SS, false)
1954                                   << DroppedSpecifier << SS.getRange(),
1955                      PDiag(NoteID), AcceptableWithRecovery);
1956 
1957       // Tell the callee whether to try to recover.
1958       return !AcceptableWithRecovery;
1959     }
1960   }
1961   R.clear();
1962 
1963   // Emit a special diagnostic for failed member lookups.
1964   // FIXME: computing the declaration context might fail here (?)
1965   if (!SS.isEmpty()) {
1966     Diag(R.getNameLoc(), diag::err_no_member)
1967       << Name << computeDeclContext(SS, false)
1968       << SS.getRange();
1969     return true;
1970   }
1971 
1972   // Give up, we can't recover.
1973   Diag(R.getNameLoc(), diagnostic) << Name;
1974   return true;
1975 }
1976 
1977 /// In Microsoft mode, if we are inside a template class whose parent class has
1978 /// dependent base classes, and we can't resolve an unqualified identifier, then
1979 /// assume the identifier is a member of a dependent base class.  We can only
1980 /// recover successfully in static methods, instance methods, and other contexts
1981 /// where 'this' is available.  This doesn't precisely match MSVC's
1982 /// instantiation model, but it's close enough.
1983 static Expr *
1984 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1985                                DeclarationNameInfo &NameInfo,
1986                                SourceLocation TemplateKWLoc,
1987                                const TemplateArgumentListInfo *TemplateArgs) {
1988   // Only try to recover from lookup into dependent bases in static methods or
1989   // contexts where 'this' is available.
1990   QualType ThisType = S.getCurrentThisType();
1991   const CXXRecordDecl *RD = nullptr;
1992   if (!ThisType.isNull())
1993     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1994   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1995     RD = MD->getParent();
1996   if (!RD || !RD->hasAnyDependentBases())
1997     return nullptr;
1998 
1999   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2000   // is available, suggest inserting 'this->' as a fixit.
2001   SourceLocation Loc = NameInfo.getLoc();
2002   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2003   DB << NameInfo.getName() << RD;
2004 
2005   if (!ThisType.isNull()) {
2006     DB << FixItHint::CreateInsertion(Loc, "this->");
2007     return CXXDependentScopeMemberExpr::Create(
2008         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2009         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2010         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2011   }
2012 
2013   // Synthesize a fake NNS that points to the derived class.  This will
2014   // perform name lookup during template instantiation.
2015   CXXScopeSpec SS;
2016   auto *NNS =
2017       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2018   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2019   return DependentScopeDeclRefExpr::Create(
2020       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2021       TemplateArgs);
2022 }
2023 
2024 ExprResult
2025 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2026                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2027                         bool HasTrailingLParen, bool IsAddressOfOperand,
2028                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2029                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2030   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2031          "cannot be direct & operand and have a trailing lparen");
2032   if (SS.isInvalid())
2033     return ExprError();
2034 
2035   TemplateArgumentListInfo TemplateArgsBuffer;
2036 
2037   // Decompose the UnqualifiedId into the following data.
2038   DeclarationNameInfo NameInfo;
2039   const TemplateArgumentListInfo *TemplateArgs;
2040   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2041 
2042   DeclarationName Name = NameInfo.getName();
2043   IdentifierInfo *II = Name.getAsIdentifierInfo();
2044   SourceLocation NameLoc = NameInfo.getLoc();
2045 
2046   if (II && II->isEditorPlaceholder()) {
2047     // FIXME: When typed placeholders are supported we can create a typed
2048     // placeholder expression node.
2049     return ExprError();
2050   }
2051 
2052   // C++ [temp.dep.expr]p3:
2053   //   An id-expression is type-dependent if it contains:
2054   //     -- an identifier that was declared with a dependent type,
2055   //        (note: handled after lookup)
2056   //     -- a template-id that is dependent,
2057   //        (note: handled in BuildTemplateIdExpr)
2058   //     -- a conversion-function-id that specifies a dependent type,
2059   //     -- a nested-name-specifier that contains a class-name that
2060   //        names a dependent type.
2061   // Determine whether this is a member of an unknown specialization;
2062   // we need to handle these differently.
2063   bool DependentID = false;
2064   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2065       Name.getCXXNameType()->isDependentType()) {
2066     DependentID = true;
2067   } else if (SS.isSet()) {
2068     if (DeclContext *DC = computeDeclContext(SS, false)) {
2069       if (RequireCompleteDeclContext(SS, DC))
2070         return ExprError();
2071     } else {
2072       DependentID = true;
2073     }
2074   }
2075 
2076   if (DependentID)
2077     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2078                                       IsAddressOfOperand, TemplateArgs);
2079 
2080   // Perform the required lookup.
2081   LookupResult R(*this, NameInfo,
2082                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2083                      ? LookupObjCImplicitSelfParam
2084                      : LookupOrdinaryName);
2085   if (TemplateKWLoc.isValid() || TemplateArgs) {
2086     // Lookup the template name again to correctly establish the context in
2087     // which it was found. This is really unfortunate as we already did the
2088     // lookup to determine that it was a template name in the first place. If
2089     // this becomes a performance hit, we can work harder to preserve those
2090     // results until we get here but it's likely not worth it.
2091     bool MemberOfUnknownSpecialization;
2092     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2093                        MemberOfUnknownSpecialization);
2094 
2095     if (MemberOfUnknownSpecialization ||
2096         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2097       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2098                                         IsAddressOfOperand, TemplateArgs);
2099   } else {
2100     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2101     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2102 
2103     // If the result might be in a dependent base class, this is a dependent
2104     // id-expression.
2105     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2106       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2107                                         IsAddressOfOperand, TemplateArgs);
2108 
2109     // If this reference is in an Objective-C method, then we need to do
2110     // some special Objective-C lookup, too.
2111     if (IvarLookupFollowUp) {
2112       ExprResult E(LookupInObjCMethod(R, S, II, true));
2113       if (E.isInvalid())
2114         return ExprError();
2115 
2116       if (Expr *Ex = E.getAs<Expr>())
2117         return Ex;
2118     }
2119   }
2120 
2121   if (R.isAmbiguous())
2122     return ExprError();
2123 
2124   // This could be an implicitly declared function reference (legal in C90,
2125   // extension in C99, forbidden in C++).
2126   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2127     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2128     if (D) R.addDecl(D);
2129   }
2130 
2131   // Determine whether this name might be a candidate for
2132   // argument-dependent lookup.
2133   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2134 
2135   if (R.empty() && !ADL) {
2136     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2137       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2138                                                    TemplateKWLoc, TemplateArgs))
2139         return E;
2140     }
2141 
2142     // Don't diagnose an empty lookup for inline assembly.
2143     if (IsInlineAsmIdentifier)
2144       return ExprError();
2145 
2146     // If this name wasn't predeclared and if this is not a function
2147     // call, diagnose the problem.
2148     TypoExpr *TE = nullptr;
2149     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2150         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2151     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2152     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2153            "Typo correction callback misconfigured");
2154     if (CCC) {
2155       // Make sure the callback knows what the typo being diagnosed is.
2156       CCC->setTypoName(II);
2157       if (SS.isValid())
2158         CCC->setTypoNNS(SS.getScopeRep());
2159     }
2160     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2161     // a template name, but we happen to have always already looked up the name
2162     // before we get here if it must be a template name.
2163     if (DiagnoseEmptyLookup(S, SS, R,
2164                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2165                             nullptr, None, &TE)) {
2166       if (TE && KeywordReplacement) {
2167         auto &State = getTypoExprState(TE);
2168         auto BestTC = State.Consumer->getNextCorrection();
2169         if (BestTC.isKeyword()) {
2170           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2171           if (State.DiagHandler)
2172             State.DiagHandler(BestTC);
2173           KeywordReplacement->startToken();
2174           KeywordReplacement->setKind(II->getTokenID());
2175           KeywordReplacement->setIdentifierInfo(II);
2176           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2177           // Clean up the state associated with the TypoExpr, since it has
2178           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2179           clearDelayedTypo(TE);
2180           // Signal that a correction to a keyword was performed by returning a
2181           // valid-but-null ExprResult.
2182           return (Expr*)nullptr;
2183         }
2184         State.Consumer->resetCorrectionStream();
2185       }
2186       return TE ? TE : ExprError();
2187     }
2188 
2189     assert(!R.empty() &&
2190            "DiagnoseEmptyLookup returned false but added no results");
2191 
2192     // If we found an Objective-C instance variable, let
2193     // LookupInObjCMethod build the appropriate expression to
2194     // reference the ivar.
2195     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2196       R.clear();
2197       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2198       // In a hopelessly buggy code, Objective-C instance variable
2199       // lookup fails and no expression will be built to reference it.
2200       if (!E.isInvalid() && !E.get())
2201         return ExprError();
2202       return E;
2203     }
2204   }
2205 
2206   // This is guaranteed from this point on.
2207   assert(!R.empty() || ADL);
2208 
2209   // Check whether this might be a C++ implicit instance member access.
2210   // C++ [class.mfct.non-static]p3:
2211   //   When an id-expression that is not part of a class member access
2212   //   syntax and not used to form a pointer to member is used in the
2213   //   body of a non-static member function of class X, if name lookup
2214   //   resolves the name in the id-expression to a non-static non-type
2215   //   member of some class C, the id-expression is transformed into a
2216   //   class member access expression using (*this) as the
2217   //   postfix-expression to the left of the . operator.
2218   //
2219   // But we don't actually need to do this for '&' operands if R
2220   // resolved to a function or overloaded function set, because the
2221   // expression is ill-formed if it actually works out to be a
2222   // non-static member function:
2223   //
2224   // C++ [expr.ref]p4:
2225   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2226   //   [t]he expression can be used only as the left-hand operand of a
2227   //   member function call.
2228   //
2229   // There are other safeguards against such uses, but it's important
2230   // to get this right here so that we don't end up making a
2231   // spuriously dependent expression if we're inside a dependent
2232   // instance method.
2233   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2234     bool MightBeImplicitMember;
2235     if (!IsAddressOfOperand)
2236       MightBeImplicitMember = true;
2237     else if (!SS.isEmpty())
2238       MightBeImplicitMember = false;
2239     else if (R.isOverloadedResult())
2240       MightBeImplicitMember = false;
2241     else if (R.isUnresolvableResult())
2242       MightBeImplicitMember = true;
2243     else
2244       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2245                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2246                               isa<MSPropertyDecl>(R.getFoundDecl());
2247 
2248     if (MightBeImplicitMember)
2249       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2250                                              R, TemplateArgs, S);
2251   }
2252 
2253   if (TemplateArgs || TemplateKWLoc.isValid()) {
2254 
2255     // In C++1y, if this is a variable template id, then check it
2256     // in BuildTemplateIdExpr().
2257     // The single lookup result must be a variable template declaration.
2258     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2259         Id.TemplateId->Kind == TNK_Var_template) {
2260       assert(R.getAsSingle<VarTemplateDecl>() &&
2261              "There should only be one declaration found.");
2262     }
2263 
2264     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2265   }
2266 
2267   return BuildDeclarationNameExpr(SS, R, ADL);
2268 }
2269 
2270 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2271 /// declaration name, generally during template instantiation.
2272 /// There's a large number of things which don't need to be done along
2273 /// this path.
2274 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2275     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2276     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2277   DeclContext *DC = computeDeclContext(SS, false);
2278   if (!DC)
2279     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2280                                      NameInfo, /*TemplateArgs=*/nullptr);
2281 
2282   if (RequireCompleteDeclContext(SS, DC))
2283     return ExprError();
2284 
2285   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2286   LookupQualifiedName(R, DC);
2287 
2288   if (R.isAmbiguous())
2289     return ExprError();
2290 
2291   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2292     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2293                                      NameInfo, /*TemplateArgs=*/nullptr);
2294 
2295   if (R.empty()) {
2296     Diag(NameInfo.getLoc(), diag::err_no_member)
2297       << NameInfo.getName() << DC << SS.getRange();
2298     return ExprError();
2299   }
2300 
2301   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2302     // Diagnose a missing typename if this resolved unambiguously to a type in
2303     // a dependent context.  If we can recover with a type, downgrade this to
2304     // a warning in Microsoft compatibility mode.
2305     unsigned DiagID = diag::err_typename_missing;
2306     if (RecoveryTSI && getLangOpts().MSVCCompat)
2307       DiagID = diag::ext_typename_missing;
2308     SourceLocation Loc = SS.getBeginLoc();
2309     auto D = Diag(Loc, DiagID);
2310     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2311       << SourceRange(Loc, NameInfo.getEndLoc());
2312 
2313     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2314     // context.
2315     if (!RecoveryTSI)
2316       return ExprError();
2317 
2318     // Only issue the fixit if we're prepared to recover.
2319     D << FixItHint::CreateInsertion(Loc, "typename ");
2320 
2321     // Recover by pretending this was an elaborated type.
2322     QualType Ty = Context.getTypeDeclType(TD);
2323     TypeLocBuilder TLB;
2324     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2325 
2326     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2327     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2328     QTL.setElaboratedKeywordLoc(SourceLocation());
2329     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2330 
2331     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2332 
2333     return ExprEmpty();
2334   }
2335 
2336   // Defend against this resolving to an implicit member access. We usually
2337   // won't get here if this might be a legitimate a class member (we end up in
2338   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2339   // a pointer-to-member or in an unevaluated context in C++11.
2340   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2341     return BuildPossibleImplicitMemberExpr(SS,
2342                                            /*TemplateKWLoc=*/SourceLocation(),
2343                                            R, /*TemplateArgs=*/nullptr, S);
2344 
2345   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2346 }
2347 
2348 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2349 /// detected that we're currently inside an ObjC method.  Perform some
2350 /// additional lookup.
2351 ///
2352 /// Ideally, most of this would be done by lookup, but there's
2353 /// actually quite a lot of extra work involved.
2354 ///
2355 /// Returns a null sentinel to indicate trivial success.
2356 ExprResult
2357 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2358                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2359   SourceLocation Loc = Lookup.getNameLoc();
2360   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2361 
2362   // Check for error condition which is already reported.
2363   if (!CurMethod)
2364     return ExprError();
2365 
2366   // There are two cases to handle here.  1) scoped lookup could have failed,
2367   // in which case we should look for an ivar.  2) scoped lookup could have
2368   // found a decl, but that decl is outside the current instance method (i.e.
2369   // a global variable).  In these two cases, we do a lookup for an ivar with
2370   // this name, if the lookup sucedes, we replace it our current decl.
2371 
2372   // If we're in a class method, we don't normally want to look for
2373   // ivars.  But if we don't find anything else, and there's an
2374   // ivar, that's an error.
2375   bool IsClassMethod = CurMethod->isClassMethod();
2376 
2377   bool LookForIvars;
2378   if (Lookup.empty())
2379     LookForIvars = true;
2380   else if (IsClassMethod)
2381     LookForIvars = false;
2382   else
2383     LookForIvars = (Lookup.isSingleResult() &&
2384                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2385   ObjCInterfaceDecl *IFace = nullptr;
2386   if (LookForIvars) {
2387     IFace = CurMethod->getClassInterface();
2388     ObjCInterfaceDecl *ClassDeclared;
2389     ObjCIvarDecl *IV = nullptr;
2390     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2391       // Diagnose using an ivar in a class method.
2392       if (IsClassMethod)
2393         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2394                          << IV->getDeclName());
2395 
2396       // If we're referencing an invalid decl, just return this as a silent
2397       // error node.  The error diagnostic was already emitted on the decl.
2398       if (IV->isInvalidDecl())
2399         return ExprError();
2400 
2401       // Check if referencing a field with __attribute__((deprecated)).
2402       if (DiagnoseUseOfDecl(IV, Loc))
2403         return ExprError();
2404 
2405       // Diagnose the use of an ivar outside of the declaring class.
2406       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2407           !declaresSameEntity(ClassDeclared, IFace) &&
2408           !getLangOpts().DebuggerSupport)
2409         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2410 
2411       // FIXME: This should use a new expr for a direct reference, don't
2412       // turn this into Self->ivar, just return a BareIVarExpr or something.
2413       IdentifierInfo &II = Context.Idents.get("self");
2414       UnqualifiedId SelfName;
2415       SelfName.setIdentifier(&II, SourceLocation());
2416       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2417       CXXScopeSpec SelfScopeSpec;
2418       SourceLocation TemplateKWLoc;
2419       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2420                                               SelfName, false, false);
2421       if (SelfExpr.isInvalid())
2422         return ExprError();
2423 
2424       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2425       if (SelfExpr.isInvalid())
2426         return ExprError();
2427 
2428       MarkAnyDeclReferenced(Loc, IV, true);
2429 
2430       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2431       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2432           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2433         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2434 
2435       ObjCIvarRefExpr *Result = new (Context)
2436           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2437                           IV->getLocation(), SelfExpr.get(), true, true);
2438 
2439       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2440         if (!isUnevaluatedContext() &&
2441             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2442           getCurFunction()->recordUseOfWeak(Result);
2443       }
2444       if (getLangOpts().ObjCAutoRefCount) {
2445         if (CurContext->isClosure())
2446           Diag(Loc, diag::warn_implicitly_retains_self)
2447             << FixItHint::CreateInsertion(Loc, "self->");
2448       }
2449 
2450       return Result;
2451     }
2452   } else if (CurMethod->isInstanceMethod()) {
2453     // We should warn if a local variable hides an ivar.
2454     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2455       ObjCInterfaceDecl *ClassDeclared;
2456       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2457         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2458             declaresSameEntity(IFace, ClassDeclared))
2459           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2460       }
2461     }
2462   } else if (Lookup.isSingleResult() &&
2463              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2464     // If accessing a stand-alone ivar in a class method, this is an error.
2465     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2466       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2467                        << IV->getDeclName());
2468   }
2469 
2470   if (Lookup.empty() && II && AllowBuiltinCreation) {
2471     // FIXME. Consolidate this with similar code in LookupName.
2472     if (unsigned BuiltinID = II->getBuiltinID()) {
2473       if (!(getLangOpts().CPlusPlus &&
2474             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2475         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2476                                            S, Lookup.isForRedeclaration(),
2477                                            Lookup.getNameLoc());
2478         if (D) Lookup.addDecl(D);
2479       }
2480     }
2481   }
2482   // Sentinel value saying that we didn't do anything special.
2483   return ExprResult((Expr *)nullptr);
2484 }
2485 
2486 /// \brief Cast a base object to a member's actual type.
2487 ///
2488 /// Logically this happens in three phases:
2489 ///
2490 /// * First we cast from the base type to the naming class.
2491 ///   The naming class is the class into which we were looking
2492 ///   when we found the member;  it's the qualifier type if a
2493 ///   qualifier was provided, and otherwise it's the base type.
2494 ///
2495 /// * Next we cast from the naming class to the declaring class.
2496 ///   If the member we found was brought into a class's scope by
2497 ///   a using declaration, this is that class;  otherwise it's
2498 ///   the class declaring the member.
2499 ///
2500 /// * Finally we cast from the declaring class to the "true"
2501 ///   declaring class of the member.  This conversion does not
2502 ///   obey access control.
2503 ExprResult
2504 Sema::PerformObjectMemberConversion(Expr *From,
2505                                     NestedNameSpecifier *Qualifier,
2506                                     NamedDecl *FoundDecl,
2507                                     NamedDecl *Member) {
2508   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2509   if (!RD)
2510     return From;
2511 
2512   QualType DestRecordType;
2513   QualType DestType;
2514   QualType FromRecordType;
2515   QualType FromType = From->getType();
2516   bool PointerConversions = false;
2517   if (isa<FieldDecl>(Member)) {
2518     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2519 
2520     if (FromType->getAs<PointerType>()) {
2521       DestType = Context.getPointerType(DestRecordType);
2522       FromRecordType = FromType->getPointeeType();
2523       PointerConversions = true;
2524     } else {
2525       DestType = DestRecordType;
2526       FromRecordType = FromType;
2527     }
2528   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2529     if (Method->isStatic())
2530       return From;
2531 
2532     DestType = Method->getThisType(Context);
2533     DestRecordType = DestType->getPointeeType();
2534 
2535     if (FromType->getAs<PointerType>()) {
2536       FromRecordType = FromType->getPointeeType();
2537       PointerConversions = true;
2538     } else {
2539       FromRecordType = FromType;
2540       DestType = DestRecordType;
2541     }
2542   } else {
2543     // No conversion necessary.
2544     return From;
2545   }
2546 
2547   if (DestType->isDependentType() || FromType->isDependentType())
2548     return From;
2549 
2550   // If the unqualified types are the same, no conversion is necessary.
2551   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2552     return From;
2553 
2554   SourceRange FromRange = From->getSourceRange();
2555   SourceLocation FromLoc = FromRange.getBegin();
2556 
2557   ExprValueKind VK = From->getValueKind();
2558 
2559   // C++ [class.member.lookup]p8:
2560   //   [...] Ambiguities can often be resolved by qualifying a name with its
2561   //   class name.
2562   //
2563   // If the member was a qualified name and the qualified referred to a
2564   // specific base subobject type, we'll cast to that intermediate type
2565   // first and then to the object in which the member is declared. That allows
2566   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2567   //
2568   //   class Base { public: int x; };
2569   //   class Derived1 : public Base { };
2570   //   class Derived2 : public Base { };
2571   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2572   //
2573   //   void VeryDerived::f() {
2574   //     x = 17; // error: ambiguous base subobjects
2575   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2576   //   }
2577   if (Qualifier && Qualifier->getAsType()) {
2578     QualType QType = QualType(Qualifier->getAsType(), 0);
2579     assert(QType->isRecordType() && "lookup done with non-record type");
2580 
2581     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2582 
2583     // In C++98, the qualifier type doesn't actually have to be a base
2584     // type of the object type, in which case we just ignore it.
2585     // Otherwise build the appropriate casts.
2586     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2587       CXXCastPath BasePath;
2588       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2589                                        FromLoc, FromRange, &BasePath))
2590         return ExprError();
2591 
2592       if (PointerConversions)
2593         QType = Context.getPointerType(QType);
2594       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2595                                VK, &BasePath).get();
2596 
2597       FromType = QType;
2598       FromRecordType = QRecordType;
2599 
2600       // If the qualifier type was the same as the destination type,
2601       // we're done.
2602       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2603         return From;
2604     }
2605   }
2606 
2607   bool IgnoreAccess = false;
2608 
2609   // If we actually found the member through a using declaration, cast
2610   // down to the using declaration's type.
2611   //
2612   // Pointer equality is fine here because only one declaration of a
2613   // class ever has member declarations.
2614   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2615     assert(isa<UsingShadowDecl>(FoundDecl));
2616     QualType URecordType = Context.getTypeDeclType(
2617                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2618 
2619     // We only need to do this if the naming-class to declaring-class
2620     // conversion is non-trivial.
2621     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2622       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2623       CXXCastPath BasePath;
2624       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2625                                        FromLoc, FromRange, &BasePath))
2626         return ExprError();
2627 
2628       QualType UType = URecordType;
2629       if (PointerConversions)
2630         UType = Context.getPointerType(UType);
2631       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2632                                VK, &BasePath).get();
2633       FromType = UType;
2634       FromRecordType = URecordType;
2635     }
2636 
2637     // We don't do access control for the conversion from the
2638     // declaring class to the true declaring class.
2639     IgnoreAccess = true;
2640   }
2641 
2642   CXXCastPath BasePath;
2643   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2644                                    FromLoc, FromRange, &BasePath,
2645                                    IgnoreAccess))
2646     return ExprError();
2647 
2648   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2649                            VK, &BasePath);
2650 }
2651 
2652 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2653                                       const LookupResult &R,
2654                                       bool HasTrailingLParen) {
2655   // Only when used directly as the postfix-expression of a call.
2656   if (!HasTrailingLParen)
2657     return false;
2658 
2659   // Never if a scope specifier was provided.
2660   if (SS.isSet())
2661     return false;
2662 
2663   // Only in C++ or ObjC++.
2664   if (!getLangOpts().CPlusPlus)
2665     return false;
2666 
2667   // Turn off ADL when we find certain kinds of declarations during
2668   // normal lookup:
2669   for (NamedDecl *D : R) {
2670     // C++0x [basic.lookup.argdep]p3:
2671     //     -- a declaration of a class member
2672     // Since using decls preserve this property, we check this on the
2673     // original decl.
2674     if (D->isCXXClassMember())
2675       return false;
2676 
2677     // C++0x [basic.lookup.argdep]p3:
2678     //     -- a block-scope function declaration that is not a
2679     //        using-declaration
2680     // NOTE: we also trigger this for function templates (in fact, we
2681     // don't check the decl type at all, since all other decl types
2682     // turn off ADL anyway).
2683     if (isa<UsingShadowDecl>(D))
2684       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2685     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2686       return false;
2687 
2688     // C++0x [basic.lookup.argdep]p3:
2689     //     -- a declaration that is neither a function or a function
2690     //        template
2691     // And also for builtin functions.
2692     if (isa<FunctionDecl>(D)) {
2693       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2694 
2695       // But also builtin functions.
2696       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2697         return false;
2698     } else if (!isa<FunctionTemplateDecl>(D))
2699       return false;
2700   }
2701 
2702   return true;
2703 }
2704 
2705 
2706 /// Diagnoses obvious problems with the use of the given declaration
2707 /// as an expression.  This is only actually called for lookups that
2708 /// were not overloaded, and it doesn't promise that the declaration
2709 /// will in fact be used.
2710 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2711   if (D->isInvalidDecl())
2712     return true;
2713 
2714   if (isa<TypedefNameDecl>(D)) {
2715     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2716     return true;
2717   }
2718 
2719   if (isa<ObjCInterfaceDecl>(D)) {
2720     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2721     return true;
2722   }
2723 
2724   if (isa<NamespaceDecl>(D)) {
2725     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2726     return true;
2727   }
2728 
2729   return false;
2730 }
2731 
2732 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2733                                           LookupResult &R, bool NeedsADL,
2734                                           bool AcceptInvalidDecl) {
2735   // If this is a single, fully-resolved result and we don't need ADL,
2736   // just build an ordinary singleton decl ref.
2737   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2738     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2739                                     R.getRepresentativeDecl(), nullptr,
2740                                     AcceptInvalidDecl);
2741 
2742   // We only need to check the declaration if there's exactly one
2743   // result, because in the overloaded case the results can only be
2744   // functions and function templates.
2745   if (R.isSingleResult() &&
2746       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2747     return ExprError();
2748 
2749   // Otherwise, just build an unresolved lookup expression.  Suppress
2750   // any lookup-related diagnostics; we'll hash these out later, when
2751   // we've picked a target.
2752   R.suppressDiagnostics();
2753 
2754   UnresolvedLookupExpr *ULE
2755     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2756                                    SS.getWithLocInContext(Context),
2757                                    R.getLookupNameInfo(),
2758                                    NeedsADL, R.isOverloadedResult(),
2759                                    R.begin(), R.end());
2760 
2761   return ULE;
2762 }
2763 
2764 static void
2765 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2766                                    ValueDecl *var, DeclContext *DC);
2767 
2768 /// \brief Complete semantic analysis for a reference to the given declaration.
2769 ExprResult Sema::BuildDeclarationNameExpr(
2770     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2771     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2772     bool AcceptInvalidDecl) {
2773   assert(D && "Cannot refer to a NULL declaration");
2774   assert(!isa<FunctionTemplateDecl>(D) &&
2775          "Cannot refer unambiguously to a function template");
2776 
2777   SourceLocation Loc = NameInfo.getLoc();
2778   if (CheckDeclInExpr(*this, Loc, D))
2779     return ExprError();
2780 
2781   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2782     // Specifically diagnose references to class templates that are missing
2783     // a template argument list.
2784     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2785     return ExprError();
2786   }
2787 
2788   // Make sure that we're referring to a value.
2789   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2790   if (!VD) {
2791     Diag(Loc, diag::err_ref_non_value)
2792       << D << SS.getRange();
2793     Diag(D->getLocation(), diag::note_declared_at);
2794     return ExprError();
2795   }
2796 
2797   // Check whether this declaration can be used. Note that we suppress
2798   // this check when we're going to perform argument-dependent lookup
2799   // on this function name, because this might not be the function
2800   // that overload resolution actually selects.
2801   if (DiagnoseUseOfDecl(VD, Loc))
2802     return ExprError();
2803 
2804   // Only create DeclRefExpr's for valid Decl's.
2805   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2806     return ExprError();
2807 
2808   // Handle members of anonymous structs and unions.  If we got here,
2809   // and the reference is to a class member indirect field, then this
2810   // must be the subject of a pointer-to-member expression.
2811   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2812     if (!indirectField->isCXXClassMember())
2813       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2814                                                       indirectField);
2815 
2816   {
2817     QualType type = VD->getType();
2818     if (type.isNull())
2819       return ExprError();
2820     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2821       // C++ [except.spec]p17:
2822       //   An exception-specification is considered to be needed when:
2823       //   - in an expression, the function is the unique lookup result or
2824       //     the selected member of a set of overloaded functions.
2825       ResolveExceptionSpec(Loc, FPT);
2826       type = VD->getType();
2827     }
2828     ExprValueKind valueKind = VK_RValue;
2829 
2830     switch (D->getKind()) {
2831     // Ignore all the non-ValueDecl kinds.
2832 #define ABSTRACT_DECL(kind)
2833 #define VALUE(type, base)
2834 #define DECL(type, base) \
2835     case Decl::type:
2836 #include "clang/AST/DeclNodes.inc"
2837       llvm_unreachable("invalid value decl kind");
2838 
2839     // These shouldn't make it here.
2840     case Decl::ObjCAtDefsField:
2841     case Decl::ObjCIvar:
2842       llvm_unreachable("forming non-member reference to ivar?");
2843 
2844     // Enum constants are always r-values and never references.
2845     // Unresolved using declarations are dependent.
2846     case Decl::EnumConstant:
2847     case Decl::UnresolvedUsingValue:
2848     case Decl::OMPDeclareReduction:
2849       valueKind = VK_RValue;
2850       break;
2851 
2852     // Fields and indirect fields that got here must be for
2853     // pointer-to-member expressions; we just call them l-values for
2854     // internal consistency, because this subexpression doesn't really
2855     // exist in the high-level semantics.
2856     case Decl::Field:
2857     case Decl::IndirectField:
2858       assert(getLangOpts().CPlusPlus &&
2859              "building reference to field in C?");
2860 
2861       // These can't have reference type in well-formed programs, but
2862       // for internal consistency we do this anyway.
2863       type = type.getNonReferenceType();
2864       valueKind = VK_LValue;
2865       break;
2866 
2867     // Non-type template parameters are either l-values or r-values
2868     // depending on the type.
2869     case Decl::NonTypeTemplateParm: {
2870       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2871         type = reftype->getPointeeType();
2872         valueKind = VK_LValue; // even if the parameter is an r-value reference
2873         break;
2874       }
2875 
2876       // For non-references, we need to strip qualifiers just in case
2877       // the template parameter was declared as 'const int' or whatever.
2878       valueKind = VK_RValue;
2879       type = type.getUnqualifiedType();
2880       break;
2881     }
2882 
2883     case Decl::Var:
2884     case Decl::VarTemplateSpecialization:
2885     case Decl::VarTemplatePartialSpecialization:
2886     case Decl::Decomposition:
2887     case Decl::OMPCapturedExpr:
2888       // In C, "extern void blah;" is valid and is an r-value.
2889       if (!getLangOpts().CPlusPlus &&
2890           !type.hasQualifiers() &&
2891           type->isVoidType()) {
2892         valueKind = VK_RValue;
2893         break;
2894       }
2895       LLVM_FALLTHROUGH;
2896 
2897     case Decl::ImplicitParam:
2898     case Decl::ParmVar: {
2899       // These are always l-values.
2900       valueKind = VK_LValue;
2901       type = type.getNonReferenceType();
2902 
2903       // FIXME: Does the addition of const really only apply in
2904       // potentially-evaluated contexts? Since the variable isn't actually
2905       // captured in an unevaluated context, it seems that the answer is no.
2906       if (!isUnevaluatedContext()) {
2907         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2908         if (!CapturedType.isNull())
2909           type = CapturedType;
2910       }
2911 
2912       break;
2913     }
2914 
2915     case Decl::Binding: {
2916       // These are always lvalues.
2917       valueKind = VK_LValue;
2918       type = type.getNonReferenceType();
2919       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2920       // decides how that's supposed to work.
2921       auto *BD = cast<BindingDecl>(VD);
2922       if (BD->getDeclContext()->isFunctionOrMethod() &&
2923           BD->getDeclContext() != CurContext)
2924         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2925       break;
2926     }
2927 
2928     case Decl::Function: {
2929       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2930         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2931           type = Context.BuiltinFnTy;
2932           valueKind = VK_RValue;
2933           break;
2934         }
2935       }
2936 
2937       const FunctionType *fty = type->castAs<FunctionType>();
2938 
2939       // If we're referring to a function with an __unknown_anytype
2940       // result type, make the entire expression __unknown_anytype.
2941       if (fty->getReturnType() == Context.UnknownAnyTy) {
2942         type = Context.UnknownAnyTy;
2943         valueKind = VK_RValue;
2944         break;
2945       }
2946 
2947       // Functions are l-values in C++.
2948       if (getLangOpts().CPlusPlus) {
2949         valueKind = VK_LValue;
2950         break;
2951       }
2952 
2953       // C99 DR 316 says that, if a function type comes from a
2954       // function definition (without a prototype), that type is only
2955       // used for checking compatibility. Therefore, when referencing
2956       // the function, we pretend that we don't have the full function
2957       // type.
2958       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2959           isa<FunctionProtoType>(fty))
2960         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2961                                               fty->getExtInfo());
2962 
2963       // Functions are r-values in C.
2964       valueKind = VK_RValue;
2965       break;
2966     }
2967 
2968     case Decl::CXXDeductionGuide:
2969       llvm_unreachable("building reference to deduction guide");
2970 
2971     case Decl::MSProperty:
2972       valueKind = VK_LValue;
2973       break;
2974 
2975     case Decl::CXXMethod:
2976       // If we're referring to a method with an __unknown_anytype
2977       // result type, make the entire expression __unknown_anytype.
2978       // This should only be possible with a type written directly.
2979       if (const FunctionProtoType *proto
2980             = dyn_cast<FunctionProtoType>(VD->getType()))
2981         if (proto->getReturnType() == Context.UnknownAnyTy) {
2982           type = Context.UnknownAnyTy;
2983           valueKind = VK_RValue;
2984           break;
2985         }
2986 
2987       // C++ methods are l-values if static, r-values if non-static.
2988       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2989         valueKind = VK_LValue;
2990         break;
2991       }
2992       LLVM_FALLTHROUGH;
2993 
2994     case Decl::CXXConversion:
2995     case Decl::CXXDestructor:
2996     case Decl::CXXConstructor:
2997       valueKind = VK_RValue;
2998       break;
2999     }
3000 
3001     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3002                             TemplateArgs);
3003   }
3004 }
3005 
3006 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3007                                     SmallString<32> &Target) {
3008   Target.resize(CharByteWidth * (Source.size() + 1));
3009   char *ResultPtr = &Target[0];
3010   const llvm::UTF8 *ErrorPtr;
3011   bool success =
3012       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3013   (void)success;
3014   assert(success);
3015   Target.resize(ResultPtr - &Target[0]);
3016 }
3017 
3018 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3019                                      PredefinedExpr::IdentType IT) {
3020   // Pick the current block, lambda, captured statement or function.
3021   Decl *currentDecl = nullptr;
3022   if (const BlockScopeInfo *BSI = getCurBlock())
3023     currentDecl = BSI->TheDecl;
3024   else if (const LambdaScopeInfo *LSI = getCurLambda())
3025     currentDecl = LSI->CallOperator;
3026   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3027     currentDecl = CSI->TheCapturedDecl;
3028   else
3029     currentDecl = getCurFunctionOrMethodDecl();
3030 
3031   if (!currentDecl) {
3032     Diag(Loc, diag::ext_predef_outside_function);
3033     currentDecl = Context.getTranslationUnitDecl();
3034   }
3035 
3036   QualType ResTy;
3037   StringLiteral *SL = nullptr;
3038   if (cast<DeclContext>(currentDecl)->isDependentContext())
3039     ResTy = Context.DependentTy;
3040   else {
3041     // Pre-defined identifiers are of type char[x], where x is the length of
3042     // the string.
3043     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3044     unsigned Length = Str.length();
3045 
3046     llvm::APInt LengthI(32, Length + 1);
3047     if (IT == PredefinedExpr::LFunction) {
3048       ResTy = Context.WideCharTy.withConst();
3049       SmallString<32> RawChars;
3050       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3051                               Str, RawChars);
3052       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3053                                            /*IndexTypeQuals*/ 0);
3054       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3055                                  /*Pascal*/ false, ResTy, Loc);
3056     } else {
3057       ResTy = Context.CharTy.withConst();
3058       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3059                                            /*IndexTypeQuals*/ 0);
3060       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3061                                  /*Pascal*/ false, ResTy, Loc);
3062     }
3063   }
3064 
3065   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3066 }
3067 
3068 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3069   PredefinedExpr::IdentType IT;
3070 
3071   switch (Kind) {
3072   default: llvm_unreachable("Unknown simple primary expr!");
3073   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3074   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3075   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3076   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3077   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3078   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3079   }
3080 
3081   return BuildPredefinedExpr(Loc, IT);
3082 }
3083 
3084 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3085   SmallString<16> CharBuffer;
3086   bool Invalid = false;
3087   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3088   if (Invalid)
3089     return ExprError();
3090 
3091   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3092                             PP, Tok.getKind());
3093   if (Literal.hadError())
3094     return ExprError();
3095 
3096   QualType Ty;
3097   if (Literal.isWide())
3098     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3099   else if (Literal.isUTF8() && getLangOpts().Char8)
3100     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3101   else if (Literal.isUTF16())
3102     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3103   else if (Literal.isUTF32())
3104     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3105   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3106     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3107   else
3108     Ty = Context.CharTy;  // 'x' -> char in C++
3109 
3110   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3111   if (Literal.isWide())
3112     Kind = CharacterLiteral::Wide;
3113   else if (Literal.isUTF16())
3114     Kind = CharacterLiteral::UTF16;
3115   else if (Literal.isUTF32())
3116     Kind = CharacterLiteral::UTF32;
3117   else if (Literal.isUTF8())
3118     Kind = CharacterLiteral::UTF8;
3119 
3120   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3121                                              Tok.getLocation());
3122 
3123   if (Literal.getUDSuffix().empty())
3124     return Lit;
3125 
3126   // We're building a user-defined literal.
3127   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3128   SourceLocation UDSuffixLoc =
3129     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3130 
3131   // Make sure we're allowed user-defined literals here.
3132   if (!UDLScope)
3133     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3134 
3135   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3136   //   operator "" X (ch)
3137   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3138                                         Lit, Tok.getLocation());
3139 }
3140 
3141 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3142   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3143   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3144                                 Context.IntTy, Loc);
3145 }
3146 
3147 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3148                                   QualType Ty, SourceLocation Loc) {
3149   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3150 
3151   using llvm::APFloat;
3152   APFloat Val(Format);
3153 
3154   APFloat::opStatus result = Literal.GetFloatValue(Val);
3155 
3156   // Overflow is always an error, but underflow is only an error if
3157   // we underflowed to zero (APFloat reports denormals as underflow).
3158   if ((result & APFloat::opOverflow) ||
3159       ((result & APFloat::opUnderflow) && Val.isZero())) {
3160     unsigned diagnostic;
3161     SmallString<20> buffer;
3162     if (result & APFloat::opOverflow) {
3163       diagnostic = diag::warn_float_overflow;
3164       APFloat::getLargest(Format).toString(buffer);
3165     } else {
3166       diagnostic = diag::warn_float_underflow;
3167       APFloat::getSmallest(Format).toString(buffer);
3168     }
3169 
3170     S.Diag(Loc, diagnostic)
3171       << Ty
3172       << StringRef(buffer.data(), buffer.size());
3173   }
3174 
3175   bool isExact = (result == APFloat::opOK);
3176   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3177 }
3178 
3179 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3180   assert(E && "Invalid expression");
3181 
3182   if (E->isValueDependent())
3183     return false;
3184 
3185   QualType QT = E->getType();
3186   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3187     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3188     return true;
3189   }
3190 
3191   llvm::APSInt ValueAPS;
3192   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3193 
3194   if (R.isInvalid())
3195     return true;
3196 
3197   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3198   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3199     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3200         << ValueAPS.toString(10) << ValueIsPositive;
3201     return true;
3202   }
3203 
3204   return false;
3205 }
3206 
3207 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3208   // Fast path for a single digit (which is quite common).  A single digit
3209   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3210   if (Tok.getLength() == 1) {
3211     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3212     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3213   }
3214 
3215   SmallString<128> SpellingBuffer;
3216   // NumericLiteralParser wants to overread by one character.  Add padding to
3217   // the buffer in case the token is copied to the buffer.  If getSpelling()
3218   // returns a StringRef to the memory buffer, it should have a null char at
3219   // the EOF, so it is also safe.
3220   SpellingBuffer.resize(Tok.getLength() + 1);
3221 
3222   // Get the spelling of the token, which eliminates trigraphs, etc.
3223   bool Invalid = false;
3224   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3225   if (Invalid)
3226     return ExprError();
3227 
3228   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3229   if (Literal.hadError)
3230     return ExprError();
3231 
3232   if (Literal.hasUDSuffix()) {
3233     // We're building a user-defined literal.
3234     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3235     SourceLocation UDSuffixLoc =
3236       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3237 
3238     // Make sure we're allowed user-defined literals here.
3239     if (!UDLScope)
3240       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3241 
3242     QualType CookedTy;
3243     if (Literal.isFloatingLiteral()) {
3244       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3245       // long double, the literal is treated as a call of the form
3246       //   operator "" X (f L)
3247       CookedTy = Context.LongDoubleTy;
3248     } else {
3249       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3250       // unsigned long long, the literal is treated as a call of the form
3251       //   operator "" X (n ULL)
3252       CookedTy = Context.UnsignedLongLongTy;
3253     }
3254 
3255     DeclarationName OpName =
3256       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3257     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3258     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3259 
3260     SourceLocation TokLoc = Tok.getLocation();
3261 
3262     // Perform literal operator lookup to determine if we're building a raw
3263     // literal or a cooked one.
3264     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3265     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3266                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3267                                   /*AllowStringTemplate*/ false,
3268                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3269     case LOLR_ErrorNoDiagnostic:
3270       // Lookup failure for imaginary constants isn't fatal, there's still the
3271       // GNU extension producing _Complex types.
3272       break;
3273     case LOLR_Error:
3274       return ExprError();
3275     case LOLR_Cooked: {
3276       Expr *Lit;
3277       if (Literal.isFloatingLiteral()) {
3278         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3279       } else {
3280         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3281         if (Literal.GetIntegerValue(ResultVal))
3282           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3283               << /* Unsigned */ 1;
3284         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3285                                      Tok.getLocation());
3286       }
3287       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3288     }
3289 
3290     case LOLR_Raw: {
3291       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3292       // literal is treated as a call of the form
3293       //   operator "" X ("n")
3294       unsigned Length = Literal.getUDSuffixOffset();
3295       QualType StrTy = Context.getConstantArrayType(
3296           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3297           ArrayType::Normal, 0);
3298       Expr *Lit = StringLiteral::Create(
3299           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3300           /*Pascal*/false, StrTy, &TokLoc, 1);
3301       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3302     }
3303 
3304     case LOLR_Template: {
3305       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3306       // template), L is treated as a call fo the form
3307       //   operator "" X <'c1', 'c2', ... 'ck'>()
3308       // where n is the source character sequence c1 c2 ... ck.
3309       TemplateArgumentListInfo ExplicitArgs;
3310       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3311       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3312       llvm::APSInt Value(CharBits, CharIsUnsigned);
3313       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3314         Value = TokSpelling[I];
3315         TemplateArgument Arg(Context, Value, Context.CharTy);
3316         TemplateArgumentLocInfo ArgInfo;
3317         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3318       }
3319       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3320                                       &ExplicitArgs);
3321     }
3322     case LOLR_StringTemplate:
3323       llvm_unreachable("unexpected literal operator lookup result");
3324     }
3325   }
3326 
3327   Expr *Res;
3328 
3329   if (Literal.isFloatingLiteral()) {
3330     QualType Ty;
3331     if (Literal.isHalf){
3332       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3333         Ty = Context.HalfTy;
3334       else {
3335         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3336         return ExprError();
3337       }
3338     } else if (Literal.isFloat)
3339       Ty = Context.FloatTy;
3340     else if (Literal.isLong)
3341       Ty = Context.LongDoubleTy;
3342     else if (Literal.isFloat16)
3343       Ty = Context.Float16Ty;
3344     else if (Literal.isFloat128)
3345       Ty = Context.Float128Ty;
3346     else
3347       Ty = Context.DoubleTy;
3348 
3349     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3350 
3351     if (Ty == Context.DoubleTy) {
3352       if (getLangOpts().SinglePrecisionConstants) {
3353         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3354         if (BTy->getKind() != BuiltinType::Float) {
3355           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3356         }
3357       } else if (getLangOpts().OpenCL &&
3358                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3359         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3360         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3361         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3362       }
3363     }
3364   } else if (!Literal.isIntegerLiteral()) {
3365     return ExprError();
3366   } else {
3367     QualType Ty;
3368 
3369     // 'long long' is a C99 or C++11 feature.
3370     if (!getLangOpts().C99 && Literal.isLongLong) {
3371       if (getLangOpts().CPlusPlus)
3372         Diag(Tok.getLocation(),
3373              getLangOpts().CPlusPlus11 ?
3374              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3375       else
3376         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3377     }
3378 
3379     // Get the value in the widest-possible width.
3380     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3381     llvm::APInt ResultVal(MaxWidth, 0);
3382 
3383     if (Literal.GetIntegerValue(ResultVal)) {
3384       // If this value didn't fit into uintmax_t, error and force to ull.
3385       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3386           << /* Unsigned */ 1;
3387       Ty = Context.UnsignedLongLongTy;
3388       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3389              "long long is not intmax_t?");
3390     } else {
3391       // If this value fits into a ULL, try to figure out what else it fits into
3392       // according to the rules of C99 6.4.4.1p5.
3393 
3394       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3395       // be an unsigned int.
3396       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3397 
3398       // Check from smallest to largest, picking the smallest type we can.
3399       unsigned Width = 0;
3400 
3401       // Microsoft specific integer suffixes are explicitly sized.
3402       if (Literal.MicrosoftInteger) {
3403         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3404           Width = 8;
3405           Ty = Context.CharTy;
3406         } else {
3407           Width = Literal.MicrosoftInteger;
3408           Ty = Context.getIntTypeForBitwidth(Width,
3409                                              /*Signed=*/!Literal.isUnsigned);
3410         }
3411       }
3412 
3413       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3414         // Are int/unsigned possibilities?
3415         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3416 
3417         // Does it fit in a unsigned int?
3418         if (ResultVal.isIntN(IntSize)) {
3419           // Does it fit in a signed int?
3420           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3421             Ty = Context.IntTy;
3422           else if (AllowUnsigned)
3423             Ty = Context.UnsignedIntTy;
3424           Width = IntSize;
3425         }
3426       }
3427 
3428       // Are long/unsigned long possibilities?
3429       if (Ty.isNull() && !Literal.isLongLong) {
3430         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3431 
3432         // Does it fit in a unsigned long?
3433         if (ResultVal.isIntN(LongSize)) {
3434           // Does it fit in a signed long?
3435           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3436             Ty = Context.LongTy;
3437           else if (AllowUnsigned)
3438             Ty = Context.UnsignedLongTy;
3439           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3440           // is compatible.
3441           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3442             const unsigned LongLongSize =
3443                 Context.getTargetInfo().getLongLongWidth();
3444             Diag(Tok.getLocation(),
3445                  getLangOpts().CPlusPlus
3446                      ? Literal.isLong
3447                            ? diag::warn_old_implicitly_unsigned_long_cxx
3448                            : /*C++98 UB*/ diag::
3449                                  ext_old_implicitly_unsigned_long_cxx
3450                      : diag::warn_old_implicitly_unsigned_long)
3451                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3452                                             : /*will be ill-formed*/ 1);
3453             Ty = Context.UnsignedLongTy;
3454           }
3455           Width = LongSize;
3456         }
3457       }
3458 
3459       // Check long long if needed.
3460       if (Ty.isNull()) {
3461         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3462 
3463         // Does it fit in a unsigned long long?
3464         if (ResultVal.isIntN(LongLongSize)) {
3465           // Does it fit in a signed long long?
3466           // To be compatible with MSVC, hex integer literals ending with the
3467           // LL or i64 suffix are always signed in Microsoft mode.
3468           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3469               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3470             Ty = Context.LongLongTy;
3471           else if (AllowUnsigned)
3472             Ty = Context.UnsignedLongLongTy;
3473           Width = LongLongSize;
3474         }
3475       }
3476 
3477       // If we still couldn't decide a type, we probably have something that
3478       // does not fit in a signed long long, but has no U suffix.
3479       if (Ty.isNull()) {
3480         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3481         Ty = Context.UnsignedLongLongTy;
3482         Width = Context.getTargetInfo().getLongLongWidth();
3483       }
3484 
3485       if (ResultVal.getBitWidth() != Width)
3486         ResultVal = ResultVal.trunc(Width);
3487     }
3488     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3489   }
3490 
3491   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3492   if (Literal.isImaginary) {
3493     Res = new (Context) ImaginaryLiteral(Res,
3494                                         Context.getComplexType(Res->getType()));
3495 
3496     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3497   }
3498   return Res;
3499 }
3500 
3501 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3502   assert(E && "ActOnParenExpr() missing expr");
3503   return new (Context) ParenExpr(L, R, E);
3504 }
3505 
3506 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3507                                          SourceLocation Loc,
3508                                          SourceRange ArgRange) {
3509   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3510   // scalar or vector data type argument..."
3511   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3512   // type (C99 6.2.5p18) or void.
3513   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3514     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3515       << T << ArgRange;
3516     return true;
3517   }
3518 
3519   assert((T->isVoidType() || !T->isIncompleteType()) &&
3520          "Scalar types should always be complete");
3521   return false;
3522 }
3523 
3524 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3525                                            SourceLocation Loc,
3526                                            SourceRange ArgRange,
3527                                            UnaryExprOrTypeTrait TraitKind) {
3528   // Invalid types must be hard errors for SFINAE in C++.
3529   if (S.LangOpts.CPlusPlus)
3530     return true;
3531 
3532   // C99 6.5.3.4p1:
3533   if (T->isFunctionType() &&
3534       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3535     // sizeof(function)/alignof(function) is allowed as an extension.
3536     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3537       << TraitKind << ArgRange;
3538     return false;
3539   }
3540 
3541   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3542   // this is an error (OpenCL v1.1 s6.3.k)
3543   if (T->isVoidType()) {
3544     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3545                                         : diag::ext_sizeof_alignof_void_type;
3546     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3547     return false;
3548   }
3549 
3550   return true;
3551 }
3552 
3553 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3554                                              SourceLocation Loc,
3555                                              SourceRange ArgRange,
3556                                              UnaryExprOrTypeTrait TraitKind) {
3557   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3558   // runtime doesn't allow it.
3559   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3560     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3561       << T << (TraitKind == UETT_SizeOf)
3562       << ArgRange;
3563     return true;
3564   }
3565 
3566   return false;
3567 }
3568 
3569 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3570 /// pointer type is equal to T) and emit a warning if it is.
3571 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3572                                      Expr *E) {
3573   // Don't warn if the operation changed the type.
3574   if (T != E->getType())
3575     return;
3576 
3577   // Now look for array decays.
3578   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3579   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3580     return;
3581 
3582   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3583                                              << ICE->getType()
3584                                              << ICE->getSubExpr()->getType();
3585 }
3586 
3587 /// \brief Check the constraints on expression operands to unary type expression
3588 /// and type traits.
3589 ///
3590 /// Completes any types necessary and validates the constraints on the operand
3591 /// expression. The logic mostly mirrors the type-based overload, but may modify
3592 /// the expression as it completes the type for that expression through template
3593 /// instantiation, etc.
3594 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3595                                             UnaryExprOrTypeTrait ExprKind) {
3596   QualType ExprTy = E->getType();
3597   assert(!ExprTy->isReferenceType());
3598 
3599   if (ExprKind == UETT_VecStep)
3600     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3601                                         E->getSourceRange());
3602 
3603   // Whitelist some types as extensions
3604   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3605                                       E->getSourceRange(), ExprKind))
3606     return false;
3607 
3608   // 'alignof' applied to an expression only requires the base element type of
3609   // the expression to be complete. 'sizeof' requires the expression's type to
3610   // be complete (and will attempt to complete it if it's an array of unknown
3611   // bound).
3612   if (ExprKind == UETT_AlignOf) {
3613     if (RequireCompleteType(E->getExprLoc(),
3614                             Context.getBaseElementType(E->getType()),
3615                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3616                             E->getSourceRange()))
3617       return true;
3618   } else {
3619     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3620                                 ExprKind, E->getSourceRange()))
3621       return true;
3622   }
3623 
3624   // Completing the expression's type may have changed it.
3625   ExprTy = E->getType();
3626   assert(!ExprTy->isReferenceType());
3627 
3628   if (ExprTy->isFunctionType()) {
3629     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3630       << ExprKind << E->getSourceRange();
3631     return true;
3632   }
3633 
3634   // The operand for sizeof and alignof is in an unevaluated expression context,
3635   // so side effects could result in unintended consequences.
3636   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3637       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3638     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3639 
3640   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3641                                        E->getSourceRange(), ExprKind))
3642     return true;
3643 
3644   if (ExprKind == UETT_SizeOf) {
3645     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3646       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3647         QualType OType = PVD->getOriginalType();
3648         QualType Type = PVD->getType();
3649         if (Type->isPointerType() && OType->isArrayType()) {
3650           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3651             << Type << OType;
3652           Diag(PVD->getLocation(), diag::note_declared_at);
3653         }
3654       }
3655     }
3656 
3657     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3658     // decays into a pointer and returns an unintended result. This is most
3659     // likely a typo for "sizeof(array) op x".
3660     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3661       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3662                                BO->getLHS());
3663       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3664                                BO->getRHS());
3665     }
3666   }
3667 
3668   return false;
3669 }
3670 
3671 /// \brief Check the constraints on operands to unary expression and type
3672 /// traits.
3673 ///
3674 /// This will complete any types necessary, and validate the various constraints
3675 /// on those operands.
3676 ///
3677 /// The UsualUnaryConversions() function is *not* called by this routine.
3678 /// C99 6.3.2.1p[2-4] all state:
3679 ///   Except when it is the operand of the sizeof operator ...
3680 ///
3681 /// C++ [expr.sizeof]p4
3682 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3683 ///   standard conversions are not applied to the operand of sizeof.
3684 ///
3685 /// This policy is followed for all of the unary trait expressions.
3686 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3687                                             SourceLocation OpLoc,
3688                                             SourceRange ExprRange,
3689                                             UnaryExprOrTypeTrait ExprKind) {
3690   if (ExprType->isDependentType())
3691     return false;
3692 
3693   // C++ [expr.sizeof]p2:
3694   //     When applied to a reference or a reference type, the result
3695   //     is the size of the referenced type.
3696   // C++11 [expr.alignof]p3:
3697   //     When alignof is applied to a reference type, the result
3698   //     shall be the alignment of the referenced type.
3699   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3700     ExprType = Ref->getPointeeType();
3701 
3702   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3703   //   When alignof or _Alignof is applied to an array type, the result
3704   //   is the alignment of the element type.
3705   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3706     ExprType = Context.getBaseElementType(ExprType);
3707 
3708   if (ExprKind == UETT_VecStep)
3709     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3710 
3711   // Whitelist some types as extensions
3712   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3713                                       ExprKind))
3714     return false;
3715 
3716   if (RequireCompleteType(OpLoc, ExprType,
3717                           diag::err_sizeof_alignof_incomplete_type,
3718                           ExprKind, ExprRange))
3719     return true;
3720 
3721   if (ExprType->isFunctionType()) {
3722     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3723       << ExprKind << ExprRange;
3724     return true;
3725   }
3726 
3727   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3728                                        ExprKind))
3729     return true;
3730 
3731   return false;
3732 }
3733 
3734 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3735   E = E->IgnoreParens();
3736 
3737   // Cannot know anything else if the expression is dependent.
3738   if (E->isTypeDependent())
3739     return false;
3740 
3741   if (E->getObjectKind() == OK_BitField) {
3742     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3743        << 1 << E->getSourceRange();
3744     return true;
3745   }
3746 
3747   ValueDecl *D = nullptr;
3748   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3749     D = DRE->getDecl();
3750   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3751     D = ME->getMemberDecl();
3752   }
3753 
3754   // If it's a field, require the containing struct to have a
3755   // complete definition so that we can compute the layout.
3756   //
3757   // This can happen in C++11 onwards, either by naming the member
3758   // in a way that is not transformed into a member access expression
3759   // (in an unevaluated operand, for instance), or by naming the member
3760   // in a trailing-return-type.
3761   //
3762   // For the record, since __alignof__ on expressions is a GCC
3763   // extension, GCC seems to permit this but always gives the
3764   // nonsensical answer 0.
3765   //
3766   // We don't really need the layout here --- we could instead just
3767   // directly check for all the appropriate alignment-lowing
3768   // attributes --- but that would require duplicating a lot of
3769   // logic that just isn't worth duplicating for such a marginal
3770   // use-case.
3771   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3772     // Fast path this check, since we at least know the record has a
3773     // definition if we can find a member of it.
3774     if (!FD->getParent()->isCompleteDefinition()) {
3775       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3776         << E->getSourceRange();
3777       return true;
3778     }
3779 
3780     // Otherwise, if it's a field, and the field doesn't have
3781     // reference type, then it must have a complete type (or be a
3782     // flexible array member, which we explicitly want to
3783     // white-list anyway), which makes the following checks trivial.
3784     if (!FD->getType()->isReferenceType())
3785       return false;
3786   }
3787 
3788   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3789 }
3790 
3791 bool Sema::CheckVecStepExpr(Expr *E) {
3792   E = E->IgnoreParens();
3793 
3794   // Cannot know anything else if the expression is dependent.
3795   if (E->isTypeDependent())
3796     return false;
3797 
3798   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3799 }
3800 
3801 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3802                                         CapturingScopeInfo *CSI) {
3803   assert(T->isVariablyModifiedType());
3804   assert(CSI != nullptr);
3805 
3806   // We're going to walk down into the type and look for VLA expressions.
3807   do {
3808     const Type *Ty = T.getTypePtr();
3809     switch (Ty->getTypeClass()) {
3810 #define TYPE(Class, Base)
3811 #define ABSTRACT_TYPE(Class, Base)
3812 #define NON_CANONICAL_TYPE(Class, Base)
3813 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3814 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3815 #include "clang/AST/TypeNodes.def"
3816       T = QualType();
3817       break;
3818     // These types are never variably-modified.
3819     case Type::Builtin:
3820     case Type::Complex:
3821     case Type::Vector:
3822     case Type::ExtVector:
3823     case Type::Record:
3824     case Type::Enum:
3825     case Type::Elaborated:
3826     case Type::TemplateSpecialization:
3827     case Type::ObjCObject:
3828     case Type::ObjCInterface:
3829     case Type::ObjCObjectPointer:
3830     case Type::ObjCTypeParam:
3831     case Type::Pipe:
3832       llvm_unreachable("type class is never variably-modified!");
3833     case Type::Adjusted:
3834       T = cast<AdjustedType>(Ty)->getOriginalType();
3835       break;
3836     case Type::Decayed:
3837       T = cast<DecayedType>(Ty)->getPointeeType();
3838       break;
3839     case Type::Pointer:
3840       T = cast<PointerType>(Ty)->getPointeeType();
3841       break;
3842     case Type::BlockPointer:
3843       T = cast<BlockPointerType>(Ty)->getPointeeType();
3844       break;
3845     case Type::LValueReference:
3846     case Type::RValueReference:
3847       T = cast<ReferenceType>(Ty)->getPointeeType();
3848       break;
3849     case Type::MemberPointer:
3850       T = cast<MemberPointerType>(Ty)->getPointeeType();
3851       break;
3852     case Type::ConstantArray:
3853     case Type::IncompleteArray:
3854       // Losing element qualification here is fine.
3855       T = cast<ArrayType>(Ty)->getElementType();
3856       break;
3857     case Type::VariableArray: {
3858       // Losing element qualification here is fine.
3859       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3860 
3861       // Unknown size indication requires no size computation.
3862       // Otherwise, evaluate and record it.
3863       if (auto Size = VAT->getSizeExpr()) {
3864         if (!CSI->isVLATypeCaptured(VAT)) {
3865           RecordDecl *CapRecord = nullptr;
3866           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3867             CapRecord = LSI->Lambda;
3868           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3869             CapRecord = CRSI->TheRecordDecl;
3870           }
3871           if (CapRecord) {
3872             auto ExprLoc = Size->getExprLoc();
3873             auto SizeType = Context.getSizeType();
3874             // Build the non-static data member.
3875             auto Field =
3876                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3877                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3878                                   /*BW*/ nullptr, /*Mutable*/ false,
3879                                   /*InitStyle*/ ICIS_NoInit);
3880             Field->setImplicit(true);
3881             Field->setAccess(AS_private);
3882             Field->setCapturedVLAType(VAT);
3883             CapRecord->addDecl(Field);
3884 
3885             CSI->addVLATypeCapture(ExprLoc, SizeType);
3886           }
3887         }
3888       }
3889       T = VAT->getElementType();
3890       break;
3891     }
3892     case Type::FunctionProto:
3893     case Type::FunctionNoProto:
3894       T = cast<FunctionType>(Ty)->getReturnType();
3895       break;
3896     case Type::Paren:
3897     case Type::TypeOf:
3898     case Type::UnaryTransform:
3899     case Type::Attributed:
3900     case Type::SubstTemplateTypeParm:
3901     case Type::PackExpansion:
3902       // Keep walking after single level desugaring.
3903       T = T.getSingleStepDesugaredType(Context);
3904       break;
3905     case Type::Typedef:
3906       T = cast<TypedefType>(Ty)->desugar();
3907       break;
3908     case Type::Decltype:
3909       T = cast<DecltypeType>(Ty)->desugar();
3910       break;
3911     case Type::Auto:
3912     case Type::DeducedTemplateSpecialization:
3913       T = cast<DeducedType>(Ty)->getDeducedType();
3914       break;
3915     case Type::TypeOfExpr:
3916       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3917       break;
3918     case Type::Atomic:
3919       T = cast<AtomicType>(Ty)->getValueType();
3920       break;
3921     }
3922   } while (!T.isNull() && T->isVariablyModifiedType());
3923 }
3924 
3925 /// \brief Build a sizeof or alignof expression given a type operand.
3926 ExprResult
3927 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3928                                      SourceLocation OpLoc,
3929                                      UnaryExprOrTypeTrait ExprKind,
3930                                      SourceRange R) {
3931   if (!TInfo)
3932     return ExprError();
3933 
3934   QualType T = TInfo->getType();
3935 
3936   if (!T->isDependentType() &&
3937       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3938     return ExprError();
3939 
3940   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3941     if (auto *TT = T->getAs<TypedefType>()) {
3942       for (auto I = FunctionScopes.rbegin(),
3943                 E = std::prev(FunctionScopes.rend());
3944            I != E; ++I) {
3945         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3946         if (CSI == nullptr)
3947           break;
3948         DeclContext *DC = nullptr;
3949         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3950           DC = LSI->CallOperator;
3951         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3952           DC = CRSI->TheCapturedDecl;
3953         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3954           DC = BSI->TheDecl;
3955         if (DC) {
3956           if (DC->containsDecl(TT->getDecl()))
3957             break;
3958           captureVariablyModifiedType(Context, T, CSI);
3959         }
3960       }
3961     }
3962   }
3963 
3964   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3965   return new (Context) UnaryExprOrTypeTraitExpr(
3966       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3967 }
3968 
3969 /// \brief Build a sizeof or alignof expression given an expression
3970 /// operand.
3971 ExprResult
3972 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3973                                      UnaryExprOrTypeTrait ExprKind) {
3974   ExprResult PE = CheckPlaceholderExpr(E);
3975   if (PE.isInvalid())
3976     return ExprError();
3977 
3978   E = PE.get();
3979 
3980   // Verify that the operand is valid.
3981   bool isInvalid = false;
3982   if (E->isTypeDependent()) {
3983     // Delay type-checking for type-dependent expressions.
3984   } else if (ExprKind == UETT_AlignOf) {
3985     isInvalid = CheckAlignOfExpr(*this, E);
3986   } else if (ExprKind == UETT_VecStep) {
3987     isInvalid = CheckVecStepExpr(E);
3988   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3989       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3990       isInvalid = true;
3991   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3992     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3993     isInvalid = true;
3994   } else {
3995     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3996   }
3997 
3998   if (isInvalid)
3999     return ExprError();
4000 
4001   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4002     PE = TransformToPotentiallyEvaluated(E);
4003     if (PE.isInvalid()) return ExprError();
4004     E = PE.get();
4005   }
4006 
4007   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4008   return new (Context) UnaryExprOrTypeTraitExpr(
4009       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4010 }
4011 
4012 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4013 /// expr and the same for @c alignof and @c __alignof
4014 /// Note that the ArgRange is invalid if isType is false.
4015 ExprResult
4016 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4017                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4018                                     void *TyOrEx, SourceRange ArgRange) {
4019   // If error parsing type, ignore.
4020   if (!TyOrEx) return ExprError();
4021 
4022   if (IsType) {
4023     TypeSourceInfo *TInfo;
4024     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4025     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4026   }
4027 
4028   Expr *ArgEx = (Expr *)TyOrEx;
4029   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4030   return Result;
4031 }
4032 
4033 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4034                                      bool IsReal) {
4035   if (V.get()->isTypeDependent())
4036     return S.Context.DependentTy;
4037 
4038   // _Real and _Imag are only l-values for normal l-values.
4039   if (V.get()->getObjectKind() != OK_Ordinary) {
4040     V = S.DefaultLvalueConversion(V.get());
4041     if (V.isInvalid())
4042       return QualType();
4043   }
4044 
4045   // These operators return the element type of a complex type.
4046   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4047     return CT->getElementType();
4048 
4049   // Otherwise they pass through real integer and floating point types here.
4050   if (V.get()->getType()->isArithmeticType())
4051     return V.get()->getType();
4052 
4053   // Test for placeholders.
4054   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4055   if (PR.isInvalid()) return QualType();
4056   if (PR.get() != V.get()) {
4057     V = PR;
4058     return CheckRealImagOperand(S, V, Loc, IsReal);
4059   }
4060 
4061   // Reject anything else.
4062   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4063     << (IsReal ? "__real" : "__imag");
4064   return QualType();
4065 }
4066 
4067 
4068 
4069 ExprResult
4070 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4071                           tok::TokenKind Kind, Expr *Input) {
4072   UnaryOperatorKind Opc;
4073   switch (Kind) {
4074   default: llvm_unreachable("Unknown unary op!");
4075   case tok::plusplus:   Opc = UO_PostInc; break;
4076   case tok::minusminus: Opc = UO_PostDec; break;
4077   }
4078 
4079   // Since this might is a postfix expression, get rid of ParenListExprs.
4080   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4081   if (Result.isInvalid()) return ExprError();
4082   Input = Result.get();
4083 
4084   return BuildUnaryOp(S, OpLoc, Opc, Input);
4085 }
4086 
4087 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4088 ///
4089 /// \return true on error
4090 static bool checkArithmeticOnObjCPointer(Sema &S,
4091                                          SourceLocation opLoc,
4092                                          Expr *op) {
4093   assert(op->getType()->isObjCObjectPointerType());
4094   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4095       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4096     return false;
4097 
4098   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4099     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4100     << op->getSourceRange();
4101   return true;
4102 }
4103 
4104 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4105   auto *BaseNoParens = Base->IgnoreParens();
4106   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4107     return MSProp->getPropertyDecl()->getType()->isArrayType();
4108   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4109 }
4110 
4111 ExprResult
4112 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4113                               Expr *idx, SourceLocation rbLoc) {
4114   if (base && !base->getType().isNull() &&
4115       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4116     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4117                                     /*Length=*/nullptr, rbLoc);
4118 
4119   // Since this might be a postfix expression, get rid of ParenListExprs.
4120   if (isa<ParenListExpr>(base)) {
4121     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4122     if (result.isInvalid()) return ExprError();
4123     base = result.get();
4124   }
4125 
4126   // Handle any non-overload placeholder types in the base and index
4127   // expressions.  We can't handle overloads here because the other
4128   // operand might be an overloadable type, in which case the overload
4129   // resolution for the operator overload should get the first crack
4130   // at the overload.
4131   bool IsMSPropertySubscript = false;
4132   if (base->getType()->isNonOverloadPlaceholderType()) {
4133     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4134     if (!IsMSPropertySubscript) {
4135       ExprResult result = CheckPlaceholderExpr(base);
4136       if (result.isInvalid())
4137         return ExprError();
4138       base = result.get();
4139     }
4140   }
4141   if (idx->getType()->isNonOverloadPlaceholderType()) {
4142     ExprResult result = CheckPlaceholderExpr(idx);
4143     if (result.isInvalid()) return ExprError();
4144     idx = result.get();
4145   }
4146 
4147   // Build an unanalyzed expression if either operand is type-dependent.
4148   if (getLangOpts().CPlusPlus &&
4149       (base->isTypeDependent() || idx->isTypeDependent())) {
4150     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4151                                             VK_LValue, OK_Ordinary, rbLoc);
4152   }
4153 
4154   // MSDN, property (C++)
4155   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4156   // This attribute can also be used in the declaration of an empty array in a
4157   // class or structure definition. For example:
4158   // __declspec(property(get=GetX, put=PutX)) int x[];
4159   // The above statement indicates that x[] can be used with one or more array
4160   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4161   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4162   if (IsMSPropertySubscript) {
4163     // Build MS property subscript expression if base is MS property reference
4164     // or MS property subscript.
4165     return new (Context) MSPropertySubscriptExpr(
4166         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4167   }
4168 
4169   // Use C++ overloaded-operator rules if either operand has record
4170   // type.  The spec says to do this if either type is *overloadable*,
4171   // but enum types can't declare subscript operators or conversion
4172   // operators, so there's nothing interesting for overload resolution
4173   // to do if there aren't any record types involved.
4174   //
4175   // ObjC pointers have their own subscripting logic that is not tied
4176   // to overload resolution and so should not take this path.
4177   if (getLangOpts().CPlusPlus &&
4178       (base->getType()->isRecordType() ||
4179        (!base->getType()->isObjCObjectPointerType() &&
4180         idx->getType()->isRecordType()))) {
4181     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4182   }
4183 
4184   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4185 }
4186 
4187 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4188                                           Expr *LowerBound,
4189                                           SourceLocation ColonLoc, Expr *Length,
4190                                           SourceLocation RBLoc) {
4191   if (Base->getType()->isPlaceholderType() &&
4192       !Base->getType()->isSpecificPlaceholderType(
4193           BuiltinType::OMPArraySection)) {
4194     ExprResult Result = CheckPlaceholderExpr(Base);
4195     if (Result.isInvalid())
4196       return ExprError();
4197     Base = Result.get();
4198   }
4199   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4200     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4201     if (Result.isInvalid())
4202       return ExprError();
4203     Result = DefaultLvalueConversion(Result.get());
4204     if (Result.isInvalid())
4205       return ExprError();
4206     LowerBound = Result.get();
4207   }
4208   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4209     ExprResult Result = CheckPlaceholderExpr(Length);
4210     if (Result.isInvalid())
4211       return ExprError();
4212     Result = DefaultLvalueConversion(Result.get());
4213     if (Result.isInvalid())
4214       return ExprError();
4215     Length = Result.get();
4216   }
4217 
4218   // Build an unanalyzed expression if either operand is type-dependent.
4219   if (Base->isTypeDependent() ||
4220       (LowerBound &&
4221        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4222       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4223     return new (Context)
4224         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4225                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4226   }
4227 
4228   // Perform default conversions.
4229   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4230   QualType ResultTy;
4231   if (OriginalTy->isAnyPointerType()) {
4232     ResultTy = OriginalTy->getPointeeType();
4233   } else if (OriginalTy->isArrayType()) {
4234     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4235   } else {
4236     return ExprError(
4237         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4238         << Base->getSourceRange());
4239   }
4240   // C99 6.5.2.1p1
4241   if (LowerBound) {
4242     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4243                                                       LowerBound);
4244     if (Res.isInvalid())
4245       return ExprError(Diag(LowerBound->getExprLoc(),
4246                             diag::err_omp_typecheck_section_not_integer)
4247                        << 0 << LowerBound->getSourceRange());
4248     LowerBound = Res.get();
4249 
4250     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4251         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4252       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4253           << 0 << LowerBound->getSourceRange();
4254   }
4255   if (Length) {
4256     auto Res =
4257         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4258     if (Res.isInvalid())
4259       return ExprError(Diag(Length->getExprLoc(),
4260                             diag::err_omp_typecheck_section_not_integer)
4261                        << 1 << Length->getSourceRange());
4262     Length = Res.get();
4263 
4264     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4265         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4266       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4267           << 1 << Length->getSourceRange();
4268   }
4269 
4270   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4271   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4272   // type. Note that functions are not objects, and that (in C99 parlance)
4273   // incomplete types are not object types.
4274   if (ResultTy->isFunctionType()) {
4275     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4276         << ResultTy << Base->getSourceRange();
4277     return ExprError();
4278   }
4279 
4280   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4281                           diag::err_omp_section_incomplete_type, Base))
4282     return ExprError();
4283 
4284   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4285     llvm::APSInt LowerBoundValue;
4286     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4287       // OpenMP 4.5, [2.4 Array Sections]
4288       // The array section must be a subset of the original array.
4289       if (LowerBoundValue.isNegative()) {
4290         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4291             << LowerBound->getSourceRange();
4292         return ExprError();
4293       }
4294     }
4295   }
4296 
4297   if (Length) {
4298     llvm::APSInt LengthValue;
4299     if (Length->EvaluateAsInt(LengthValue, Context)) {
4300       // OpenMP 4.5, [2.4 Array Sections]
4301       // The length must evaluate to non-negative integers.
4302       if (LengthValue.isNegative()) {
4303         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4304             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4305             << Length->getSourceRange();
4306         return ExprError();
4307       }
4308     }
4309   } else if (ColonLoc.isValid() &&
4310              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4311                                       !OriginalTy->isVariableArrayType()))) {
4312     // OpenMP 4.5, [2.4 Array Sections]
4313     // When the size of the array dimension is not known, the length must be
4314     // specified explicitly.
4315     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4316         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4317     return ExprError();
4318   }
4319 
4320   if (!Base->getType()->isSpecificPlaceholderType(
4321           BuiltinType::OMPArraySection)) {
4322     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4323     if (Result.isInvalid())
4324       return ExprError();
4325     Base = Result.get();
4326   }
4327   return new (Context)
4328       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4329                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4330 }
4331 
4332 ExprResult
4333 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4334                                       Expr *Idx, SourceLocation RLoc) {
4335   Expr *LHSExp = Base;
4336   Expr *RHSExp = Idx;
4337 
4338   ExprValueKind VK = VK_LValue;
4339   ExprObjectKind OK = OK_Ordinary;
4340 
4341   // Per C++ core issue 1213, the result is an xvalue if either operand is
4342   // a non-lvalue array, and an lvalue otherwise.
4343   if (getLangOpts().CPlusPlus11 &&
4344       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4345        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4346     VK = VK_XValue;
4347 
4348   // Perform default conversions.
4349   if (!LHSExp->getType()->getAs<VectorType>()) {
4350     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4351     if (Result.isInvalid())
4352       return ExprError();
4353     LHSExp = Result.get();
4354   }
4355   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4356   if (Result.isInvalid())
4357     return ExprError();
4358   RHSExp = Result.get();
4359 
4360   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4361 
4362   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4363   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4364   // in the subscript position. As a result, we need to derive the array base
4365   // and index from the expression types.
4366   Expr *BaseExpr, *IndexExpr;
4367   QualType ResultType;
4368   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4369     BaseExpr = LHSExp;
4370     IndexExpr = RHSExp;
4371     ResultType = Context.DependentTy;
4372   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4373     BaseExpr = LHSExp;
4374     IndexExpr = RHSExp;
4375     ResultType = PTy->getPointeeType();
4376   } else if (const ObjCObjectPointerType *PTy =
4377                LHSTy->getAs<ObjCObjectPointerType>()) {
4378     BaseExpr = LHSExp;
4379     IndexExpr = RHSExp;
4380 
4381     // Use custom logic if this should be the pseudo-object subscript
4382     // expression.
4383     if (!LangOpts.isSubscriptPointerArithmetic())
4384       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4385                                           nullptr);
4386 
4387     ResultType = PTy->getPointeeType();
4388   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4389      // Handle the uncommon case of "123[Ptr]".
4390     BaseExpr = RHSExp;
4391     IndexExpr = LHSExp;
4392     ResultType = PTy->getPointeeType();
4393   } else if (const ObjCObjectPointerType *PTy =
4394                RHSTy->getAs<ObjCObjectPointerType>()) {
4395      // Handle the uncommon case of "123[Ptr]".
4396     BaseExpr = RHSExp;
4397     IndexExpr = LHSExp;
4398     ResultType = PTy->getPointeeType();
4399     if (!LangOpts.isSubscriptPointerArithmetic()) {
4400       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4401         << ResultType << BaseExpr->getSourceRange();
4402       return ExprError();
4403     }
4404   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4405     BaseExpr = LHSExp;    // vectors: V[123]
4406     IndexExpr = RHSExp;
4407     VK = LHSExp->getValueKind();
4408     if (VK != VK_RValue)
4409       OK = OK_VectorComponent;
4410 
4411     ResultType = VTy->getElementType();
4412     QualType BaseType = BaseExpr->getType();
4413     Qualifiers BaseQuals = BaseType.getQualifiers();
4414     Qualifiers MemberQuals = ResultType.getQualifiers();
4415     Qualifiers Combined = BaseQuals + MemberQuals;
4416     if (Combined != MemberQuals)
4417       ResultType = Context.getQualifiedType(ResultType, Combined);
4418   } else if (LHSTy->isArrayType()) {
4419     // If we see an array that wasn't promoted by
4420     // DefaultFunctionArrayLvalueConversion, it must be an array that
4421     // wasn't promoted because of the C90 rule that doesn't
4422     // allow promoting non-lvalue arrays.  Warn, then
4423     // force the promotion here.
4424     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4425         LHSExp->getSourceRange();
4426     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4427                                CK_ArrayToPointerDecay).get();
4428     LHSTy = LHSExp->getType();
4429 
4430     BaseExpr = LHSExp;
4431     IndexExpr = RHSExp;
4432     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4433   } else if (RHSTy->isArrayType()) {
4434     // Same as previous, except for 123[f().a] case
4435     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4436         RHSExp->getSourceRange();
4437     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4438                                CK_ArrayToPointerDecay).get();
4439     RHSTy = RHSExp->getType();
4440 
4441     BaseExpr = RHSExp;
4442     IndexExpr = LHSExp;
4443     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4444   } else {
4445     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4446        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4447   }
4448   // C99 6.5.2.1p1
4449   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4450     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4451                      << IndexExpr->getSourceRange());
4452 
4453   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4454        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4455          && !IndexExpr->isTypeDependent())
4456     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4457 
4458   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4459   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4460   // type. Note that Functions are not objects, and that (in C99 parlance)
4461   // incomplete types are not object types.
4462   if (ResultType->isFunctionType()) {
4463     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4464       << ResultType << BaseExpr->getSourceRange();
4465     return ExprError();
4466   }
4467 
4468   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4469     // GNU extension: subscripting on pointer to void
4470     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4471       << BaseExpr->getSourceRange();
4472 
4473     // C forbids expressions of unqualified void type from being l-values.
4474     // See IsCForbiddenLValueType.
4475     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4476   } else if (!ResultType->isDependentType() &&
4477       RequireCompleteType(LLoc, ResultType,
4478                           diag::err_subscript_incomplete_type, BaseExpr))
4479     return ExprError();
4480 
4481   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4482          !ResultType.isCForbiddenLValueType());
4483 
4484   return new (Context)
4485       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4486 }
4487 
4488 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4489                                   ParmVarDecl *Param) {
4490   if (Param->hasUnparsedDefaultArg()) {
4491     Diag(CallLoc,
4492          diag::err_use_of_default_argument_to_function_declared_later) <<
4493       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4494     Diag(UnparsedDefaultArgLocs[Param],
4495          diag::note_default_argument_declared_here);
4496     return true;
4497   }
4498 
4499   if (Param->hasUninstantiatedDefaultArg()) {
4500     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4501 
4502     EnterExpressionEvaluationContext EvalContext(
4503         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4504 
4505     // Instantiate the expression.
4506     //
4507     // FIXME: Pass in a correct Pattern argument, otherwise
4508     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4509     //
4510     // template<typename T>
4511     // struct A {
4512     //   static int FooImpl();
4513     //
4514     //   template<typename Tp>
4515     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4516     //   // template argument list [[T], [Tp]], should be [[Tp]].
4517     //   friend A<Tp> Foo(int a);
4518     // };
4519     //
4520     // template<typename T>
4521     // A<T> Foo(int a = A<T>::FooImpl());
4522     MultiLevelTemplateArgumentList MutiLevelArgList
4523       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4524 
4525     InstantiatingTemplate Inst(*this, CallLoc, Param,
4526                                MutiLevelArgList.getInnermost());
4527     if (Inst.isInvalid())
4528       return true;
4529     if (Inst.isAlreadyInstantiating()) {
4530       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4531       Param->setInvalidDecl();
4532       return true;
4533     }
4534 
4535     ExprResult Result;
4536     {
4537       // C++ [dcl.fct.default]p5:
4538       //   The names in the [default argument] expression are bound, and
4539       //   the semantic constraints are checked, at the point where the
4540       //   default argument expression appears.
4541       ContextRAII SavedContext(*this, FD);
4542       LocalInstantiationScope Local(*this);
4543       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4544                                 /*DirectInit*/false);
4545     }
4546     if (Result.isInvalid())
4547       return true;
4548 
4549     // Check the expression as an initializer for the parameter.
4550     InitializedEntity Entity
4551       = InitializedEntity::InitializeParameter(Context, Param);
4552     InitializationKind Kind
4553       = InitializationKind::CreateCopy(Param->getLocation(),
4554              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4555     Expr *ResultE = Result.getAs<Expr>();
4556 
4557     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4558     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4559     if (Result.isInvalid())
4560       return true;
4561 
4562     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4563                                  Param->getOuterLocStart());
4564     if (Result.isInvalid())
4565       return true;
4566 
4567     // Remember the instantiated default argument.
4568     Param->setDefaultArg(Result.getAs<Expr>());
4569     if (ASTMutationListener *L = getASTMutationListener()) {
4570       L->DefaultArgumentInstantiated(Param);
4571     }
4572   }
4573 
4574   // If the default argument expression is not set yet, we are building it now.
4575   if (!Param->hasInit()) {
4576     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4577     Param->setInvalidDecl();
4578     return true;
4579   }
4580 
4581   // If the default expression creates temporaries, we need to
4582   // push them to the current stack of expression temporaries so they'll
4583   // be properly destroyed.
4584   // FIXME: We should really be rebuilding the default argument with new
4585   // bound temporaries; see the comment in PR5810.
4586   // We don't need to do that with block decls, though, because
4587   // blocks in default argument expression can never capture anything.
4588   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4589     // Set the "needs cleanups" bit regardless of whether there are
4590     // any explicit objects.
4591     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4592 
4593     // Append all the objects to the cleanup list.  Right now, this
4594     // should always be a no-op, because blocks in default argument
4595     // expressions should never be able to capture anything.
4596     assert(!Init->getNumObjects() &&
4597            "default argument expression has capturing blocks?");
4598   }
4599 
4600   // We already type-checked the argument, so we know it works.
4601   // Just mark all of the declarations in this potentially-evaluated expression
4602   // as being "referenced".
4603   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4604                                    /*SkipLocalVariables=*/true);
4605   return false;
4606 }
4607 
4608 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4609                                         FunctionDecl *FD, ParmVarDecl *Param) {
4610   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4611     return ExprError();
4612   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4613 }
4614 
4615 Sema::VariadicCallType
4616 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4617                           Expr *Fn) {
4618   if (Proto && Proto->isVariadic()) {
4619     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4620       return VariadicConstructor;
4621     else if (Fn && Fn->getType()->isBlockPointerType())
4622       return VariadicBlock;
4623     else if (FDecl) {
4624       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4625         if (Method->isInstance())
4626           return VariadicMethod;
4627     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4628       return VariadicMethod;
4629     return VariadicFunction;
4630   }
4631   return VariadicDoesNotApply;
4632 }
4633 
4634 namespace {
4635 class FunctionCallCCC : public FunctionCallFilterCCC {
4636 public:
4637   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4638                   unsigned NumArgs, MemberExpr *ME)
4639       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4640         FunctionName(FuncName) {}
4641 
4642   bool ValidateCandidate(const TypoCorrection &candidate) override {
4643     if (!candidate.getCorrectionSpecifier() ||
4644         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4645       return false;
4646     }
4647 
4648     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4649   }
4650 
4651 private:
4652   const IdentifierInfo *const FunctionName;
4653 };
4654 }
4655 
4656 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4657                                                FunctionDecl *FDecl,
4658                                                ArrayRef<Expr *> Args) {
4659   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4660   DeclarationName FuncName = FDecl->getDeclName();
4661   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4662 
4663   if (TypoCorrection Corrected = S.CorrectTypo(
4664           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4665           S.getScopeForContext(S.CurContext), nullptr,
4666           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4667                                              Args.size(), ME),
4668           Sema::CTK_ErrorRecovery)) {
4669     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4670       if (Corrected.isOverloaded()) {
4671         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4672         OverloadCandidateSet::iterator Best;
4673         for (NamedDecl *CD : Corrected) {
4674           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4675             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4676                                    OCS);
4677         }
4678         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4679         case OR_Success:
4680           ND = Best->FoundDecl;
4681           Corrected.setCorrectionDecl(ND);
4682           break;
4683         default:
4684           break;
4685         }
4686       }
4687       ND = ND->getUnderlyingDecl();
4688       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4689         return Corrected;
4690     }
4691   }
4692   return TypoCorrection();
4693 }
4694 
4695 /// ConvertArgumentsForCall - Converts the arguments specified in
4696 /// Args/NumArgs to the parameter types of the function FDecl with
4697 /// function prototype Proto. Call is the call expression itself, and
4698 /// Fn is the function expression. For a C++ member function, this
4699 /// routine does not attempt to convert the object argument. Returns
4700 /// true if the call is ill-formed.
4701 bool
4702 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4703                               FunctionDecl *FDecl,
4704                               const FunctionProtoType *Proto,
4705                               ArrayRef<Expr *> Args,
4706                               SourceLocation RParenLoc,
4707                               bool IsExecConfig) {
4708   // Bail out early if calling a builtin with custom typechecking.
4709   if (FDecl)
4710     if (unsigned ID = FDecl->getBuiltinID())
4711       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4712         return false;
4713 
4714   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4715   // assignment, to the types of the corresponding parameter, ...
4716   unsigned NumParams = Proto->getNumParams();
4717   bool Invalid = false;
4718   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4719   unsigned FnKind = Fn->getType()->isBlockPointerType()
4720                        ? 1 /* block */
4721                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4722                                        : 0 /* function */);
4723 
4724   // If too few arguments are available (and we don't have default
4725   // arguments for the remaining parameters), don't make the call.
4726   if (Args.size() < NumParams) {
4727     if (Args.size() < MinArgs) {
4728       TypoCorrection TC;
4729       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4730         unsigned diag_id =
4731             MinArgs == NumParams && !Proto->isVariadic()
4732                 ? diag::err_typecheck_call_too_few_args_suggest
4733                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4734         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4735                                         << static_cast<unsigned>(Args.size())
4736                                         << TC.getCorrectionRange());
4737       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4738         Diag(RParenLoc,
4739              MinArgs == NumParams && !Proto->isVariadic()
4740                  ? diag::err_typecheck_call_too_few_args_one
4741                  : diag::err_typecheck_call_too_few_args_at_least_one)
4742             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4743       else
4744         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4745                             ? diag::err_typecheck_call_too_few_args
4746                             : diag::err_typecheck_call_too_few_args_at_least)
4747             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4748             << Fn->getSourceRange();
4749 
4750       // Emit the location of the prototype.
4751       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4752         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4753           << FDecl;
4754 
4755       return true;
4756     }
4757     Call->setNumArgs(Context, NumParams);
4758   }
4759 
4760   // If too many are passed and not variadic, error on the extras and drop
4761   // them.
4762   if (Args.size() > NumParams) {
4763     if (!Proto->isVariadic()) {
4764       TypoCorrection TC;
4765       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4766         unsigned diag_id =
4767             MinArgs == NumParams && !Proto->isVariadic()
4768                 ? diag::err_typecheck_call_too_many_args_suggest
4769                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4770         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4771                                         << static_cast<unsigned>(Args.size())
4772                                         << TC.getCorrectionRange());
4773       } else if (NumParams == 1 && FDecl &&
4774                  FDecl->getParamDecl(0)->getDeclName())
4775         Diag(Args[NumParams]->getLocStart(),
4776              MinArgs == NumParams
4777                  ? diag::err_typecheck_call_too_many_args_one
4778                  : diag::err_typecheck_call_too_many_args_at_most_one)
4779             << FnKind << FDecl->getParamDecl(0)
4780             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4781             << SourceRange(Args[NumParams]->getLocStart(),
4782                            Args.back()->getLocEnd());
4783       else
4784         Diag(Args[NumParams]->getLocStart(),
4785              MinArgs == NumParams
4786                  ? diag::err_typecheck_call_too_many_args
4787                  : diag::err_typecheck_call_too_many_args_at_most)
4788             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4789             << Fn->getSourceRange()
4790             << SourceRange(Args[NumParams]->getLocStart(),
4791                            Args.back()->getLocEnd());
4792 
4793       // Emit the location of the prototype.
4794       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4795         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4796           << FDecl;
4797 
4798       // This deletes the extra arguments.
4799       Call->setNumArgs(Context, NumParams);
4800       return true;
4801     }
4802   }
4803   SmallVector<Expr *, 8> AllArgs;
4804   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4805 
4806   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4807                                    Proto, 0, Args, AllArgs, CallType);
4808   if (Invalid)
4809     return true;
4810   unsigned TotalNumArgs = AllArgs.size();
4811   for (unsigned i = 0; i < TotalNumArgs; ++i)
4812     Call->setArg(i, AllArgs[i]);
4813 
4814   return false;
4815 }
4816 
4817 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4818                                   const FunctionProtoType *Proto,
4819                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4820                                   SmallVectorImpl<Expr *> &AllArgs,
4821                                   VariadicCallType CallType, bool AllowExplicit,
4822                                   bool IsListInitialization) {
4823   unsigned NumParams = Proto->getNumParams();
4824   bool Invalid = false;
4825   size_t ArgIx = 0;
4826   // Continue to check argument types (even if we have too few/many args).
4827   for (unsigned i = FirstParam; i < NumParams; i++) {
4828     QualType ProtoArgType = Proto->getParamType(i);
4829 
4830     Expr *Arg;
4831     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4832     if (ArgIx < Args.size()) {
4833       Arg = Args[ArgIx++];
4834 
4835       if (RequireCompleteType(Arg->getLocStart(),
4836                               ProtoArgType,
4837                               diag::err_call_incomplete_argument, Arg))
4838         return true;
4839 
4840       // Strip the unbridged-cast placeholder expression off, if applicable.
4841       bool CFAudited = false;
4842       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4843           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4844           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4845         Arg = stripARCUnbridgedCast(Arg);
4846       else if (getLangOpts().ObjCAutoRefCount &&
4847                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4848                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4849         CFAudited = true;
4850 
4851       if (Proto->getExtParameterInfo(i).isNoEscape())
4852         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4853           BE->getBlockDecl()->setDoesNotEscape();
4854 
4855       InitializedEntity Entity =
4856           Param ? InitializedEntity::InitializeParameter(Context, Param,
4857                                                          ProtoArgType)
4858                 : InitializedEntity::InitializeParameter(
4859                       Context, ProtoArgType, Proto->isParamConsumed(i));
4860 
4861       // Remember that parameter belongs to a CF audited API.
4862       if (CFAudited)
4863         Entity.setParameterCFAudited();
4864 
4865       ExprResult ArgE = PerformCopyInitialization(
4866           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4867       if (ArgE.isInvalid())
4868         return true;
4869 
4870       Arg = ArgE.getAs<Expr>();
4871     } else {
4872       assert(Param && "can't use default arguments without a known callee");
4873 
4874       ExprResult ArgExpr =
4875         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4876       if (ArgExpr.isInvalid())
4877         return true;
4878 
4879       Arg = ArgExpr.getAs<Expr>();
4880     }
4881 
4882     // Check for array bounds violations for each argument to the call. This
4883     // check only triggers warnings when the argument isn't a more complex Expr
4884     // with its own checking, such as a BinaryOperator.
4885     CheckArrayAccess(Arg);
4886 
4887     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4888     CheckStaticArrayArgument(CallLoc, Param, Arg);
4889 
4890     AllArgs.push_back(Arg);
4891   }
4892 
4893   // If this is a variadic call, handle args passed through "...".
4894   if (CallType != VariadicDoesNotApply) {
4895     // Assume that extern "C" functions with variadic arguments that
4896     // return __unknown_anytype aren't *really* variadic.
4897     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4898         FDecl->isExternC()) {
4899       for (Expr *A : Args.slice(ArgIx)) {
4900         QualType paramType; // ignored
4901         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4902         Invalid |= arg.isInvalid();
4903         AllArgs.push_back(arg.get());
4904       }
4905 
4906     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4907     } else {
4908       for (Expr *A : Args.slice(ArgIx)) {
4909         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4910         Invalid |= Arg.isInvalid();
4911         AllArgs.push_back(Arg.get());
4912       }
4913     }
4914 
4915     // Check for array bounds violations.
4916     for (Expr *A : Args.slice(ArgIx))
4917       CheckArrayAccess(A);
4918   }
4919   return Invalid;
4920 }
4921 
4922 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4923   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4924   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4925     TL = DTL.getOriginalLoc();
4926   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4927     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4928       << ATL.getLocalSourceRange();
4929 }
4930 
4931 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4932 /// array parameter, check that it is non-null, and that if it is formed by
4933 /// array-to-pointer decay, the underlying array is sufficiently large.
4934 ///
4935 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4936 /// array type derivation, then for each call to the function, the value of the
4937 /// corresponding actual argument shall provide access to the first element of
4938 /// an array with at least as many elements as specified by the size expression.
4939 void
4940 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4941                                ParmVarDecl *Param,
4942                                const Expr *ArgExpr) {
4943   // Static array parameters are not supported in C++.
4944   if (!Param || getLangOpts().CPlusPlus)
4945     return;
4946 
4947   QualType OrigTy = Param->getOriginalType();
4948 
4949   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4950   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4951     return;
4952 
4953   if (ArgExpr->isNullPointerConstant(Context,
4954                                      Expr::NPC_NeverValueDependent)) {
4955     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4956     DiagnoseCalleeStaticArrayParam(*this, Param);
4957     return;
4958   }
4959 
4960   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4961   if (!CAT)
4962     return;
4963 
4964   const ConstantArrayType *ArgCAT =
4965     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4966   if (!ArgCAT)
4967     return;
4968 
4969   if (ArgCAT->getSize().ult(CAT->getSize())) {
4970     Diag(CallLoc, diag::warn_static_array_too_small)
4971       << ArgExpr->getSourceRange()
4972       << (unsigned) ArgCAT->getSize().getZExtValue()
4973       << (unsigned) CAT->getSize().getZExtValue();
4974     DiagnoseCalleeStaticArrayParam(*this, Param);
4975   }
4976 }
4977 
4978 /// Given a function expression of unknown-any type, try to rebuild it
4979 /// to have a function type.
4980 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4981 
4982 /// Is the given type a placeholder that we need to lower out
4983 /// immediately during argument processing?
4984 static bool isPlaceholderToRemoveAsArg(QualType type) {
4985   // Placeholders are never sugared.
4986   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4987   if (!placeholder) return false;
4988 
4989   switch (placeholder->getKind()) {
4990   // Ignore all the non-placeholder types.
4991 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4992   case BuiltinType::Id:
4993 #include "clang/Basic/OpenCLImageTypes.def"
4994 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4995 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4996 #include "clang/AST/BuiltinTypes.def"
4997     return false;
4998 
4999   // We cannot lower out overload sets; they might validly be resolved
5000   // by the call machinery.
5001   case BuiltinType::Overload:
5002     return false;
5003 
5004   // Unbridged casts in ARC can be handled in some call positions and
5005   // should be left in place.
5006   case BuiltinType::ARCUnbridgedCast:
5007     return false;
5008 
5009   // Pseudo-objects should be converted as soon as possible.
5010   case BuiltinType::PseudoObject:
5011     return true;
5012 
5013   // The debugger mode could theoretically but currently does not try
5014   // to resolve unknown-typed arguments based on known parameter types.
5015   case BuiltinType::UnknownAny:
5016     return true;
5017 
5018   // These are always invalid as call arguments and should be reported.
5019   case BuiltinType::BoundMember:
5020   case BuiltinType::BuiltinFn:
5021   case BuiltinType::OMPArraySection:
5022     return true;
5023 
5024   }
5025   llvm_unreachable("bad builtin type kind");
5026 }
5027 
5028 /// Check an argument list for placeholders that we won't try to
5029 /// handle later.
5030 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5031   // Apply this processing to all the arguments at once instead of
5032   // dying at the first failure.
5033   bool hasInvalid = false;
5034   for (size_t i = 0, e = args.size(); i != e; i++) {
5035     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5036       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5037       if (result.isInvalid()) hasInvalid = true;
5038       else args[i] = result.get();
5039     } else if (hasInvalid) {
5040       (void)S.CorrectDelayedTyposInExpr(args[i]);
5041     }
5042   }
5043   return hasInvalid;
5044 }
5045 
5046 /// If a builtin function has a pointer argument with no explicit address
5047 /// space, then it should be able to accept a pointer to any address
5048 /// space as input.  In order to do this, we need to replace the
5049 /// standard builtin declaration with one that uses the same address space
5050 /// as the call.
5051 ///
5052 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5053 ///                  it does not contain any pointer arguments without
5054 ///                  an address space qualifer.  Otherwise the rewritten
5055 ///                  FunctionDecl is returned.
5056 /// TODO: Handle pointer return types.
5057 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5058                                                 const FunctionDecl *FDecl,
5059                                                 MultiExprArg ArgExprs) {
5060 
5061   QualType DeclType = FDecl->getType();
5062   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5063 
5064   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5065       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5066     return nullptr;
5067 
5068   bool NeedsNewDecl = false;
5069   unsigned i = 0;
5070   SmallVector<QualType, 8> OverloadParams;
5071 
5072   for (QualType ParamType : FT->param_types()) {
5073 
5074     // Convert array arguments to pointer to simplify type lookup.
5075     ExprResult ArgRes =
5076         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5077     if (ArgRes.isInvalid())
5078       return nullptr;
5079     Expr *Arg = ArgRes.get();
5080     QualType ArgType = Arg->getType();
5081     if (!ParamType->isPointerType() ||
5082         ParamType.getQualifiers().hasAddressSpace() ||
5083         !ArgType->isPointerType() ||
5084         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5085       OverloadParams.push_back(ParamType);
5086       continue;
5087     }
5088 
5089     NeedsNewDecl = true;
5090     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5091 
5092     QualType PointeeType = ParamType->getPointeeType();
5093     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5094     OverloadParams.push_back(Context.getPointerType(PointeeType));
5095   }
5096 
5097   if (!NeedsNewDecl)
5098     return nullptr;
5099 
5100   FunctionProtoType::ExtProtoInfo EPI;
5101   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5102                                                 OverloadParams, EPI);
5103   DeclContext *Parent = Context.getTranslationUnitDecl();
5104   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5105                                                     FDecl->getLocation(),
5106                                                     FDecl->getLocation(),
5107                                                     FDecl->getIdentifier(),
5108                                                     OverloadTy,
5109                                                     /*TInfo=*/nullptr,
5110                                                     SC_Extern, false,
5111                                                     /*hasPrototype=*/true);
5112   SmallVector<ParmVarDecl*, 16> Params;
5113   FT = cast<FunctionProtoType>(OverloadTy);
5114   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5115     QualType ParamType = FT->getParamType(i);
5116     ParmVarDecl *Parm =
5117         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5118                                 SourceLocation(), nullptr, ParamType,
5119                                 /*TInfo=*/nullptr, SC_None, nullptr);
5120     Parm->setScopeInfo(0, i);
5121     Params.push_back(Parm);
5122   }
5123   OverloadDecl->setParams(Params);
5124   return OverloadDecl;
5125 }
5126 
5127 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5128                                     FunctionDecl *Callee,
5129                                     MultiExprArg ArgExprs) {
5130   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5131   // similar attributes) really don't like it when functions are called with an
5132   // invalid number of args.
5133   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5134                          /*PartialOverloading=*/false) &&
5135       !Callee->isVariadic())
5136     return;
5137   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5138     return;
5139 
5140   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5141     S.Diag(Fn->getLocStart(),
5142            isa<CXXMethodDecl>(Callee)
5143                ? diag::err_ovl_no_viable_member_function_in_call
5144                : diag::err_ovl_no_viable_function_in_call)
5145         << Callee << Callee->getSourceRange();
5146     S.Diag(Callee->getLocation(),
5147            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5148         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5149     return;
5150   }
5151 }
5152 
5153 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5154     const UnresolvedMemberExpr *const UME, Sema &S) {
5155 
5156   const auto GetFunctionLevelDCIfCXXClass =
5157       [](Sema &S) -> const CXXRecordDecl * {
5158     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5159     if (!DC || !DC->getParent())
5160       return nullptr;
5161 
5162     // If the call to some member function was made from within a member
5163     // function body 'M' return return 'M's parent.
5164     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5165       return MD->getParent()->getCanonicalDecl();
5166     // else the call was made from within a default member initializer of a
5167     // class, so return the class.
5168     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5169       return RD->getCanonicalDecl();
5170     return nullptr;
5171   };
5172   // If our DeclContext is neither a member function nor a class (in the
5173   // case of a lambda in a default member initializer), we can't have an
5174   // enclosing 'this'.
5175 
5176   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5177   if (!CurParentClass)
5178     return false;
5179 
5180   // The naming class for implicit member functions call is the class in which
5181   // name lookup starts.
5182   const CXXRecordDecl *const NamingClass =
5183       UME->getNamingClass()->getCanonicalDecl();
5184   assert(NamingClass && "Must have naming class even for implicit access");
5185 
5186   // If the unresolved member functions were found in a 'naming class' that is
5187   // related (either the same or derived from) to the class that contains the
5188   // member function that itself contained the implicit member access.
5189 
5190   return CurParentClass == NamingClass ||
5191          CurParentClass->isDerivedFrom(NamingClass);
5192 }
5193 
5194 static void
5195 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5196     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5197 
5198   if (!UME)
5199     return;
5200 
5201   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5202   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5203   // already been captured, or if this is an implicit member function call (if
5204   // it isn't, an attempt to capture 'this' should already have been made).
5205   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5206       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5207     return;
5208 
5209   // Check if the naming class in which the unresolved members were found is
5210   // related (same as or is a base of) to the enclosing class.
5211 
5212   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5213     return;
5214 
5215 
5216   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5217   // If the enclosing function is not dependent, then this lambda is
5218   // capture ready, so if we can capture this, do so.
5219   if (!EnclosingFunctionCtx->isDependentContext()) {
5220     // If the current lambda and all enclosing lambdas can capture 'this' -
5221     // then go ahead and capture 'this' (since our unresolved overload set
5222     // contains at least one non-static member function).
5223     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5224       S.CheckCXXThisCapture(CallLoc);
5225   } else if (S.CurContext->isDependentContext()) {
5226     // ... since this is an implicit member reference, that might potentially
5227     // involve a 'this' capture, mark 'this' for potential capture in
5228     // enclosing lambdas.
5229     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5230       CurLSI->addPotentialThisCapture(CallLoc);
5231   }
5232 }
5233 
5234 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5235 /// This provides the location of the left/right parens and a list of comma
5236 /// locations.
5237 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5238                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5239                                Expr *ExecConfig, bool IsExecConfig) {
5240   // Since this might be a postfix expression, get rid of ParenListExprs.
5241   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5242   if (Result.isInvalid()) return ExprError();
5243   Fn = Result.get();
5244 
5245   if (checkArgsForPlaceholders(*this, ArgExprs))
5246     return ExprError();
5247 
5248   if (getLangOpts().CPlusPlus) {
5249     // If this is a pseudo-destructor expression, build the call immediately.
5250     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5251       if (!ArgExprs.empty()) {
5252         // Pseudo-destructor calls should not have any arguments.
5253         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5254             << FixItHint::CreateRemoval(
5255                    SourceRange(ArgExprs.front()->getLocStart(),
5256                                ArgExprs.back()->getLocEnd()));
5257       }
5258 
5259       return new (Context)
5260           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5261     }
5262     if (Fn->getType() == Context.PseudoObjectTy) {
5263       ExprResult result = CheckPlaceholderExpr(Fn);
5264       if (result.isInvalid()) return ExprError();
5265       Fn = result.get();
5266     }
5267 
5268     // Determine whether this is a dependent call inside a C++ template,
5269     // in which case we won't do any semantic analysis now.
5270     bool Dependent = false;
5271     if (Fn->isTypeDependent())
5272       Dependent = true;
5273     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5274       Dependent = true;
5275 
5276     if (Dependent) {
5277       if (ExecConfig) {
5278         return new (Context) CUDAKernelCallExpr(
5279             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5280             Context.DependentTy, VK_RValue, RParenLoc);
5281       } else {
5282 
5283        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5284             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5285             Fn->getLocStart());
5286 
5287         return new (Context) CallExpr(
5288             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5289       }
5290     }
5291 
5292     // Determine whether this is a call to an object (C++ [over.call.object]).
5293     if (Fn->getType()->isRecordType())
5294       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5295                                           RParenLoc);
5296 
5297     if (Fn->getType() == Context.UnknownAnyTy) {
5298       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5299       if (result.isInvalid()) return ExprError();
5300       Fn = result.get();
5301     }
5302 
5303     if (Fn->getType() == Context.BoundMemberTy) {
5304       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5305                                        RParenLoc);
5306     }
5307   }
5308 
5309   // Check for overloaded calls.  This can happen even in C due to extensions.
5310   if (Fn->getType() == Context.OverloadTy) {
5311     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5312 
5313     // We aren't supposed to apply this logic if there's an '&' involved.
5314     if (!find.HasFormOfMemberPointer) {
5315       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5316         return new (Context) CallExpr(
5317             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5318       OverloadExpr *ovl = find.Expression;
5319       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5320         return BuildOverloadedCallExpr(
5321             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5322             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5323       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5324                                        RParenLoc);
5325     }
5326   }
5327 
5328   // If we're directly calling a function, get the appropriate declaration.
5329   if (Fn->getType() == Context.UnknownAnyTy) {
5330     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5331     if (result.isInvalid()) return ExprError();
5332     Fn = result.get();
5333   }
5334 
5335   Expr *NakedFn = Fn->IgnoreParens();
5336 
5337   bool CallingNDeclIndirectly = false;
5338   NamedDecl *NDecl = nullptr;
5339   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5340     if (UnOp->getOpcode() == UO_AddrOf) {
5341       CallingNDeclIndirectly = true;
5342       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5343     }
5344   }
5345 
5346   if (isa<DeclRefExpr>(NakedFn)) {
5347     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5348 
5349     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5350     if (FDecl && FDecl->getBuiltinID()) {
5351       // Rewrite the function decl for this builtin by replacing parameters
5352       // with no explicit address space with the address space of the arguments
5353       // in ArgExprs.
5354       if ((FDecl =
5355                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5356         NDecl = FDecl;
5357         Fn = DeclRefExpr::Create(
5358             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5359             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5360       }
5361     }
5362   } else if (isa<MemberExpr>(NakedFn))
5363     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5364 
5365   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5366     if (CallingNDeclIndirectly &&
5367         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5368                                            Fn->getLocStart()))
5369       return ExprError();
5370 
5371     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5372       return ExprError();
5373 
5374     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5375   }
5376 
5377   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5378                                ExecConfig, IsExecConfig);
5379 }
5380 
5381 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5382 ///
5383 /// __builtin_astype( value, dst type )
5384 ///
5385 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5386                                  SourceLocation BuiltinLoc,
5387                                  SourceLocation RParenLoc) {
5388   ExprValueKind VK = VK_RValue;
5389   ExprObjectKind OK = OK_Ordinary;
5390   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5391   QualType SrcTy = E->getType();
5392   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5393     return ExprError(Diag(BuiltinLoc,
5394                           diag::err_invalid_astype_of_different_size)
5395                      << DstTy
5396                      << SrcTy
5397                      << E->getSourceRange());
5398   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5399 }
5400 
5401 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5402 /// provided arguments.
5403 ///
5404 /// __builtin_convertvector( value, dst type )
5405 ///
5406 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5407                                         SourceLocation BuiltinLoc,
5408                                         SourceLocation RParenLoc) {
5409   TypeSourceInfo *TInfo;
5410   GetTypeFromParser(ParsedDestTy, &TInfo);
5411   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5412 }
5413 
5414 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5415 /// i.e. an expression not of \p OverloadTy.  The expression should
5416 /// unary-convert to an expression of function-pointer or
5417 /// block-pointer type.
5418 ///
5419 /// \param NDecl the declaration being called, if available
5420 ExprResult
5421 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5422                             SourceLocation LParenLoc,
5423                             ArrayRef<Expr *> Args,
5424                             SourceLocation RParenLoc,
5425                             Expr *Config, bool IsExecConfig) {
5426   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5427   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5428 
5429   // Functions with 'interrupt' attribute cannot be called directly.
5430   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5431     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5432     return ExprError();
5433   }
5434 
5435   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5436   // so there's some risk when calling out to non-interrupt handler functions
5437   // that the callee might not preserve them. This is easy to diagnose here,
5438   // but can be very challenging to debug.
5439   if (auto *Caller = getCurFunctionDecl())
5440     if (Caller->hasAttr<ARMInterruptAttr>()) {
5441       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5442       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5443         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5444     }
5445 
5446   // Promote the function operand.
5447   // We special-case function promotion here because we only allow promoting
5448   // builtin functions to function pointers in the callee of a call.
5449   ExprResult Result;
5450   if (BuiltinID &&
5451       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5452     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5453                                CK_BuiltinFnToFnPtr).get();
5454   } else {
5455     Result = CallExprUnaryConversions(Fn);
5456   }
5457   if (Result.isInvalid())
5458     return ExprError();
5459   Fn = Result.get();
5460 
5461   // Make the call expr early, before semantic checks.  This guarantees cleanup
5462   // of arguments and function on error.
5463   CallExpr *TheCall;
5464   if (Config)
5465     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5466                                                cast<CallExpr>(Config), Args,
5467                                                Context.BoolTy, VK_RValue,
5468                                                RParenLoc);
5469   else
5470     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5471                                      VK_RValue, RParenLoc);
5472 
5473   if (!getLangOpts().CPlusPlus) {
5474     // C cannot always handle TypoExpr nodes in builtin calls and direct
5475     // function calls as their argument checking don't necessarily handle
5476     // dependent types properly, so make sure any TypoExprs have been
5477     // dealt with.
5478     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5479     if (!Result.isUsable()) return ExprError();
5480     TheCall = dyn_cast<CallExpr>(Result.get());
5481     if (!TheCall) return Result;
5482     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5483   }
5484 
5485   // Bail out early if calling a builtin with custom typechecking.
5486   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5487     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5488 
5489  retry:
5490   const FunctionType *FuncT;
5491   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5492     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5493     // have type pointer to function".
5494     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5495     if (!FuncT)
5496       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5497                          << Fn->getType() << Fn->getSourceRange());
5498   } else if (const BlockPointerType *BPT =
5499                Fn->getType()->getAs<BlockPointerType>()) {
5500     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5501   } else {
5502     // Handle calls to expressions of unknown-any type.
5503     if (Fn->getType() == Context.UnknownAnyTy) {
5504       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5505       if (rewrite.isInvalid()) return ExprError();
5506       Fn = rewrite.get();
5507       TheCall->setCallee(Fn);
5508       goto retry;
5509     }
5510 
5511     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5512       << Fn->getType() << Fn->getSourceRange());
5513   }
5514 
5515   if (getLangOpts().CUDA) {
5516     if (Config) {
5517       // CUDA: Kernel calls must be to global functions
5518       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5519         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5520             << FDecl << Fn->getSourceRange());
5521 
5522       // CUDA: Kernel function must have 'void' return type
5523       if (!FuncT->getReturnType()->isVoidType())
5524         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5525             << Fn->getType() << Fn->getSourceRange());
5526     } else {
5527       // CUDA: Calls to global functions must be configured
5528       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5529         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5530             << FDecl << Fn->getSourceRange());
5531     }
5532   }
5533 
5534   // Check for a valid return type
5535   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5536                           FDecl))
5537     return ExprError();
5538 
5539   // We know the result type of the call, set it.
5540   TheCall->setType(FuncT->getCallResultType(Context));
5541   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5542 
5543   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5544   if (Proto) {
5545     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5546                                 IsExecConfig))
5547       return ExprError();
5548   } else {
5549     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5550 
5551     if (FDecl) {
5552       // Check if we have too few/too many template arguments, based
5553       // on our knowledge of the function definition.
5554       const FunctionDecl *Def = nullptr;
5555       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5556         Proto = Def->getType()->getAs<FunctionProtoType>();
5557        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5558           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5559           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5560       }
5561 
5562       // If the function we're calling isn't a function prototype, but we have
5563       // a function prototype from a prior declaratiom, use that prototype.
5564       if (!FDecl->hasPrototype())
5565         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5566     }
5567 
5568     // Promote the arguments (C99 6.5.2.2p6).
5569     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5570       Expr *Arg = Args[i];
5571 
5572       if (Proto && i < Proto->getNumParams()) {
5573         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5574             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5575         ExprResult ArgE =
5576             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5577         if (ArgE.isInvalid())
5578           return true;
5579 
5580         Arg = ArgE.getAs<Expr>();
5581 
5582       } else {
5583         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5584 
5585         if (ArgE.isInvalid())
5586           return true;
5587 
5588         Arg = ArgE.getAs<Expr>();
5589       }
5590 
5591       if (RequireCompleteType(Arg->getLocStart(),
5592                               Arg->getType(),
5593                               diag::err_call_incomplete_argument, Arg))
5594         return ExprError();
5595 
5596       TheCall->setArg(i, Arg);
5597     }
5598   }
5599 
5600   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5601     if (!Method->isStatic())
5602       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5603         << Fn->getSourceRange());
5604 
5605   // Check for sentinels
5606   if (NDecl)
5607     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5608 
5609   // Do special checking on direct calls to functions.
5610   if (FDecl) {
5611     if (CheckFunctionCall(FDecl, TheCall, Proto))
5612       return ExprError();
5613 
5614     if (BuiltinID)
5615       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5616   } else if (NDecl) {
5617     if (CheckPointerCall(NDecl, TheCall, Proto))
5618       return ExprError();
5619   } else {
5620     if (CheckOtherCall(TheCall, Proto))
5621       return ExprError();
5622   }
5623 
5624   return MaybeBindToTemporary(TheCall);
5625 }
5626 
5627 ExprResult
5628 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5629                            SourceLocation RParenLoc, Expr *InitExpr) {
5630   assert(Ty && "ActOnCompoundLiteral(): missing type");
5631   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5632 
5633   TypeSourceInfo *TInfo;
5634   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5635   if (!TInfo)
5636     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5637 
5638   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5639 }
5640 
5641 ExprResult
5642 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5643                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5644   QualType literalType = TInfo->getType();
5645 
5646   if (literalType->isArrayType()) {
5647     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5648           diag::err_illegal_decl_array_incomplete_type,
5649           SourceRange(LParenLoc,
5650                       LiteralExpr->getSourceRange().getEnd())))
5651       return ExprError();
5652     if (literalType->isVariableArrayType())
5653       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5654         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5655   } else if (!literalType->isDependentType() &&
5656              RequireCompleteType(LParenLoc, literalType,
5657                diag::err_typecheck_decl_incomplete_type,
5658                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5659     return ExprError();
5660 
5661   InitializedEntity Entity
5662     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5663   InitializationKind Kind
5664     = InitializationKind::CreateCStyleCast(LParenLoc,
5665                                            SourceRange(LParenLoc, RParenLoc),
5666                                            /*InitList=*/true);
5667   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5668   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5669                                       &literalType);
5670   if (Result.isInvalid())
5671     return ExprError();
5672   LiteralExpr = Result.get();
5673 
5674   bool isFileScope = !CurContext->isFunctionOrMethod();
5675   if (isFileScope &&
5676       !LiteralExpr->isTypeDependent() &&
5677       !LiteralExpr->isValueDependent() &&
5678       !literalType->isDependentType()) { // 6.5.2.5p3
5679     if (CheckForConstantInitializer(LiteralExpr, literalType))
5680       return ExprError();
5681   }
5682 
5683   // In C, compound literals are l-values for some reason.
5684   // For GCC compatibility, in C++, file-scope array compound literals with
5685   // constant initializers are also l-values, and compound literals are
5686   // otherwise prvalues.
5687   //
5688   // (GCC also treats C++ list-initialized file-scope array prvalues with
5689   // constant initializers as l-values, but that's non-conforming, so we don't
5690   // follow it there.)
5691   //
5692   // FIXME: It would be better to handle the lvalue cases as materializing and
5693   // lifetime-extending a temporary object, but our materialized temporaries
5694   // representation only supports lifetime extension from a variable, not "out
5695   // of thin air".
5696   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5697   // is bound to the result of applying array-to-pointer decay to the compound
5698   // literal.
5699   // FIXME: GCC supports compound literals of reference type, which should
5700   // obviously have a value kind derived from the kind of reference involved.
5701   ExprValueKind VK =
5702       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5703           ? VK_RValue
5704           : VK_LValue;
5705 
5706   return MaybeBindToTemporary(
5707       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5708                                         VK, LiteralExpr, isFileScope));
5709 }
5710 
5711 ExprResult
5712 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5713                     SourceLocation RBraceLoc) {
5714   // Immediately handle non-overload placeholders.  Overloads can be
5715   // resolved contextually, but everything else here can't.
5716   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5717     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5718       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5719 
5720       // Ignore failures; dropping the entire initializer list because
5721       // of one failure would be terrible for indexing/etc.
5722       if (result.isInvalid()) continue;
5723 
5724       InitArgList[I] = result.get();
5725     }
5726   }
5727 
5728   // Semantic analysis for initializers is done by ActOnDeclarator() and
5729   // CheckInitializer() - it requires knowledge of the object being initialized.
5730 
5731   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5732                                                RBraceLoc);
5733   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5734   return E;
5735 }
5736 
5737 /// Do an explicit extend of the given block pointer if we're in ARC.
5738 void Sema::maybeExtendBlockObject(ExprResult &E) {
5739   assert(E.get()->getType()->isBlockPointerType());
5740   assert(E.get()->isRValue());
5741 
5742   // Only do this in an r-value context.
5743   if (!getLangOpts().ObjCAutoRefCount) return;
5744 
5745   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5746                                CK_ARCExtendBlockObject, E.get(),
5747                                /*base path*/ nullptr, VK_RValue);
5748   Cleanup.setExprNeedsCleanups(true);
5749 }
5750 
5751 /// Prepare a conversion of the given expression to an ObjC object
5752 /// pointer type.
5753 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5754   QualType type = E.get()->getType();
5755   if (type->isObjCObjectPointerType()) {
5756     return CK_BitCast;
5757   } else if (type->isBlockPointerType()) {
5758     maybeExtendBlockObject(E);
5759     return CK_BlockPointerToObjCPointerCast;
5760   } else {
5761     assert(type->isPointerType());
5762     return CK_CPointerToObjCPointerCast;
5763   }
5764 }
5765 
5766 /// Prepares for a scalar cast, performing all the necessary stages
5767 /// except the final cast and returning the kind required.
5768 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5769   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5770   // Also, callers should have filtered out the invalid cases with
5771   // pointers.  Everything else should be possible.
5772 
5773   QualType SrcTy = Src.get()->getType();
5774   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5775     return CK_NoOp;
5776 
5777   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5778   case Type::STK_MemberPointer:
5779     llvm_unreachable("member pointer type in C");
5780 
5781   case Type::STK_CPointer:
5782   case Type::STK_BlockPointer:
5783   case Type::STK_ObjCObjectPointer:
5784     switch (DestTy->getScalarTypeKind()) {
5785     case Type::STK_CPointer: {
5786       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5787       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5788       if (SrcAS != DestAS)
5789         return CK_AddressSpaceConversion;
5790       return CK_BitCast;
5791     }
5792     case Type::STK_BlockPointer:
5793       return (SrcKind == Type::STK_BlockPointer
5794                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5795     case Type::STK_ObjCObjectPointer:
5796       if (SrcKind == Type::STK_ObjCObjectPointer)
5797         return CK_BitCast;
5798       if (SrcKind == Type::STK_CPointer)
5799         return CK_CPointerToObjCPointerCast;
5800       maybeExtendBlockObject(Src);
5801       return CK_BlockPointerToObjCPointerCast;
5802     case Type::STK_Bool:
5803       return CK_PointerToBoolean;
5804     case Type::STK_Integral:
5805       return CK_PointerToIntegral;
5806     case Type::STK_Floating:
5807     case Type::STK_FloatingComplex:
5808     case Type::STK_IntegralComplex:
5809     case Type::STK_MemberPointer:
5810       llvm_unreachable("illegal cast from pointer");
5811     }
5812     llvm_unreachable("Should have returned before this");
5813 
5814   case Type::STK_Bool: // casting from bool is like casting from an integer
5815   case Type::STK_Integral:
5816     switch (DestTy->getScalarTypeKind()) {
5817     case Type::STK_CPointer:
5818     case Type::STK_ObjCObjectPointer:
5819     case Type::STK_BlockPointer:
5820       if (Src.get()->isNullPointerConstant(Context,
5821                                            Expr::NPC_ValueDependentIsNull))
5822         return CK_NullToPointer;
5823       return CK_IntegralToPointer;
5824     case Type::STK_Bool:
5825       return CK_IntegralToBoolean;
5826     case Type::STK_Integral:
5827       return CK_IntegralCast;
5828     case Type::STK_Floating:
5829       return CK_IntegralToFloating;
5830     case Type::STK_IntegralComplex:
5831       Src = ImpCastExprToType(Src.get(),
5832                       DestTy->castAs<ComplexType>()->getElementType(),
5833                       CK_IntegralCast);
5834       return CK_IntegralRealToComplex;
5835     case Type::STK_FloatingComplex:
5836       Src = ImpCastExprToType(Src.get(),
5837                       DestTy->castAs<ComplexType>()->getElementType(),
5838                       CK_IntegralToFloating);
5839       return CK_FloatingRealToComplex;
5840     case Type::STK_MemberPointer:
5841       llvm_unreachable("member pointer type in C");
5842     }
5843     llvm_unreachable("Should have returned before this");
5844 
5845   case Type::STK_Floating:
5846     switch (DestTy->getScalarTypeKind()) {
5847     case Type::STK_Floating:
5848       return CK_FloatingCast;
5849     case Type::STK_Bool:
5850       return CK_FloatingToBoolean;
5851     case Type::STK_Integral:
5852       return CK_FloatingToIntegral;
5853     case Type::STK_FloatingComplex:
5854       Src = ImpCastExprToType(Src.get(),
5855                               DestTy->castAs<ComplexType>()->getElementType(),
5856                               CK_FloatingCast);
5857       return CK_FloatingRealToComplex;
5858     case Type::STK_IntegralComplex:
5859       Src = ImpCastExprToType(Src.get(),
5860                               DestTy->castAs<ComplexType>()->getElementType(),
5861                               CK_FloatingToIntegral);
5862       return CK_IntegralRealToComplex;
5863     case Type::STK_CPointer:
5864     case Type::STK_ObjCObjectPointer:
5865     case Type::STK_BlockPointer:
5866       llvm_unreachable("valid float->pointer cast?");
5867     case Type::STK_MemberPointer:
5868       llvm_unreachable("member pointer type in C");
5869     }
5870     llvm_unreachable("Should have returned before this");
5871 
5872   case Type::STK_FloatingComplex:
5873     switch (DestTy->getScalarTypeKind()) {
5874     case Type::STK_FloatingComplex:
5875       return CK_FloatingComplexCast;
5876     case Type::STK_IntegralComplex:
5877       return CK_FloatingComplexToIntegralComplex;
5878     case Type::STK_Floating: {
5879       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5880       if (Context.hasSameType(ET, DestTy))
5881         return CK_FloatingComplexToReal;
5882       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5883       return CK_FloatingCast;
5884     }
5885     case Type::STK_Bool:
5886       return CK_FloatingComplexToBoolean;
5887     case Type::STK_Integral:
5888       Src = ImpCastExprToType(Src.get(),
5889                               SrcTy->castAs<ComplexType>()->getElementType(),
5890                               CK_FloatingComplexToReal);
5891       return CK_FloatingToIntegral;
5892     case Type::STK_CPointer:
5893     case Type::STK_ObjCObjectPointer:
5894     case Type::STK_BlockPointer:
5895       llvm_unreachable("valid complex float->pointer cast?");
5896     case Type::STK_MemberPointer:
5897       llvm_unreachable("member pointer type in C");
5898     }
5899     llvm_unreachable("Should have returned before this");
5900 
5901   case Type::STK_IntegralComplex:
5902     switch (DestTy->getScalarTypeKind()) {
5903     case Type::STK_FloatingComplex:
5904       return CK_IntegralComplexToFloatingComplex;
5905     case Type::STK_IntegralComplex:
5906       return CK_IntegralComplexCast;
5907     case Type::STK_Integral: {
5908       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5909       if (Context.hasSameType(ET, DestTy))
5910         return CK_IntegralComplexToReal;
5911       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5912       return CK_IntegralCast;
5913     }
5914     case Type::STK_Bool:
5915       return CK_IntegralComplexToBoolean;
5916     case Type::STK_Floating:
5917       Src = ImpCastExprToType(Src.get(),
5918                               SrcTy->castAs<ComplexType>()->getElementType(),
5919                               CK_IntegralComplexToReal);
5920       return CK_IntegralToFloating;
5921     case Type::STK_CPointer:
5922     case Type::STK_ObjCObjectPointer:
5923     case Type::STK_BlockPointer:
5924       llvm_unreachable("valid complex int->pointer cast?");
5925     case Type::STK_MemberPointer:
5926       llvm_unreachable("member pointer type in C");
5927     }
5928     llvm_unreachable("Should have returned before this");
5929   }
5930 
5931   llvm_unreachable("Unhandled scalar cast");
5932 }
5933 
5934 static bool breakDownVectorType(QualType type, uint64_t &len,
5935                                 QualType &eltType) {
5936   // Vectors are simple.
5937   if (const VectorType *vecType = type->getAs<VectorType>()) {
5938     len = vecType->getNumElements();
5939     eltType = vecType->getElementType();
5940     assert(eltType->isScalarType());
5941     return true;
5942   }
5943 
5944   // We allow lax conversion to and from non-vector types, but only if
5945   // they're real types (i.e. non-complex, non-pointer scalar types).
5946   if (!type->isRealType()) return false;
5947 
5948   len = 1;
5949   eltType = type;
5950   return true;
5951 }
5952 
5953 /// Are the two types lax-compatible vector types?  That is, given
5954 /// that one of them is a vector, do they have equal storage sizes,
5955 /// where the storage size is the number of elements times the element
5956 /// size?
5957 ///
5958 /// This will also return false if either of the types is neither a
5959 /// vector nor a real type.
5960 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5961   assert(destTy->isVectorType() || srcTy->isVectorType());
5962 
5963   // Disallow lax conversions between scalars and ExtVectors (these
5964   // conversions are allowed for other vector types because common headers
5965   // depend on them).  Most scalar OP ExtVector cases are handled by the
5966   // splat path anyway, which does what we want (convert, not bitcast).
5967   // What this rules out for ExtVectors is crazy things like char4*float.
5968   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5969   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5970 
5971   uint64_t srcLen, destLen;
5972   QualType srcEltTy, destEltTy;
5973   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5974   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5975 
5976   // ASTContext::getTypeSize will return the size rounded up to a
5977   // power of 2, so instead of using that, we need to use the raw
5978   // element size multiplied by the element count.
5979   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5980   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5981 
5982   return (srcLen * srcEltSize == destLen * destEltSize);
5983 }
5984 
5985 /// Is this a legal conversion between two types, one of which is
5986 /// known to be a vector type?
5987 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5988   assert(destTy->isVectorType() || srcTy->isVectorType());
5989 
5990   if (!Context.getLangOpts().LaxVectorConversions)
5991     return false;
5992   return areLaxCompatibleVectorTypes(srcTy, destTy);
5993 }
5994 
5995 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5996                            CastKind &Kind) {
5997   assert(VectorTy->isVectorType() && "Not a vector type!");
5998 
5999   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6000     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6001       return Diag(R.getBegin(),
6002                   Ty->isVectorType() ?
6003                   diag::err_invalid_conversion_between_vectors :
6004                   diag::err_invalid_conversion_between_vector_and_integer)
6005         << VectorTy << Ty << R;
6006   } else
6007     return Diag(R.getBegin(),
6008                 diag::err_invalid_conversion_between_vector_and_scalar)
6009       << VectorTy << Ty << R;
6010 
6011   Kind = CK_BitCast;
6012   return false;
6013 }
6014 
6015 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6016   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6017 
6018   if (DestElemTy == SplattedExpr->getType())
6019     return SplattedExpr;
6020 
6021   assert(DestElemTy->isFloatingType() ||
6022          DestElemTy->isIntegralOrEnumerationType());
6023 
6024   CastKind CK;
6025   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6026     // OpenCL requires that we convert `true` boolean expressions to -1, but
6027     // only when splatting vectors.
6028     if (DestElemTy->isFloatingType()) {
6029       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6030       // in two steps: boolean to signed integral, then to floating.
6031       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6032                                                  CK_BooleanToSignedIntegral);
6033       SplattedExpr = CastExprRes.get();
6034       CK = CK_IntegralToFloating;
6035     } else {
6036       CK = CK_BooleanToSignedIntegral;
6037     }
6038   } else {
6039     ExprResult CastExprRes = SplattedExpr;
6040     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6041     if (CastExprRes.isInvalid())
6042       return ExprError();
6043     SplattedExpr = CastExprRes.get();
6044   }
6045   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6046 }
6047 
6048 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6049                                     Expr *CastExpr, CastKind &Kind) {
6050   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6051 
6052   QualType SrcTy = CastExpr->getType();
6053 
6054   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6055   // an ExtVectorType.
6056   // In OpenCL, casts between vectors of different types are not allowed.
6057   // (See OpenCL 6.2).
6058   if (SrcTy->isVectorType()) {
6059     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6060         (getLangOpts().OpenCL &&
6061          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6062       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6063         << DestTy << SrcTy << R;
6064       return ExprError();
6065     }
6066     Kind = CK_BitCast;
6067     return CastExpr;
6068   }
6069 
6070   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6071   // conversion will take place first from scalar to elt type, and then
6072   // splat from elt type to vector.
6073   if (SrcTy->isPointerType())
6074     return Diag(R.getBegin(),
6075                 diag::err_invalid_conversion_between_vector_and_scalar)
6076       << DestTy << SrcTy << R;
6077 
6078   Kind = CK_VectorSplat;
6079   return prepareVectorSplat(DestTy, CastExpr);
6080 }
6081 
6082 ExprResult
6083 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6084                     Declarator &D, ParsedType &Ty,
6085                     SourceLocation RParenLoc, Expr *CastExpr) {
6086   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6087          "ActOnCastExpr(): missing type or expr");
6088 
6089   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6090   if (D.isInvalidType())
6091     return ExprError();
6092 
6093   if (getLangOpts().CPlusPlus) {
6094     // Check that there are no default arguments (C++ only).
6095     CheckExtraCXXDefaultArguments(D);
6096   } else {
6097     // Make sure any TypoExprs have been dealt with.
6098     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6099     if (!Res.isUsable())
6100       return ExprError();
6101     CastExpr = Res.get();
6102   }
6103 
6104   checkUnusedDeclAttributes(D);
6105 
6106   QualType castType = castTInfo->getType();
6107   Ty = CreateParsedType(castType, castTInfo);
6108 
6109   bool isVectorLiteral = false;
6110 
6111   // Check for an altivec or OpenCL literal,
6112   // i.e. all the elements are integer constants.
6113   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6114   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6115   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6116        && castType->isVectorType() && (PE || PLE)) {
6117     if (PLE && PLE->getNumExprs() == 0) {
6118       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6119       return ExprError();
6120     }
6121     if (PE || PLE->getNumExprs() == 1) {
6122       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6123       if (!E->getType()->isVectorType())
6124         isVectorLiteral = true;
6125     }
6126     else
6127       isVectorLiteral = true;
6128   }
6129 
6130   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6131   // then handle it as such.
6132   if (isVectorLiteral)
6133     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6134 
6135   // If the Expr being casted is a ParenListExpr, handle it specially.
6136   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6137   // sequence of BinOp comma operators.
6138   if (isa<ParenListExpr>(CastExpr)) {
6139     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6140     if (Result.isInvalid()) return ExprError();
6141     CastExpr = Result.get();
6142   }
6143 
6144   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6145       !getSourceManager().isInSystemMacro(LParenLoc))
6146     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6147 
6148   CheckTollFreeBridgeCast(castType, CastExpr);
6149 
6150   CheckObjCBridgeRelatedCast(castType, CastExpr);
6151 
6152   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6153 
6154   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6155 }
6156 
6157 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6158                                     SourceLocation RParenLoc, Expr *E,
6159                                     TypeSourceInfo *TInfo) {
6160   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6161          "Expected paren or paren list expression");
6162 
6163   Expr **exprs;
6164   unsigned numExprs;
6165   Expr *subExpr;
6166   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6167   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6168     LiteralLParenLoc = PE->getLParenLoc();
6169     LiteralRParenLoc = PE->getRParenLoc();
6170     exprs = PE->getExprs();
6171     numExprs = PE->getNumExprs();
6172   } else { // isa<ParenExpr> by assertion at function entrance
6173     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6174     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6175     subExpr = cast<ParenExpr>(E)->getSubExpr();
6176     exprs = &subExpr;
6177     numExprs = 1;
6178   }
6179 
6180   QualType Ty = TInfo->getType();
6181   assert(Ty->isVectorType() && "Expected vector type");
6182 
6183   SmallVector<Expr *, 8> initExprs;
6184   const VectorType *VTy = Ty->getAs<VectorType>();
6185   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6186 
6187   // '(...)' form of vector initialization in AltiVec: the number of
6188   // initializers must be one or must match the size of the vector.
6189   // If a single value is specified in the initializer then it will be
6190   // replicated to all the components of the vector
6191   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6192     // The number of initializers must be one or must match the size of the
6193     // vector. If a single value is specified in the initializer then it will
6194     // be replicated to all the components of the vector
6195     if (numExprs == 1) {
6196       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6197       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6198       if (Literal.isInvalid())
6199         return ExprError();
6200       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6201                                   PrepareScalarCast(Literal, ElemTy));
6202       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6203     }
6204     else if (numExprs < numElems) {
6205       Diag(E->getExprLoc(),
6206            diag::err_incorrect_number_of_vector_initializers);
6207       return ExprError();
6208     }
6209     else
6210       initExprs.append(exprs, exprs + numExprs);
6211   }
6212   else {
6213     // For OpenCL, when the number of initializers is a single value,
6214     // it will be replicated to all components of the vector.
6215     if (getLangOpts().OpenCL &&
6216         VTy->getVectorKind() == VectorType::GenericVector &&
6217         numExprs == 1) {
6218         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6219         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6220         if (Literal.isInvalid())
6221           return ExprError();
6222         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6223                                     PrepareScalarCast(Literal, ElemTy));
6224         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6225     }
6226 
6227     initExprs.append(exprs, exprs + numExprs);
6228   }
6229   // FIXME: This means that pretty-printing the final AST will produce curly
6230   // braces instead of the original commas.
6231   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6232                                                    initExprs, LiteralRParenLoc);
6233   initE->setType(Ty);
6234   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6235 }
6236 
6237 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6238 /// the ParenListExpr into a sequence of comma binary operators.
6239 ExprResult
6240 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6241   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6242   if (!E)
6243     return OrigExpr;
6244 
6245   ExprResult Result(E->getExpr(0));
6246 
6247   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6248     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6249                         E->getExpr(i));
6250 
6251   if (Result.isInvalid()) return ExprError();
6252 
6253   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6254 }
6255 
6256 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6257                                     SourceLocation R,
6258                                     MultiExprArg Val) {
6259   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6260   return expr;
6261 }
6262 
6263 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6264 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6265 /// emitted.
6266 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6267                                       SourceLocation QuestionLoc) {
6268   Expr *NullExpr = LHSExpr;
6269   Expr *NonPointerExpr = RHSExpr;
6270   Expr::NullPointerConstantKind NullKind =
6271       NullExpr->isNullPointerConstant(Context,
6272                                       Expr::NPC_ValueDependentIsNotNull);
6273 
6274   if (NullKind == Expr::NPCK_NotNull) {
6275     NullExpr = RHSExpr;
6276     NonPointerExpr = LHSExpr;
6277     NullKind =
6278         NullExpr->isNullPointerConstant(Context,
6279                                         Expr::NPC_ValueDependentIsNotNull);
6280   }
6281 
6282   if (NullKind == Expr::NPCK_NotNull)
6283     return false;
6284 
6285   if (NullKind == Expr::NPCK_ZeroExpression)
6286     return false;
6287 
6288   if (NullKind == Expr::NPCK_ZeroLiteral) {
6289     // In this case, check to make sure that we got here from a "NULL"
6290     // string in the source code.
6291     NullExpr = NullExpr->IgnoreParenImpCasts();
6292     SourceLocation loc = NullExpr->getExprLoc();
6293     if (!findMacroSpelling(loc, "NULL"))
6294       return false;
6295   }
6296 
6297   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6298   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6299       << NonPointerExpr->getType() << DiagType
6300       << NonPointerExpr->getSourceRange();
6301   return true;
6302 }
6303 
6304 /// \brief Return false if the condition expression is valid, true otherwise.
6305 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6306   QualType CondTy = Cond->getType();
6307 
6308   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6309   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6310     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6311       << CondTy << Cond->getSourceRange();
6312     return true;
6313   }
6314 
6315   // C99 6.5.15p2
6316   if (CondTy->isScalarType()) return false;
6317 
6318   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6319     << CondTy << Cond->getSourceRange();
6320   return true;
6321 }
6322 
6323 /// \brief Handle when one or both operands are void type.
6324 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6325                                          ExprResult &RHS) {
6326     Expr *LHSExpr = LHS.get();
6327     Expr *RHSExpr = RHS.get();
6328 
6329     if (!LHSExpr->getType()->isVoidType())
6330       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6331         << RHSExpr->getSourceRange();
6332     if (!RHSExpr->getType()->isVoidType())
6333       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6334         << LHSExpr->getSourceRange();
6335     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6336     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6337     return S.Context.VoidTy;
6338 }
6339 
6340 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6341 /// true otherwise.
6342 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6343                                         QualType PointerTy) {
6344   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6345       !NullExpr.get()->isNullPointerConstant(S.Context,
6346                                             Expr::NPC_ValueDependentIsNull))
6347     return true;
6348 
6349   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6350   return false;
6351 }
6352 
6353 /// \brief Checks compatibility between two pointers and return the resulting
6354 /// type.
6355 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6356                                                      ExprResult &RHS,
6357                                                      SourceLocation Loc) {
6358   QualType LHSTy = LHS.get()->getType();
6359   QualType RHSTy = RHS.get()->getType();
6360 
6361   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6362     // Two identical pointers types are always compatible.
6363     return LHSTy;
6364   }
6365 
6366   QualType lhptee, rhptee;
6367 
6368   // Get the pointee types.
6369   bool IsBlockPointer = false;
6370   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6371     lhptee = LHSBTy->getPointeeType();
6372     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6373     IsBlockPointer = true;
6374   } else {
6375     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6376     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6377   }
6378 
6379   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6380   // differently qualified versions of compatible types, the result type is
6381   // a pointer to an appropriately qualified version of the composite
6382   // type.
6383 
6384   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6385   // clause doesn't make sense for our extensions. E.g. address space 2 should
6386   // be incompatible with address space 3: they may live on different devices or
6387   // anything.
6388   Qualifiers lhQual = lhptee.getQualifiers();
6389   Qualifiers rhQual = rhptee.getQualifiers();
6390 
6391   LangAS ResultAddrSpace = LangAS::Default;
6392   LangAS LAddrSpace = lhQual.getAddressSpace();
6393   LangAS RAddrSpace = rhQual.getAddressSpace();
6394   if (S.getLangOpts().OpenCL) {
6395     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6396     // spaces is disallowed.
6397     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6398       ResultAddrSpace = LAddrSpace;
6399     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6400       ResultAddrSpace = RAddrSpace;
6401     else {
6402       S.Diag(Loc,
6403              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6404           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6405           << RHS.get()->getSourceRange();
6406       return QualType();
6407     }
6408   }
6409 
6410   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6411   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6412   lhQual.removeCVRQualifiers();
6413   rhQual.removeCVRQualifiers();
6414 
6415   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6416   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6417   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6418   // qual types are compatible iff
6419   //  * corresponded types are compatible
6420   //  * CVR qualifiers are equal
6421   //  * address spaces are equal
6422   // Thus for conditional operator we merge CVR and address space unqualified
6423   // pointees and if there is a composite type we return a pointer to it with
6424   // merged qualifiers.
6425   if (S.getLangOpts().OpenCL) {
6426     LHSCastKind = LAddrSpace == ResultAddrSpace
6427                       ? CK_BitCast
6428                       : CK_AddressSpaceConversion;
6429     RHSCastKind = RAddrSpace == ResultAddrSpace
6430                       ? CK_BitCast
6431                       : CK_AddressSpaceConversion;
6432     lhQual.removeAddressSpace();
6433     rhQual.removeAddressSpace();
6434   }
6435 
6436   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6437   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6438 
6439   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6440 
6441   if (CompositeTy.isNull()) {
6442     // In this situation, we assume void* type. No especially good
6443     // reason, but this is what gcc does, and we do have to pick
6444     // to get a consistent AST.
6445     QualType incompatTy;
6446     incompatTy = S.Context.getPointerType(
6447         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6448     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6449     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6450     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6451     // for casts between types with incompatible address space qualifiers.
6452     // For the following code the compiler produces casts between global and
6453     // local address spaces of the corresponded innermost pointees:
6454     // local int *global *a;
6455     // global int *global *b;
6456     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6457     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6458         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6459         << RHS.get()->getSourceRange();
6460     return incompatTy;
6461   }
6462 
6463   // The pointer types are compatible.
6464   // In case of OpenCL ResultTy should have the address space qualifier
6465   // which is a superset of address spaces of both the 2nd and the 3rd
6466   // operands of the conditional operator.
6467   QualType ResultTy = [&, ResultAddrSpace]() {
6468     if (S.getLangOpts().OpenCL) {
6469       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6470       CompositeQuals.setAddressSpace(ResultAddrSpace);
6471       return S.Context
6472           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6473           .withCVRQualifiers(MergedCVRQual);
6474     }
6475     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6476   }();
6477   if (IsBlockPointer)
6478     ResultTy = S.Context.getBlockPointerType(ResultTy);
6479   else
6480     ResultTy = S.Context.getPointerType(ResultTy);
6481 
6482   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6483   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6484   return ResultTy;
6485 }
6486 
6487 /// \brief Return the resulting type when the operands are both block pointers.
6488 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6489                                                           ExprResult &LHS,
6490                                                           ExprResult &RHS,
6491                                                           SourceLocation Loc) {
6492   QualType LHSTy = LHS.get()->getType();
6493   QualType RHSTy = RHS.get()->getType();
6494 
6495   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6496     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6497       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6498       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6499       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6500       return destType;
6501     }
6502     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6503       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6504       << RHS.get()->getSourceRange();
6505     return QualType();
6506   }
6507 
6508   // We have 2 block pointer types.
6509   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6510 }
6511 
6512 /// \brief Return the resulting type when the operands are both pointers.
6513 static QualType
6514 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6515                                             ExprResult &RHS,
6516                                             SourceLocation Loc) {
6517   // get the pointer types
6518   QualType LHSTy = LHS.get()->getType();
6519   QualType RHSTy = RHS.get()->getType();
6520 
6521   // get the "pointed to" types
6522   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6523   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6524 
6525   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6526   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6527     // Figure out necessary qualifiers (C99 6.5.15p6)
6528     QualType destPointee
6529       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6530     QualType destType = S.Context.getPointerType(destPointee);
6531     // Add qualifiers if necessary.
6532     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6533     // Promote to void*.
6534     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6535     return destType;
6536   }
6537   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6538     QualType destPointee
6539       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6540     QualType destType = S.Context.getPointerType(destPointee);
6541     // Add qualifiers if necessary.
6542     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6543     // Promote to void*.
6544     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6545     return destType;
6546   }
6547 
6548   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6549 }
6550 
6551 /// \brief Return false if the first expression is not an integer and the second
6552 /// expression is not a pointer, true otherwise.
6553 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6554                                         Expr* PointerExpr, SourceLocation Loc,
6555                                         bool IsIntFirstExpr) {
6556   if (!PointerExpr->getType()->isPointerType() ||
6557       !Int.get()->getType()->isIntegerType())
6558     return false;
6559 
6560   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6561   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6562 
6563   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6564     << Expr1->getType() << Expr2->getType()
6565     << Expr1->getSourceRange() << Expr2->getSourceRange();
6566   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6567                             CK_IntegralToPointer);
6568   return true;
6569 }
6570 
6571 /// \brief Simple conversion between integer and floating point types.
6572 ///
6573 /// Used when handling the OpenCL conditional operator where the
6574 /// condition is a vector while the other operands are scalar.
6575 ///
6576 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6577 /// types are either integer or floating type. Between the two
6578 /// operands, the type with the higher rank is defined as the "result
6579 /// type". The other operand needs to be promoted to the same type. No
6580 /// other type promotion is allowed. We cannot use
6581 /// UsualArithmeticConversions() for this purpose, since it always
6582 /// promotes promotable types.
6583 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6584                                             ExprResult &RHS,
6585                                             SourceLocation QuestionLoc) {
6586   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6587   if (LHS.isInvalid())
6588     return QualType();
6589   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6590   if (RHS.isInvalid())
6591     return QualType();
6592 
6593   // For conversion purposes, we ignore any qualifiers.
6594   // For example, "const float" and "float" are equivalent.
6595   QualType LHSType =
6596     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6597   QualType RHSType =
6598     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6599 
6600   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6601     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6602       << LHSType << LHS.get()->getSourceRange();
6603     return QualType();
6604   }
6605 
6606   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6607     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6608       << RHSType << RHS.get()->getSourceRange();
6609     return QualType();
6610   }
6611 
6612   // If both types are identical, no conversion is needed.
6613   if (LHSType == RHSType)
6614     return LHSType;
6615 
6616   // Now handle "real" floating types (i.e. float, double, long double).
6617   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6618     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6619                                  /*IsCompAssign = */ false);
6620 
6621   // Finally, we have two differing integer types.
6622   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6623   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6624 }
6625 
6626 /// \brief Convert scalar operands to a vector that matches the
6627 ///        condition in length.
6628 ///
6629 /// Used when handling the OpenCL conditional operator where the
6630 /// condition is a vector while the other operands are scalar.
6631 ///
6632 /// We first compute the "result type" for the scalar operands
6633 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6634 /// into a vector of that type where the length matches the condition
6635 /// vector type. s6.11.6 requires that the element types of the result
6636 /// and the condition must have the same number of bits.
6637 static QualType
6638 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6639                               QualType CondTy, SourceLocation QuestionLoc) {
6640   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6641   if (ResTy.isNull()) return QualType();
6642 
6643   const VectorType *CV = CondTy->getAs<VectorType>();
6644   assert(CV);
6645 
6646   // Determine the vector result type
6647   unsigned NumElements = CV->getNumElements();
6648   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6649 
6650   // Ensure that all types have the same number of bits
6651   if (S.Context.getTypeSize(CV->getElementType())
6652       != S.Context.getTypeSize(ResTy)) {
6653     // Since VectorTy is created internally, it does not pretty print
6654     // with an OpenCL name. Instead, we just print a description.
6655     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6656     SmallString<64> Str;
6657     llvm::raw_svector_ostream OS(Str);
6658     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6659     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6660       << CondTy << OS.str();
6661     return QualType();
6662   }
6663 
6664   // Convert operands to the vector result type
6665   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6666   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6667 
6668   return VectorTy;
6669 }
6670 
6671 /// \brief Return false if this is a valid OpenCL condition vector
6672 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6673                                        SourceLocation QuestionLoc) {
6674   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6675   // integral type.
6676   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6677   assert(CondTy);
6678   QualType EleTy = CondTy->getElementType();
6679   if (EleTy->isIntegerType()) return false;
6680 
6681   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6682     << Cond->getType() << Cond->getSourceRange();
6683   return true;
6684 }
6685 
6686 /// \brief Return false if the vector condition type and the vector
6687 ///        result type are compatible.
6688 ///
6689 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6690 /// number of elements, and their element types have the same number
6691 /// of bits.
6692 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6693                               SourceLocation QuestionLoc) {
6694   const VectorType *CV = CondTy->getAs<VectorType>();
6695   const VectorType *RV = VecResTy->getAs<VectorType>();
6696   assert(CV && RV);
6697 
6698   if (CV->getNumElements() != RV->getNumElements()) {
6699     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6700       << CondTy << VecResTy;
6701     return true;
6702   }
6703 
6704   QualType CVE = CV->getElementType();
6705   QualType RVE = RV->getElementType();
6706 
6707   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6708     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6709       << CondTy << VecResTy;
6710     return true;
6711   }
6712 
6713   return false;
6714 }
6715 
6716 /// \brief Return the resulting type for the conditional operator in
6717 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6718 ///        s6.3.i) when the condition is a vector type.
6719 static QualType
6720 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6721                              ExprResult &LHS, ExprResult &RHS,
6722                              SourceLocation QuestionLoc) {
6723   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6724   if (Cond.isInvalid())
6725     return QualType();
6726   QualType CondTy = Cond.get()->getType();
6727 
6728   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6729     return QualType();
6730 
6731   // If either operand is a vector then find the vector type of the
6732   // result as specified in OpenCL v1.1 s6.3.i.
6733   if (LHS.get()->getType()->isVectorType() ||
6734       RHS.get()->getType()->isVectorType()) {
6735     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6736                                               /*isCompAssign*/false,
6737                                               /*AllowBothBool*/true,
6738                                               /*AllowBoolConversions*/false);
6739     if (VecResTy.isNull()) return QualType();
6740     // The result type must match the condition type as specified in
6741     // OpenCL v1.1 s6.11.6.
6742     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6743       return QualType();
6744     return VecResTy;
6745   }
6746 
6747   // Both operands are scalar.
6748   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6749 }
6750 
6751 /// \brief Return true if the Expr is block type
6752 static bool checkBlockType(Sema &S, const Expr *E) {
6753   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6754     QualType Ty = CE->getCallee()->getType();
6755     if (Ty->isBlockPointerType()) {
6756       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6757       return true;
6758     }
6759   }
6760   return false;
6761 }
6762 
6763 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6764 /// In that case, LHS = cond.
6765 /// C99 6.5.15
6766 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6767                                         ExprResult &RHS, ExprValueKind &VK,
6768                                         ExprObjectKind &OK,
6769                                         SourceLocation QuestionLoc) {
6770 
6771   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6772   if (!LHSResult.isUsable()) return QualType();
6773   LHS = LHSResult;
6774 
6775   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6776   if (!RHSResult.isUsable()) return QualType();
6777   RHS = RHSResult;
6778 
6779   // C++ is sufficiently different to merit its own checker.
6780   if (getLangOpts().CPlusPlus)
6781     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6782 
6783   VK = VK_RValue;
6784   OK = OK_Ordinary;
6785 
6786   // The OpenCL operator with a vector condition is sufficiently
6787   // different to merit its own checker.
6788   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6789     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6790 
6791   // First, check the condition.
6792   Cond = UsualUnaryConversions(Cond.get());
6793   if (Cond.isInvalid())
6794     return QualType();
6795   if (checkCondition(*this, Cond.get(), QuestionLoc))
6796     return QualType();
6797 
6798   // Now check the two expressions.
6799   if (LHS.get()->getType()->isVectorType() ||
6800       RHS.get()->getType()->isVectorType())
6801     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6802                                /*AllowBothBool*/true,
6803                                /*AllowBoolConversions*/false);
6804 
6805   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6806   if (LHS.isInvalid() || RHS.isInvalid())
6807     return QualType();
6808 
6809   QualType LHSTy = LHS.get()->getType();
6810   QualType RHSTy = RHS.get()->getType();
6811 
6812   // Diagnose attempts to convert between __float128 and long double where
6813   // such conversions currently can't be handled.
6814   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6815     Diag(QuestionLoc,
6816          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6817       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6818     return QualType();
6819   }
6820 
6821   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6822   // selection operator (?:).
6823   if (getLangOpts().OpenCL &&
6824       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6825     return QualType();
6826   }
6827 
6828   // If both operands have arithmetic type, do the usual arithmetic conversions
6829   // to find a common type: C99 6.5.15p3,5.
6830   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6831     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6832     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6833 
6834     return ResTy;
6835   }
6836 
6837   // If both operands are the same structure or union type, the result is that
6838   // type.
6839   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6840     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6841       if (LHSRT->getDecl() == RHSRT->getDecl())
6842         // "If both the operands have structure or union type, the result has
6843         // that type."  This implies that CV qualifiers are dropped.
6844         return LHSTy.getUnqualifiedType();
6845     // FIXME: Type of conditional expression must be complete in C mode.
6846   }
6847 
6848   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6849   // The following || allows only one side to be void (a GCC-ism).
6850   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6851     return checkConditionalVoidType(*this, LHS, RHS);
6852   }
6853 
6854   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6855   // the type of the other operand."
6856   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6857   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6858 
6859   // All objective-c pointer type analysis is done here.
6860   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6861                                                         QuestionLoc);
6862   if (LHS.isInvalid() || RHS.isInvalid())
6863     return QualType();
6864   if (!compositeType.isNull())
6865     return compositeType;
6866 
6867 
6868   // Handle block pointer types.
6869   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6870     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6871                                                      QuestionLoc);
6872 
6873   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6874   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6875     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6876                                                        QuestionLoc);
6877 
6878   // GCC compatibility: soften pointer/integer mismatch.  Note that
6879   // null pointers have been filtered out by this point.
6880   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6881       /*isIntFirstExpr=*/true))
6882     return RHSTy;
6883   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6884       /*isIntFirstExpr=*/false))
6885     return LHSTy;
6886 
6887   // Emit a better diagnostic if one of the expressions is a null pointer
6888   // constant and the other is not a pointer type. In this case, the user most
6889   // likely forgot to take the address of the other expression.
6890   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6891     return QualType();
6892 
6893   // Otherwise, the operands are not compatible.
6894   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6895     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6896     << RHS.get()->getSourceRange();
6897   return QualType();
6898 }
6899 
6900 /// FindCompositeObjCPointerType - Helper method to find composite type of
6901 /// two objective-c pointer types of the two input expressions.
6902 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6903                                             SourceLocation QuestionLoc) {
6904   QualType LHSTy = LHS.get()->getType();
6905   QualType RHSTy = RHS.get()->getType();
6906 
6907   // Handle things like Class and struct objc_class*.  Here we case the result
6908   // to the pseudo-builtin, because that will be implicitly cast back to the
6909   // redefinition type if an attempt is made to access its fields.
6910   if (LHSTy->isObjCClassType() &&
6911       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6912     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6913     return LHSTy;
6914   }
6915   if (RHSTy->isObjCClassType() &&
6916       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6917     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6918     return RHSTy;
6919   }
6920   // And the same for struct objc_object* / id
6921   if (LHSTy->isObjCIdType() &&
6922       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6923     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6924     return LHSTy;
6925   }
6926   if (RHSTy->isObjCIdType() &&
6927       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6928     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6929     return RHSTy;
6930   }
6931   // And the same for struct objc_selector* / SEL
6932   if (Context.isObjCSelType(LHSTy) &&
6933       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6934     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6935     return LHSTy;
6936   }
6937   if (Context.isObjCSelType(RHSTy) &&
6938       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6939     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6940     return RHSTy;
6941   }
6942   // Check constraints for Objective-C object pointers types.
6943   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6944 
6945     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6946       // Two identical object pointer types are always compatible.
6947       return LHSTy;
6948     }
6949     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6950     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6951     QualType compositeType = LHSTy;
6952 
6953     // If both operands are interfaces and either operand can be
6954     // assigned to the other, use that type as the composite
6955     // type. This allows
6956     //   xxx ? (A*) a : (B*) b
6957     // where B is a subclass of A.
6958     //
6959     // Additionally, as for assignment, if either type is 'id'
6960     // allow silent coercion. Finally, if the types are
6961     // incompatible then make sure to use 'id' as the composite
6962     // type so the result is acceptable for sending messages to.
6963 
6964     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6965     // It could return the composite type.
6966     if (!(compositeType =
6967           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6968       // Nothing more to do.
6969     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6970       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6971     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6972       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6973     } else if ((LHSTy->isObjCQualifiedIdType() ||
6974                 RHSTy->isObjCQualifiedIdType()) &&
6975                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6976       // Need to handle "id<xx>" explicitly.
6977       // GCC allows qualified id and any Objective-C type to devolve to
6978       // id. Currently localizing to here until clear this should be
6979       // part of ObjCQualifiedIdTypesAreCompatible.
6980       compositeType = Context.getObjCIdType();
6981     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6982       compositeType = Context.getObjCIdType();
6983     } else {
6984       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6985       << LHSTy << RHSTy
6986       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6987       QualType incompatTy = Context.getObjCIdType();
6988       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6989       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6990       return incompatTy;
6991     }
6992     // The object pointer types are compatible.
6993     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6994     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6995     return compositeType;
6996   }
6997   // Check Objective-C object pointer types and 'void *'
6998   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6999     if (getLangOpts().ObjCAutoRefCount) {
7000       // ARC forbids the implicit conversion of object pointers to 'void *',
7001       // so these types are not compatible.
7002       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7003           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7004       LHS = RHS = true;
7005       return QualType();
7006     }
7007     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7008     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7009     QualType destPointee
7010     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7011     QualType destType = Context.getPointerType(destPointee);
7012     // Add qualifiers if necessary.
7013     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7014     // Promote to void*.
7015     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7016     return destType;
7017   }
7018   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7019     if (getLangOpts().ObjCAutoRefCount) {
7020       // ARC forbids the implicit conversion of object pointers to 'void *',
7021       // so these types are not compatible.
7022       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7023           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7024       LHS = RHS = true;
7025       return QualType();
7026     }
7027     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7028     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7029     QualType destPointee
7030     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7031     QualType destType = Context.getPointerType(destPointee);
7032     // Add qualifiers if necessary.
7033     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7034     // Promote to void*.
7035     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7036     return destType;
7037   }
7038   return QualType();
7039 }
7040 
7041 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7042 /// ParenRange in parentheses.
7043 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7044                                const PartialDiagnostic &Note,
7045                                SourceRange ParenRange) {
7046   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7047   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7048       EndLoc.isValid()) {
7049     Self.Diag(Loc, Note)
7050       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7051       << FixItHint::CreateInsertion(EndLoc, ")");
7052   } else {
7053     // We can't display the parentheses, so just show the bare note.
7054     Self.Diag(Loc, Note) << ParenRange;
7055   }
7056 }
7057 
7058 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7059   return BinaryOperator::isAdditiveOp(Opc) ||
7060          BinaryOperator::isMultiplicativeOp(Opc) ||
7061          BinaryOperator::isShiftOp(Opc);
7062 }
7063 
7064 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7065 /// expression, either using a built-in or overloaded operator,
7066 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7067 /// expression.
7068 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7069                                    Expr **RHSExprs) {
7070   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7071   E = E->IgnoreImpCasts();
7072   E = E->IgnoreConversionOperator();
7073   E = E->IgnoreImpCasts();
7074 
7075   // Built-in binary operator.
7076   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7077     if (IsArithmeticOp(OP->getOpcode())) {
7078       *Opcode = OP->getOpcode();
7079       *RHSExprs = OP->getRHS();
7080       return true;
7081     }
7082   }
7083 
7084   // Overloaded operator.
7085   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7086     if (Call->getNumArgs() != 2)
7087       return false;
7088 
7089     // Make sure this is really a binary operator that is safe to pass into
7090     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7091     OverloadedOperatorKind OO = Call->getOperator();
7092     if (OO < OO_Plus || OO > OO_Arrow ||
7093         OO == OO_PlusPlus || OO == OO_MinusMinus)
7094       return false;
7095 
7096     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7097     if (IsArithmeticOp(OpKind)) {
7098       *Opcode = OpKind;
7099       *RHSExprs = Call->getArg(1);
7100       return true;
7101     }
7102   }
7103 
7104   return false;
7105 }
7106 
7107 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7108 /// or is a logical expression such as (x==y) which has int type, but is
7109 /// commonly interpreted as boolean.
7110 static bool ExprLooksBoolean(Expr *E) {
7111   E = E->IgnoreParenImpCasts();
7112 
7113   if (E->getType()->isBooleanType())
7114     return true;
7115   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7116     return OP->isComparisonOp() || OP->isLogicalOp();
7117   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7118     return OP->getOpcode() == UO_LNot;
7119   if (E->getType()->isPointerType())
7120     return true;
7121 
7122   return false;
7123 }
7124 
7125 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7126 /// and binary operator are mixed in a way that suggests the programmer assumed
7127 /// the conditional operator has higher precedence, for example:
7128 /// "int x = a + someBinaryCondition ? 1 : 2".
7129 static void DiagnoseConditionalPrecedence(Sema &Self,
7130                                           SourceLocation OpLoc,
7131                                           Expr *Condition,
7132                                           Expr *LHSExpr,
7133                                           Expr *RHSExpr) {
7134   BinaryOperatorKind CondOpcode;
7135   Expr *CondRHS;
7136 
7137   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7138     return;
7139   if (!ExprLooksBoolean(CondRHS))
7140     return;
7141 
7142   // The condition is an arithmetic binary expression, with a right-
7143   // hand side that looks boolean, so warn.
7144 
7145   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7146       << Condition->getSourceRange()
7147       << BinaryOperator::getOpcodeStr(CondOpcode);
7148 
7149   SuggestParentheses(Self, OpLoc,
7150     Self.PDiag(diag::note_precedence_silence)
7151       << BinaryOperator::getOpcodeStr(CondOpcode),
7152     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7153 
7154   SuggestParentheses(Self, OpLoc,
7155     Self.PDiag(diag::note_precedence_conditional_first),
7156     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7157 }
7158 
7159 /// Compute the nullability of a conditional expression.
7160 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7161                                               QualType LHSTy, QualType RHSTy,
7162                                               ASTContext &Ctx) {
7163   if (!ResTy->isAnyPointerType())
7164     return ResTy;
7165 
7166   auto GetNullability = [&Ctx](QualType Ty) {
7167     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7168     if (Kind)
7169       return *Kind;
7170     return NullabilityKind::Unspecified;
7171   };
7172 
7173   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7174   NullabilityKind MergedKind;
7175 
7176   // Compute nullability of a binary conditional expression.
7177   if (IsBin) {
7178     if (LHSKind == NullabilityKind::NonNull)
7179       MergedKind = NullabilityKind::NonNull;
7180     else
7181       MergedKind = RHSKind;
7182   // Compute nullability of a normal conditional expression.
7183   } else {
7184     if (LHSKind == NullabilityKind::Nullable ||
7185         RHSKind == NullabilityKind::Nullable)
7186       MergedKind = NullabilityKind::Nullable;
7187     else if (LHSKind == NullabilityKind::NonNull)
7188       MergedKind = RHSKind;
7189     else if (RHSKind == NullabilityKind::NonNull)
7190       MergedKind = LHSKind;
7191     else
7192       MergedKind = NullabilityKind::Unspecified;
7193   }
7194 
7195   // Return if ResTy already has the correct nullability.
7196   if (GetNullability(ResTy) == MergedKind)
7197     return ResTy;
7198 
7199   // Strip all nullability from ResTy.
7200   while (ResTy->getNullability(Ctx))
7201     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7202 
7203   // Create a new AttributedType with the new nullability kind.
7204   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7205   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7206 }
7207 
7208 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7209 /// in the case of a the GNU conditional expr extension.
7210 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7211                                     SourceLocation ColonLoc,
7212                                     Expr *CondExpr, Expr *LHSExpr,
7213                                     Expr *RHSExpr) {
7214   if (!getLangOpts().CPlusPlus) {
7215     // C cannot handle TypoExpr nodes in the condition because it
7216     // doesn't handle dependent types properly, so make sure any TypoExprs have
7217     // been dealt with before checking the operands.
7218     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7219     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7220     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7221 
7222     if (!CondResult.isUsable())
7223       return ExprError();
7224 
7225     if (LHSExpr) {
7226       if (!LHSResult.isUsable())
7227         return ExprError();
7228     }
7229 
7230     if (!RHSResult.isUsable())
7231       return ExprError();
7232 
7233     CondExpr = CondResult.get();
7234     LHSExpr = LHSResult.get();
7235     RHSExpr = RHSResult.get();
7236   }
7237 
7238   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7239   // was the condition.
7240   OpaqueValueExpr *opaqueValue = nullptr;
7241   Expr *commonExpr = nullptr;
7242   if (!LHSExpr) {
7243     commonExpr = CondExpr;
7244     // Lower out placeholder types first.  This is important so that we don't
7245     // try to capture a placeholder. This happens in few cases in C++; such
7246     // as Objective-C++'s dictionary subscripting syntax.
7247     if (commonExpr->hasPlaceholderType()) {
7248       ExprResult result = CheckPlaceholderExpr(commonExpr);
7249       if (!result.isUsable()) return ExprError();
7250       commonExpr = result.get();
7251     }
7252     // We usually want to apply unary conversions *before* saving, except
7253     // in the special case of a C++ l-value conditional.
7254     if (!(getLangOpts().CPlusPlus
7255           && !commonExpr->isTypeDependent()
7256           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7257           && commonExpr->isGLValue()
7258           && commonExpr->isOrdinaryOrBitFieldObject()
7259           && RHSExpr->isOrdinaryOrBitFieldObject()
7260           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7261       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7262       if (commonRes.isInvalid())
7263         return ExprError();
7264       commonExpr = commonRes.get();
7265     }
7266 
7267     // If the common expression is a class or array prvalue, materialize it
7268     // so that we can safely refer to it multiple times.
7269     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7270                                    commonExpr->getType()->isArrayType())) {
7271       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7272       if (MatExpr.isInvalid())
7273         return ExprError();
7274       commonExpr = MatExpr.get();
7275     }
7276 
7277     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7278                                                 commonExpr->getType(),
7279                                                 commonExpr->getValueKind(),
7280                                                 commonExpr->getObjectKind(),
7281                                                 commonExpr);
7282     LHSExpr = CondExpr = opaqueValue;
7283   }
7284 
7285   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7286   ExprValueKind VK = VK_RValue;
7287   ExprObjectKind OK = OK_Ordinary;
7288   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7289   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7290                                              VK, OK, QuestionLoc);
7291   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7292       RHS.isInvalid())
7293     return ExprError();
7294 
7295   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7296                                 RHS.get());
7297 
7298   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7299 
7300   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7301                                          Context);
7302 
7303   if (!commonExpr)
7304     return new (Context)
7305         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7306                             RHS.get(), result, VK, OK);
7307 
7308   return new (Context) BinaryConditionalOperator(
7309       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7310       ColonLoc, result, VK, OK);
7311 }
7312 
7313 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7314 // being closely modeled after the C99 spec:-). The odd characteristic of this
7315 // routine is it effectively iqnores the qualifiers on the top level pointee.
7316 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7317 // FIXME: add a couple examples in this comment.
7318 static Sema::AssignConvertType
7319 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7320   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7321   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7322 
7323   // get the "pointed to" type (ignoring qualifiers at the top level)
7324   const Type *lhptee, *rhptee;
7325   Qualifiers lhq, rhq;
7326   std::tie(lhptee, lhq) =
7327       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7328   std::tie(rhptee, rhq) =
7329       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7330 
7331   Sema::AssignConvertType ConvTy = Sema::Compatible;
7332 
7333   // C99 6.5.16.1p1: This following citation is common to constraints
7334   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7335   // qualifiers of the type *pointed to* by the right;
7336 
7337   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7338   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7339       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7340     // Ignore lifetime for further calculation.
7341     lhq.removeObjCLifetime();
7342     rhq.removeObjCLifetime();
7343   }
7344 
7345   if (!lhq.compatiblyIncludes(rhq)) {
7346     // Treat address-space mismatches as fatal.  TODO: address subspaces
7347     if (!lhq.isAddressSpaceSupersetOf(rhq))
7348       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7349 
7350     // It's okay to add or remove GC or lifetime qualifiers when converting to
7351     // and from void*.
7352     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7353                         .compatiblyIncludes(
7354                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7355              && (lhptee->isVoidType() || rhptee->isVoidType()))
7356       ; // keep old
7357 
7358     // Treat lifetime mismatches as fatal.
7359     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7360       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7361 
7362     // For GCC/MS compatibility, other qualifier mismatches are treated
7363     // as still compatible in C.
7364     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7365   }
7366 
7367   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7368   // incomplete type and the other is a pointer to a qualified or unqualified
7369   // version of void...
7370   if (lhptee->isVoidType()) {
7371     if (rhptee->isIncompleteOrObjectType())
7372       return ConvTy;
7373 
7374     // As an extension, we allow cast to/from void* to function pointer.
7375     assert(rhptee->isFunctionType());
7376     return Sema::FunctionVoidPointer;
7377   }
7378 
7379   if (rhptee->isVoidType()) {
7380     if (lhptee->isIncompleteOrObjectType())
7381       return ConvTy;
7382 
7383     // As an extension, we allow cast to/from void* to function pointer.
7384     assert(lhptee->isFunctionType());
7385     return Sema::FunctionVoidPointer;
7386   }
7387 
7388   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7389   // unqualified versions of compatible types, ...
7390   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7391   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7392     // Check if the pointee types are compatible ignoring the sign.
7393     // We explicitly check for char so that we catch "char" vs
7394     // "unsigned char" on systems where "char" is unsigned.
7395     if (lhptee->isCharType())
7396       ltrans = S.Context.UnsignedCharTy;
7397     else if (lhptee->hasSignedIntegerRepresentation())
7398       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7399 
7400     if (rhptee->isCharType())
7401       rtrans = S.Context.UnsignedCharTy;
7402     else if (rhptee->hasSignedIntegerRepresentation())
7403       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7404 
7405     if (ltrans == rtrans) {
7406       // Types are compatible ignoring the sign. Qualifier incompatibility
7407       // takes priority over sign incompatibility because the sign
7408       // warning can be disabled.
7409       if (ConvTy != Sema::Compatible)
7410         return ConvTy;
7411 
7412       return Sema::IncompatiblePointerSign;
7413     }
7414 
7415     // If we are a multi-level pointer, it's possible that our issue is simply
7416     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7417     // the eventual target type is the same and the pointers have the same
7418     // level of indirection, this must be the issue.
7419     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7420       do {
7421         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7422         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7423       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7424 
7425       if (lhptee == rhptee)
7426         return Sema::IncompatibleNestedPointerQualifiers;
7427     }
7428 
7429     // General pointer incompatibility takes priority over qualifiers.
7430     return Sema::IncompatiblePointer;
7431   }
7432   if (!S.getLangOpts().CPlusPlus &&
7433       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7434     return Sema::IncompatiblePointer;
7435   return ConvTy;
7436 }
7437 
7438 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7439 /// block pointer types are compatible or whether a block and normal pointer
7440 /// are compatible. It is more restrict than comparing two function pointer
7441 // types.
7442 static Sema::AssignConvertType
7443 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7444                                     QualType RHSType) {
7445   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7446   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7447 
7448   QualType lhptee, rhptee;
7449 
7450   // get the "pointed to" type (ignoring qualifiers at the top level)
7451   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7452   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7453 
7454   // In C++, the types have to match exactly.
7455   if (S.getLangOpts().CPlusPlus)
7456     return Sema::IncompatibleBlockPointer;
7457 
7458   Sema::AssignConvertType ConvTy = Sema::Compatible;
7459 
7460   // For blocks we enforce that qualifiers are identical.
7461   Qualifiers LQuals = lhptee.getLocalQualifiers();
7462   Qualifiers RQuals = rhptee.getLocalQualifiers();
7463   if (S.getLangOpts().OpenCL) {
7464     LQuals.removeAddressSpace();
7465     RQuals.removeAddressSpace();
7466   }
7467   if (LQuals != RQuals)
7468     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7469 
7470   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7471   // assignment.
7472   // The current behavior is similar to C++ lambdas. A block might be
7473   // assigned to a variable iff its return type and parameters are compatible
7474   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7475   // an assignment. Presumably it should behave in way that a function pointer
7476   // assignment does in C, so for each parameter and return type:
7477   //  * CVR and address space of LHS should be a superset of CVR and address
7478   //  space of RHS.
7479   //  * unqualified types should be compatible.
7480   if (S.getLangOpts().OpenCL) {
7481     if (!S.Context.typesAreBlockPointerCompatible(
7482             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7483             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7484       return Sema::IncompatibleBlockPointer;
7485   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7486     return Sema::IncompatibleBlockPointer;
7487 
7488   return ConvTy;
7489 }
7490 
7491 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7492 /// for assignment compatibility.
7493 static Sema::AssignConvertType
7494 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7495                                    QualType RHSType) {
7496   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7497   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7498 
7499   if (LHSType->isObjCBuiltinType()) {
7500     // Class is not compatible with ObjC object pointers.
7501     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7502         !RHSType->isObjCQualifiedClassType())
7503       return Sema::IncompatiblePointer;
7504     return Sema::Compatible;
7505   }
7506   if (RHSType->isObjCBuiltinType()) {
7507     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7508         !LHSType->isObjCQualifiedClassType())
7509       return Sema::IncompatiblePointer;
7510     return Sema::Compatible;
7511   }
7512   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7513   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7514 
7515   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7516       // make an exception for id<P>
7517       !LHSType->isObjCQualifiedIdType())
7518     return Sema::CompatiblePointerDiscardsQualifiers;
7519 
7520   if (S.Context.typesAreCompatible(LHSType, RHSType))
7521     return Sema::Compatible;
7522   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7523     return Sema::IncompatibleObjCQualifiedId;
7524   return Sema::IncompatiblePointer;
7525 }
7526 
7527 Sema::AssignConvertType
7528 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7529                                  QualType LHSType, QualType RHSType) {
7530   // Fake up an opaque expression.  We don't actually care about what
7531   // cast operations are required, so if CheckAssignmentConstraints
7532   // adds casts to this they'll be wasted, but fortunately that doesn't
7533   // usually happen on valid code.
7534   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7535   ExprResult RHSPtr = &RHSExpr;
7536   CastKind K;
7537 
7538   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7539 }
7540 
7541 /// This helper function returns true if QT is a vector type that has element
7542 /// type ElementType.
7543 static bool isVector(QualType QT, QualType ElementType) {
7544   if (const VectorType *VT = QT->getAs<VectorType>())
7545     return VT->getElementType() == ElementType;
7546   return false;
7547 }
7548 
7549 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7550 /// has code to accommodate several GCC extensions when type checking
7551 /// pointers. Here are some objectionable examples that GCC considers warnings:
7552 ///
7553 ///  int a, *pint;
7554 ///  short *pshort;
7555 ///  struct foo *pfoo;
7556 ///
7557 ///  pint = pshort; // warning: assignment from incompatible pointer type
7558 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7559 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7560 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7561 ///
7562 /// As a result, the code for dealing with pointers is more complex than the
7563 /// C99 spec dictates.
7564 ///
7565 /// Sets 'Kind' for any result kind except Incompatible.
7566 Sema::AssignConvertType
7567 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7568                                  CastKind &Kind, bool ConvertRHS) {
7569   QualType RHSType = RHS.get()->getType();
7570   QualType OrigLHSType = LHSType;
7571 
7572   // Get canonical types.  We're not formatting these types, just comparing
7573   // them.
7574   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7575   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7576 
7577   // Common case: no conversion required.
7578   if (LHSType == RHSType) {
7579     Kind = CK_NoOp;
7580     return Compatible;
7581   }
7582 
7583   // If we have an atomic type, try a non-atomic assignment, then just add an
7584   // atomic qualification step.
7585   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7586     Sema::AssignConvertType result =
7587       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7588     if (result != Compatible)
7589       return result;
7590     if (Kind != CK_NoOp && ConvertRHS)
7591       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7592     Kind = CK_NonAtomicToAtomic;
7593     return Compatible;
7594   }
7595 
7596   // If the left-hand side is a reference type, then we are in a
7597   // (rare!) case where we've allowed the use of references in C,
7598   // e.g., as a parameter type in a built-in function. In this case,
7599   // just make sure that the type referenced is compatible with the
7600   // right-hand side type. The caller is responsible for adjusting
7601   // LHSType so that the resulting expression does not have reference
7602   // type.
7603   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7604     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7605       Kind = CK_LValueBitCast;
7606       return Compatible;
7607     }
7608     return Incompatible;
7609   }
7610 
7611   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7612   // to the same ExtVector type.
7613   if (LHSType->isExtVectorType()) {
7614     if (RHSType->isExtVectorType())
7615       return Incompatible;
7616     if (RHSType->isArithmeticType()) {
7617       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7618       if (ConvertRHS)
7619         RHS = prepareVectorSplat(LHSType, RHS.get());
7620       Kind = CK_VectorSplat;
7621       return Compatible;
7622     }
7623   }
7624 
7625   // Conversions to or from vector type.
7626   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7627     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7628       // Allow assignments of an AltiVec vector type to an equivalent GCC
7629       // vector type and vice versa
7630       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7631         Kind = CK_BitCast;
7632         return Compatible;
7633       }
7634 
7635       // If we are allowing lax vector conversions, and LHS and RHS are both
7636       // vectors, the total size only needs to be the same. This is a bitcast;
7637       // no bits are changed but the result type is different.
7638       if (isLaxVectorConversion(RHSType, LHSType)) {
7639         Kind = CK_BitCast;
7640         return IncompatibleVectors;
7641       }
7642     }
7643 
7644     // When the RHS comes from another lax conversion (e.g. binops between
7645     // scalars and vectors) the result is canonicalized as a vector. When the
7646     // LHS is also a vector, the lax is allowed by the condition above. Handle
7647     // the case where LHS is a scalar.
7648     if (LHSType->isScalarType()) {
7649       const VectorType *VecType = RHSType->getAs<VectorType>();
7650       if (VecType && VecType->getNumElements() == 1 &&
7651           isLaxVectorConversion(RHSType, LHSType)) {
7652         ExprResult *VecExpr = &RHS;
7653         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7654         Kind = CK_BitCast;
7655         return Compatible;
7656       }
7657     }
7658 
7659     return Incompatible;
7660   }
7661 
7662   // Diagnose attempts to convert between __float128 and long double where
7663   // such conversions currently can't be handled.
7664   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7665     return Incompatible;
7666 
7667   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7668   // discards the imaginary part.
7669   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7670       !LHSType->getAs<ComplexType>())
7671     return Incompatible;
7672 
7673   // Arithmetic conversions.
7674   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7675       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7676     if (ConvertRHS)
7677       Kind = PrepareScalarCast(RHS, LHSType);
7678     return Compatible;
7679   }
7680 
7681   // Conversions to normal pointers.
7682   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7683     // U* -> T*
7684     if (isa<PointerType>(RHSType)) {
7685       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7686       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7687       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7688       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7689     }
7690 
7691     // int -> T*
7692     if (RHSType->isIntegerType()) {
7693       Kind = CK_IntegralToPointer; // FIXME: null?
7694       return IntToPointer;
7695     }
7696 
7697     // C pointers are not compatible with ObjC object pointers,
7698     // with two exceptions:
7699     if (isa<ObjCObjectPointerType>(RHSType)) {
7700       //  - conversions to void*
7701       if (LHSPointer->getPointeeType()->isVoidType()) {
7702         Kind = CK_BitCast;
7703         return Compatible;
7704       }
7705 
7706       //  - conversions from 'Class' to the redefinition type
7707       if (RHSType->isObjCClassType() &&
7708           Context.hasSameType(LHSType,
7709                               Context.getObjCClassRedefinitionType())) {
7710         Kind = CK_BitCast;
7711         return Compatible;
7712       }
7713 
7714       Kind = CK_BitCast;
7715       return IncompatiblePointer;
7716     }
7717 
7718     // U^ -> void*
7719     if (RHSType->getAs<BlockPointerType>()) {
7720       if (LHSPointer->getPointeeType()->isVoidType()) {
7721         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7722         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7723                                 ->getPointeeType()
7724                                 .getAddressSpace();
7725         Kind =
7726             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7727         return Compatible;
7728       }
7729     }
7730 
7731     return Incompatible;
7732   }
7733 
7734   // Conversions to block pointers.
7735   if (isa<BlockPointerType>(LHSType)) {
7736     // U^ -> T^
7737     if (RHSType->isBlockPointerType()) {
7738       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7739                               ->getPointeeType()
7740                               .getAddressSpace();
7741       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7742                               ->getPointeeType()
7743                               .getAddressSpace();
7744       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7745       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7746     }
7747 
7748     // int or null -> T^
7749     if (RHSType->isIntegerType()) {
7750       Kind = CK_IntegralToPointer; // FIXME: null
7751       return IntToBlockPointer;
7752     }
7753 
7754     // id -> T^
7755     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7756       Kind = CK_AnyPointerToBlockPointerCast;
7757       return Compatible;
7758     }
7759 
7760     // void* -> T^
7761     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7762       if (RHSPT->getPointeeType()->isVoidType()) {
7763         Kind = CK_AnyPointerToBlockPointerCast;
7764         return Compatible;
7765       }
7766 
7767     return Incompatible;
7768   }
7769 
7770   // Conversions to Objective-C pointers.
7771   if (isa<ObjCObjectPointerType>(LHSType)) {
7772     // A* -> B*
7773     if (RHSType->isObjCObjectPointerType()) {
7774       Kind = CK_BitCast;
7775       Sema::AssignConvertType result =
7776         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7777       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7778           result == Compatible &&
7779           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7780         result = IncompatibleObjCWeakRef;
7781       return result;
7782     }
7783 
7784     // int or null -> A*
7785     if (RHSType->isIntegerType()) {
7786       Kind = CK_IntegralToPointer; // FIXME: null
7787       return IntToPointer;
7788     }
7789 
7790     // In general, C pointers are not compatible with ObjC object pointers,
7791     // with two exceptions:
7792     if (isa<PointerType>(RHSType)) {
7793       Kind = CK_CPointerToObjCPointerCast;
7794 
7795       //  - conversions from 'void*'
7796       if (RHSType->isVoidPointerType()) {
7797         return Compatible;
7798       }
7799 
7800       //  - conversions to 'Class' from its redefinition type
7801       if (LHSType->isObjCClassType() &&
7802           Context.hasSameType(RHSType,
7803                               Context.getObjCClassRedefinitionType())) {
7804         return Compatible;
7805       }
7806 
7807       return IncompatiblePointer;
7808     }
7809 
7810     // Only under strict condition T^ is compatible with an Objective-C pointer.
7811     if (RHSType->isBlockPointerType() &&
7812         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7813       if (ConvertRHS)
7814         maybeExtendBlockObject(RHS);
7815       Kind = CK_BlockPointerToObjCPointerCast;
7816       return Compatible;
7817     }
7818 
7819     return Incompatible;
7820   }
7821 
7822   // Conversions from pointers that are not covered by the above.
7823   if (isa<PointerType>(RHSType)) {
7824     // T* -> _Bool
7825     if (LHSType == Context.BoolTy) {
7826       Kind = CK_PointerToBoolean;
7827       return Compatible;
7828     }
7829 
7830     // T* -> int
7831     if (LHSType->isIntegerType()) {
7832       Kind = CK_PointerToIntegral;
7833       return PointerToInt;
7834     }
7835 
7836     return Incompatible;
7837   }
7838 
7839   // Conversions from Objective-C pointers that are not covered by the above.
7840   if (isa<ObjCObjectPointerType>(RHSType)) {
7841     // T* -> _Bool
7842     if (LHSType == Context.BoolTy) {
7843       Kind = CK_PointerToBoolean;
7844       return Compatible;
7845     }
7846 
7847     // T* -> int
7848     if (LHSType->isIntegerType()) {
7849       Kind = CK_PointerToIntegral;
7850       return PointerToInt;
7851     }
7852 
7853     return Incompatible;
7854   }
7855 
7856   // struct A -> struct B
7857   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7858     if (Context.typesAreCompatible(LHSType, RHSType)) {
7859       Kind = CK_NoOp;
7860       return Compatible;
7861     }
7862   }
7863 
7864   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7865     Kind = CK_IntToOCLSampler;
7866     return Compatible;
7867   }
7868 
7869   return Incompatible;
7870 }
7871 
7872 /// \brief Constructs a transparent union from an expression that is
7873 /// used to initialize the transparent union.
7874 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7875                                       ExprResult &EResult, QualType UnionType,
7876                                       FieldDecl *Field) {
7877   // Build an initializer list that designates the appropriate member
7878   // of the transparent union.
7879   Expr *E = EResult.get();
7880   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7881                                                    E, SourceLocation());
7882   Initializer->setType(UnionType);
7883   Initializer->setInitializedFieldInUnion(Field);
7884 
7885   // Build a compound literal constructing a value of the transparent
7886   // union type from this initializer list.
7887   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7888   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7889                                         VK_RValue, Initializer, false);
7890 }
7891 
7892 Sema::AssignConvertType
7893 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7894                                                ExprResult &RHS) {
7895   QualType RHSType = RHS.get()->getType();
7896 
7897   // If the ArgType is a Union type, we want to handle a potential
7898   // transparent_union GCC extension.
7899   const RecordType *UT = ArgType->getAsUnionType();
7900   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7901     return Incompatible;
7902 
7903   // The field to initialize within the transparent union.
7904   RecordDecl *UD = UT->getDecl();
7905   FieldDecl *InitField = nullptr;
7906   // It's compatible if the expression matches any of the fields.
7907   for (auto *it : UD->fields()) {
7908     if (it->getType()->isPointerType()) {
7909       // If the transparent union contains a pointer type, we allow:
7910       // 1) void pointer
7911       // 2) null pointer constant
7912       if (RHSType->isPointerType())
7913         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7914           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7915           InitField = it;
7916           break;
7917         }
7918 
7919       if (RHS.get()->isNullPointerConstant(Context,
7920                                            Expr::NPC_ValueDependentIsNull)) {
7921         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7922                                 CK_NullToPointer);
7923         InitField = it;
7924         break;
7925       }
7926     }
7927 
7928     CastKind Kind;
7929     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7930           == Compatible) {
7931       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7932       InitField = it;
7933       break;
7934     }
7935   }
7936 
7937   if (!InitField)
7938     return Incompatible;
7939 
7940   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7941   return Compatible;
7942 }
7943 
7944 Sema::AssignConvertType
7945 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7946                                        bool Diagnose,
7947                                        bool DiagnoseCFAudited,
7948                                        bool ConvertRHS) {
7949   // We need to be able to tell the caller whether we diagnosed a problem, if
7950   // they ask us to issue diagnostics.
7951   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7952 
7953   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7954   // we can't avoid *all* modifications at the moment, so we need some somewhere
7955   // to put the updated value.
7956   ExprResult LocalRHS = CallerRHS;
7957   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7958 
7959   if (getLangOpts().CPlusPlus) {
7960     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7961       // C++ 5.17p3: If the left operand is not of class type, the
7962       // expression is implicitly converted (C++ 4) to the
7963       // cv-unqualified type of the left operand.
7964       QualType RHSType = RHS.get()->getType();
7965       if (Diagnose) {
7966         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7967                                         AA_Assigning);
7968       } else {
7969         ImplicitConversionSequence ICS =
7970             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7971                                   /*SuppressUserConversions=*/false,
7972                                   /*AllowExplicit=*/false,
7973                                   /*InOverloadResolution=*/false,
7974                                   /*CStyle=*/false,
7975                                   /*AllowObjCWritebackConversion=*/false);
7976         if (ICS.isFailure())
7977           return Incompatible;
7978         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7979                                         ICS, AA_Assigning);
7980       }
7981       if (RHS.isInvalid())
7982         return Incompatible;
7983       Sema::AssignConvertType result = Compatible;
7984       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7985           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7986         result = IncompatibleObjCWeakRef;
7987       return result;
7988     }
7989 
7990     // FIXME: Currently, we fall through and treat C++ classes like C
7991     // structures.
7992     // FIXME: We also fall through for atomics; not sure what should
7993     // happen there, though.
7994   } else if (RHS.get()->getType() == Context.OverloadTy) {
7995     // As a set of extensions to C, we support overloading on functions. These
7996     // functions need to be resolved here.
7997     DeclAccessPair DAP;
7998     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7999             RHS.get(), LHSType, /*Complain=*/false, DAP))
8000       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8001     else
8002       return Incompatible;
8003   }
8004 
8005   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8006   // a null pointer constant.
8007   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8008        LHSType->isBlockPointerType()) &&
8009       RHS.get()->isNullPointerConstant(Context,
8010                                        Expr::NPC_ValueDependentIsNull)) {
8011     if (Diagnose || ConvertRHS) {
8012       CastKind Kind;
8013       CXXCastPath Path;
8014       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8015                              /*IgnoreBaseAccess=*/false, Diagnose);
8016       if (ConvertRHS)
8017         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8018     }
8019     return Compatible;
8020   }
8021 
8022   // This check seems unnatural, however it is necessary to ensure the proper
8023   // conversion of functions/arrays. If the conversion were done for all
8024   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8025   // expressions that suppress this implicit conversion (&, sizeof).
8026   //
8027   // Suppress this for references: C++ 8.5.3p5.
8028   if (!LHSType->isReferenceType()) {
8029     // FIXME: We potentially allocate here even if ConvertRHS is false.
8030     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8031     if (RHS.isInvalid())
8032       return Incompatible;
8033   }
8034 
8035   Expr *PRE = RHS.get()->IgnoreParenCasts();
8036   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8037     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8038     if (PDecl && !PDecl->hasDefinition()) {
8039       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8040       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8041     }
8042   }
8043 
8044   CastKind Kind;
8045   Sema::AssignConvertType result =
8046     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8047 
8048   // C99 6.5.16.1p2: The value of the right operand is converted to the
8049   // type of the assignment expression.
8050   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8051   // so that we can use references in built-in functions even in C.
8052   // The getNonReferenceType() call makes sure that the resulting expression
8053   // does not have reference type.
8054   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8055     QualType Ty = LHSType.getNonLValueExprType(Context);
8056     Expr *E = RHS.get();
8057 
8058     // Check for various Objective-C errors. If we are not reporting
8059     // diagnostics and just checking for errors, e.g., during overload
8060     // resolution, return Incompatible to indicate the failure.
8061     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8062         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8063                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8064       if (!Diagnose)
8065         return Incompatible;
8066     }
8067     if (getLangOpts().ObjC1 &&
8068         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8069                                            E->getType(), E, Diagnose) ||
8070          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8071       if (!Diagnose)
8072         return Incompatible;
8073       // Replace the expression with a corrected version and continue so we
8074       // can find further errors.
8075       RHS = E;
8076       return Compatible;
8077     }
8078 
8079     if (ConvertRHS)
8080       RHS = ImpCastExprToType(E, Ty, Kind);
8081   }
8082   return result;
8083 }
8084 
8085 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8086                                ExprResult &RHS) {
8087   Diag(Loc, diag::err_typecheck_invalid_operands)
8088     << LHS.get()->getType() << RHS.get()->getType()
8089     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8090   return QualType();
8091 }
8092 
8093 // Diagnose cases where a scalar was implicitly converted to a vector and
8094 // diagnose the underlying types. Otherwise, diagnose the error
8095 // as invalid vector logical operands for non-C++ cases.
8096 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8097                                             ExprResult &RHS) {
8098   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8099   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8100 
8101   bool LHSNatVec = LHSType->isVectorType();
8102   bool RHSNatVec = RHSType->isVectorType();
8103 
8104   if (!(LHSNatVec && RHSNatVec)) {
8105     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8106     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8107     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8108         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8109         << Vector->getSourceRange();
8110     return QualType();
8111   }
8112 
8113   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8114       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8115       << RHS.get()->getSourceRange();
8116 
8117   return QualType();
8118 }
8119 
8120 /// Try to convert a value of non-vector type to a vector type by converting
8121 /// the type to the element type of the vector and then performing a splat.
8122 /// If the language is OpenCL, we only use conversions that promote scalar
8123 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8124 /// for float->int.
8125 ///
8126 /// OpenCL V2.0 6.2.6.p2:
8127 /// An error shall occur if any scalar operand type has greater rank
8128 /// than the type of the vector element.
8129 ///
8130 /// \param scalar - if non-null, actually perform the conversions
8131 /// \return true if the operation fails (but without diagnosing the failure)
8132 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8133                                      QualType scalarTy,
8134                                      QualType vectorEltTy,
8135                                      QualType vectorTy,
8136                                      unsigned &DiagID) {
8137   // The conversion to apply to the scalar before splatting it,
8138   // if necessary.
8139   CastKind scalarCast = CK_NoOp;
8140 
8141   if (vectorEltTy->isIntegralType(S.Context)) {
8142     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8143         (scalarTy->isIntegerType() &&
8144          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8145       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8146       return true;
8147     }
8148     if (!scalarTy->isIntegralType(S.Context))
8149       return true;
8150     scalarCast = CK_IntegralCast;
8151   } else if (vectorEltTy->isRealFloatingType()) {
8152     if (scalarTy->isRealFloatingType()) {
8153       if (S.getLangOpts().OpenCL &&
8154           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8155         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8156         return true;
8157       }
8158       scalarCast = CK_FloatingCast;
8159     }
8160     else if (scalarTy->isIntegralType(S.Context))
8161       scalarCast = CK_IntegralToFloating;
8162     else
8163       return true;
8164   } else {
8165     return true;
8166   }
8167 
8168   // Adjust scalar if desired.
8169   if (scalar) {
8170     if (scalarCast != CK_NoOp)
8171       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8172     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8173   }
8174   return false;
8175 }
8176 
8177 /// Convert vector E to a vector with the same number of elements but different
8178 /// element type.
8179 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8180   const auto *VecTy = E->getType()->getAs<VectorType>();
8181   assert(VecTy && "Expression E must be a vector");
8182   QualType NewVecTy = S.Context.getVectorType(ElementType,
8183                                               VecTy->getNumElements(),
8184                                               VecTy->getVectorKind());
8185 
8186   // Look through the implicit cast. Return the subexpression if its type is
8187   // NewVecTy.
8188   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8189     if (ICE->getSubExpr()->getType() == NewVecTy)
8190       return ICE->getSubExpr();
8191 
8192   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8193   return S.ImpCastExprToType(E, NewVecTy, Cast);
8194 }
8195 
8196 /// Test if a (constant) integer Int can be casted to another integer type
8197 /// IntTy without losing precision.
8198 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8199                                       QualType OtherIntTy) {
8200   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8201 
8202   // Reject cases where the value of the Int is unknown as that would
8203   // possibly cause truncation, but accept cases where the scalar can be
8204   // demoted without loss of precision.
8205   llvm::APSInt Result;
8206   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8207   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8208   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8209   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8210 
8211   if (CstInt) {
8212     // If the scalar is constant and is of a higher order and has more active
8213     // bits that the vector element type, reject it.
8214     unsigned NumBits = IntSigned
8215                            ? (Result.isNegative() ? Result.getMinSignedBits()
8216                                                   : Result.getActiveBits())
8217                            : Result.getActiveBits();
8218     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8219       return true;
8220 
8221     // If the signedness of the scalar type and the vector element type
8222     // differs and the number of bits is greater than that of the vector
8223     // element reject it.
8224     return (IntSigned != OtherIntSigned &&
8225             NumBits > S.Context.getIntWidth(OtherIntTy));
8226   }
8227 
8228   // Reject cases where the value of the scalar is not constant and it's
8229   // order is greater than that of the vector element type.
8230   return (Order < 0);
8231 }
8232 
8233 /// Test if a (constant) integer Int can be casted to floating point type
8234 /// FloatTy without losing precision.
8235 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8236                                      QualType FloatTy) {
8237   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8238 
8239   // Determine if the integer constant can be expressed as a floating point
8240   // number of the appropriate type.
8241   llvm::APSInt Result;
8242   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8243   uint64_t Bits = 0;
8244   if (CstInt) {
8245     // Reject constants that would be truncated if they were converted to
8246     // the floating point type. Test by simple to/from conversion.
8247     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8248     //        could be avoided if there was a convertFromAPInt method
8249     //        which could signal back if implicit truncation occurred.
8250     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8251     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8252                            llvm::APFloat::rmTowardZero);
8253     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8254                              !IntTy->hasSignedIntegerRepresentation());
8255     bool Ignored = false;
8256     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8257                            &Ignored);
8258     if (Result != ConvertBack)
8259       return true;
8260   } else {
8261     // Reject types that cannot be fully encoded into the mantissa of
8262     // the float.
8263     Bits = S.Context.getTypeSize(IntTy);
8264     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8265         S.Context.getFloatTypeSemantics(FloatTy));
8266     if (Bits > FloatPrec)
8267       return true;
8268   }
8269 
8270   return false;
8271 }
8272 
8273 /// Attempt to convert and splat Scalar into a vector whose types matches
8274 /// Vector following GCC conversion rules. The rule is that implicit
8275 /// conversion can occur when Scalar can be casted to match Vector's element
8276 /// type without causing truncation of Scalar.
8277 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8278                                         ExprResult *Vector) {
8279   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8280   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8281   const VectorType *VT = VectorTy->getAs<VectorType>();
8282 
8283   assert(!isa<ExtVectorType>(VT) &&
8284          "ExtVectorTypes should not be handled here!");
8285 
8286   QualType VectorEltTy = VT->getElementType();
8287 
8288   // Reject cases where the vector element type or the scalar element type are
8289   // not integral or floating point types.
8290   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8291     return true;
8292 
8293   // The conversion to apply to the scalar before splatting it,
8294   // if necessary.
8295   CastKind ScalarCast = CK_NoOp;
8296 
8297   // Accept cases where the vector elements are integers and the scalar is
8298   // an integer.
8299   // FIXME: Notionally if the scalar was a floating point value with a precise
8300   //        integral representation, we could cast it to an appropriate integer
8301   //        type and then perform the rest of the checks here. GCC will perform
8302   //        this conversion in some cases as determined by the input language.
8303   //        We should accept it on a language independent basis.
8304   if (VectorEltTy->isIntegralType(S.Context) &&
8305       ScalarTy->isIntegralType(S.Context) &&
8306       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8307 
8308     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8309       return true;
8310 
8311     ScalarCast = CK_IntegralCast;
8312   } else if (VectorEltTy->isRealFloatingType()) {
8313     if (ScalarTy->isRealFloatingType()) {
8314 
8315       // Reject cases where the scalar type is not a constant and has a higher
8316       // Order than the vector element type.
8317       llvm::APFloat Result(0.0);
8318       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8319       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8320       if (!CstScalar && Order < 0)
8321         return true;
8322 
8323       // If the scalar cannot be safely casted to the vector element type,
8324       // reject it.
8325       if (CstScalar) {
8326         bool Truncated = false;
8327         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8328                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8329         if (Truncated)
8330           return true;
8331       }
8332 
8333       ScalarCast = CK_FloatingCast;
8334     } else if (ScalarTy->isIntegralType(S.Context)) {
8335       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8336         return true;
8337 
8338       ScalarCast = CK_IntegralToFloating;
8339     } else
8340       return true;
8341   }
8342 
8343   // Adjust scalar if desired.
8344   if (Scalar) {
8345     if (ScalarCast != CK_NoOp)
8346       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8347     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8348   }
8349   return false;
8350 }
8351 
8352 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8353                                    SourceLocation Loc, bool IsCompAssign,
8354                                    bool AllowBothBool,
8355                                    bool AllowBoolConversions) {
8356   if (!IsCompAssign) {
8357     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8358     if (LHS.isInvalid())
8359       return QualType();
8360   }
8361   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8362   if (RHS.isInvalid())
8363     return QualType();
8364 
8365   // For conversion purposes, we ignore any qualifiers.
8366   // For example, "const float" and "float" are equivalent.
8367   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8368   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8369 
8370   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8371   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8372   assert(LHSVecType || RHSVecType);
8373 
8374   // AltiVec-style "vector bool op vector bool" combinations are allowed
8375   // for some operators but not others.
8376   if (!AllowBothBool &&
8377       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8378       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8379     return InvalidOperands(Loc, LHS, RHS);
8380 
8381   // If the vector types are identical, return.
8382   if (Context.hasSameType(LHSType, RHSType))
8383     return LHSType;
8384 
8385   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8386   if (LHSVecType && RHSVecType &&
8387       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8388     if (isa<ExtVectorType>(LHSVecType)) {
8389       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8390       return LHSType;
8391     }
8392 
8393     if (!IsCompAssign)
8394       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8395     return RHSType;
8396   }
8397 
8398   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8399   // can be mixed, with the result being the non-bool type.  The non-bool
8400   // operand must have integer element type.
8401   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8402       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8403       (Context.getTypeSize(LHSVecType->getElementType()) ==
8404        Context.getTypeSize(RHSVecType->getElementType()))) {
8405     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8406         LHSVecType->getElementType()->isIntegerType() &&
8407         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8408       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8409       return LHSType;
8410     }
8411     if (!IsCompAssign &&
8412         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8413         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8414         RHSVecType->getElementType()->isIntegerType()) {
8415       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8416       return RHSType;
8417     }
8418   }
8419 
8420   // If there's a vector type and a scalar, try to convert the scalar to
8421   // the vector element type and splat.
8422   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8423   if (!RHSVecType) {
8424     if (isa<ExtVectorType>(LHSVecType)) {
8425       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8426                                     LHSVecType->getElementType(), LHSType,
8427                                     DiagID))
8428         return LHSType;
8429     } else {
8430       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8431         return LHSType;
8432     }
8433   }
8434   if (!LHSVecType) {
8435     if (isa<ExtVectorType>(RHSVecType)) {
8436       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8437                                     LHSType, RHSVecType->getElementType(),
8438                                     RHSType, DiagID))
8439         return RHSType;
8440     } else {
8441       if (LHS.get()->getValueKind() == VK_LValue ||
8442           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8443         return RHSType;
8444     }
8445   }
8446 
8447   // FIXME: The code below also handles conversion between vectors and
8448   // non-scalars, we should break this down into fine grained specific checks
8449   // and emit proper diagnostics.
8450   QualType VecType = LHSVecType ? LHSType : RHSType;
8451   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8452   QualType OtherType = LHSVecType ? RHSType : LHSType;
8453   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8454   if (isLaxVectorConversion(OtherType, VecType)) {
8455     // If we're allowing lax vector conversions, only the total (data) size
8456     // needs to be the same. For non compound assignment, if one of the types is
8457     // scalar, the result is always the vector type.
8458     if (!IsCompAssign) {
8459       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8460       return VecType;
8461     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8462     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8463     // type. Note that this is already done by non-compound assignments in
8464     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8465     // <1 x T> -> T. The result is also a vector type.
8466     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8467                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8468       ExprResult *RHSExpr = &RHS;
8469       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8470       return VecType;
8471     }
8472   }
8473 
8474   // Okay, the expression is invalid.
8475 
8476   // If there's a non-vector, non-real operand, diagnose that.
8477   if ((!RHSVecType && !RHSType->isRealType()) ||
8478       (!LHSVecType && !LHSType->isRealType())) {
8479     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8480       << LHSType << RHSType
8481       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8482     return QualType();
8483   }
8484 
8485   // OpenCL V1.1 6.2.6.p1:
8486   // If the operands are of more than one vector type, then an error shall
8487   // occur. Implicit conversions between vector types are not permitted, per
8488   // section 6.2.1.
8489   if (getLangOpts().OpenCL &&
8490       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8491       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8492     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8493                                                            << RHSType;
8494     return QualType();
8495   }
8496 
8497 
8498   // If there is a vector type that is not a ExtVector and a scalar, we reach
8499   // this point if scalar could not be converted to the vector's element type
8500   // without truncation.
8501   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8502       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8503     QualType Scalar = LHSVecType ? RHSType : LHSType;
8504     QualType Vector = LHSVecType ? LHSType : RHSType;
8505     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8506     Diag(Loc,
8507          diag::err_typecheck_vector_not_convertable_implict_truncation)
8508         << ScalarOrVector << Scalar << Vector;
8509 
8510     return QualType();
8511   }
8512 
8513   // Otherwise, use the generic diagnostic.
8514   Diag(Loc, DiagID)
8515     << LHSType << RHSType
8516     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8517   return QualType();
8518 }
8519 
8520 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8521 // expression.  These are mainly cases where the null pointer is used as an
8522 // integer instead of a pointer.
8523 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8524                                 SourceLocation Loc, bool IsCompare) {
8525   // The canonical way to check for a GNU null is with isNullPointerConstant,
8526   // but we use a bit of a hack here for speed; this is a relatively
8527   // hot path, and isNullPointerConstant is slow.
8528   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8529   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8530 
8531   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8532 
8533   // Avoid analyzing cases where the result will either be invalid (and
8534   // diagnosed as such) or entirely valid and not something to warn about.
8535   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8536       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8537     return;
8538 
8539   // Comparison operations would not make sense with a null pointer no matter
8540   // what the other expression is.
8541   if (!IsCompare) {
8542     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8543         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8544         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8545     return;
8546   }
8547 
8548   // The rest of the operations only make sense with a null pointer
8549   // if the other expression is a pointer.
8550   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8551       NonNullType->canDecayToPointerType())
8552     return;
8553 
8554   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8555       << LHSNull /* LHS is NULL */ << NonNullType
8556       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8557 }
8558 
8559 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8560                                                ExprResult &RHS,
8561                                                SourceLocation Loc, bool IsDiv) {
8562   // Check for division/remainder by zero.
8563   llvm::APSInt RHSValue;
8564   if (!RHS.get()->isValueDependent() &&
8565       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8566     S.DiagRuntimeBehavior(Loc, RHS.get(),
8567                           S.PDiag(diag::warn_remainder_division_by_zero)
8568                             << IsDiv << RHS.get()->getSourceRange());
8569 }
8570 
8571 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8572                                            SourceLocation Loc,
8573                                            bool IsCompAssign, bool IsDiv) {
8574   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8575 
8576   if (LHS.get()->getType()->isVectorType() ||
8577       RHS.get()->getType()->isVectorType())
8578     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8579                                /*AllowBothBool*/getLangOpts().AltiVec,
8580                                /*AllowBoolConversions*/false);
8581 
8582   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8583   if (LHS.isInvalid() || RHS.isInvalid())
8584     return QualType();
8585 
8586 
8587   if (compType.isNull() || !compType->isArithmeticType())
8588     return InvalidOperands(Loc, LHS, RHS);
8589   if (IsDiv)
8590     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8591   return compType;
8592 }
8593 
8594 QualType Sema::CheckRemainderOperands(
8595   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8596   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8597 
8598   if (LHS.get()->getType()->isVectorType() ||
8599       RHS.get()->getType()->isVectorType()) {
8600     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8601         RHS.get()->getType()->hasIntegerRepresentation())
8602       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8603                                  /*AllowBothBool*/getLangOpts().AltiVec,
8604                                  /*AllowBoolConversions*/false);
8605     return InvalidOperands(Loc, LHS, RHS);
8606   }
8607 
8608   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8609   if (LHS.isInvalid() || RHS.isInvalid())
8610     return QualType();
8611 
8612   if (compType.isNull() || !compType->isIntegerType())
8613     return InvalidOperands(Loc, LHS, RHS);
8614   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8615   return compType;
8616 }
8617 
8618 /// \brief Diagnose invalid arithmetic on two void pointers.
8619 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8620                                                 Expr *LHSExpr, Expr *RHSExpr) {
8621   S.Diag(Loc, S.getLangOpts().CPlusPlus
8622                 ? diag::err_typecheck_pointer_arith_void_type
8623                 : diag::ext_gnu_void_ptr)
8624     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8625                             << RHSExpr->getSourceRange();
8626 }
8627 
8628 /// \brief Diagnose invalid arithmetic on a void pointer.
8629 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8630                                             Expr *Pointer) {
8631   S.Diag(Loc, S.getLangOpts().CPlusPlus
8632                 ? diag::err_typecheck_pointer_arith_void_type
8633                 : diag::ext_gnu_void_ptr)
8634     << 0 /* one pointer */ << Pointer->getSourceRange();
8635 }
8636 
8637 /// \brief Diagnose invalid arithmetic on a null pointer.
8638 ///
8639 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8640 /// idiom, which we recognize as a GNU extension.
8641 ///
8642 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8643                                             Expr *Pointer, bool IsGNUIdiom) {
8644   if (IsGNUIdiom)
8645     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8646       << Pointer->getSourceRange();
8647   else
8648     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8649       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8650 }
8651 
8652 /// \brief Diagnose invalid arithmetic on two function pointers.
8653 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8654                                                     Expr *LHS, Expr *RHS) {
8655   assert(LHS->getType()->isAnyPointerType());
8656   assert(RHS->getType()->isAnyPointerType());
8657   S.Diag(Loc, S.getLangOpts().CPlusPlus
8658                 ? diag::err_typecheck_pointer_arith_function_type
8659                 : diag::ext_gnu_ptr_func_arith)
8660     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8661     // We only show the second type if it differs from the first.
8662     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8663                                                    RHS->getType())
8664     << RHS->getType()->getPointeeType()
8665     << LHS->getSourceRange() << RHS->getSourceRange();
8666 }
8667 
8668 /// \brief Diagnose invalid arithmetic on a function pointer.
8669 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8670                                                 Expr *Pointer) {
8671   assert(Pointer->getType()->isAnyPointerType());
8672   S.Diag(Loc, S.getLangOpts().CPlusPlus
8673                 ? diag::err_typecheck_pointer_arith_function_type
8674                 : diag::ext_gnu_ptr_func_arith)
8675     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8676     << 0 /* one pointer, so only one type */
8677     << Pointer->getSourceRange();
8678 }
8679 
8680 /// \brief Emit error if Operand is incomplete pointer type
8681 ///
8682 /// \returns True if pointer has incomplete type
8683 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8684                                                  Expr *Operand) {
8685   QualType ResType = Operand->getType();
8686   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8687     ResType = ResAtomicType->getValueType();
8688 
8689   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8690   QualType PointeeTy = ResType->getPointeeType();
8691   return S.RequireCompleteType(Loc, PointeeTy,
8692                                diag::err_typecheck_arithmetic_incomplete_type,
8693                                PointeeTy, Operand->getSourceRange());
8694 }
8695 
8696 /// \brief Check the validity of an arithmetic pointer operand.
8697 ///
8698 /// If the operand has pointer type, this code will check for pointer types
8699 /// which are invalid in arithmetic operations. These will be diagnosed
8700 /// appropriately, including whether or not the use is supported as an
8701 /// extension.
8702 ///
8703 /// \returns True when the operand is valid to use (even if as an extension).
8704 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8705                                             Expr *Operand) {
8706   QualType ResType = Operand->getType();
8707   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8708     ResType = ResAtomicType->getValueType();
8709 
8710   if (!ResType->isAnyPointerType()) return true;
8711 
8712   QualType PointeeTy = ResType->getPointeeType();
8713   if (PointeeTy->isVoidType()) {
8714     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8715     return !S.getLangOpts().CPlusPlus;
8716   }
8717   if (PointeeTy->isFunctionType()) {
8718     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8719     return !S.getLangOpts().CPlusPlus;
8720   }
8721 
8722   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8723 
8724   return true;
8725 }
8726 
8727 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8728 /// operands.
8729 ///
8730 /// This routine will diagnose any invalid arithmetic on pointer operands much
8731 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8732 /// for emitting a single diagnostic even for operations where both LHS and RHS
8733 /// are (potentially problematic) pointers.
8734 ///
8735 /// \returns True when the operand is valid to use (even if as an extension).
8736 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8737                                                 Expr *LHSExpr, Expr *RHSExpr) {
8738   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8739   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8740   if (!isLHSPointer && !isRHSPointer) return true;
8741 
8742   QualType LHSPointeeTy, RHSPointeeTy;
8743   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8744   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8745 
8746   // if both are pointers check if operation is valid wrt address spaces
8747   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8748     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8749     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8750     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8751       S.Diag(Loc,
8752              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8753           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8754           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8755       return false;
8756     }
8757   }
8758 
8759   // Check for arithmetic on pointers to incomplete types.
8760   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8761   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8762   if (isLHSVoidPtr || isRHSVoidPtr) {
8763     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8764     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8765     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8766 
8767     return !S.getLangOpts().CPlusPlus;
8768   }
8769 
8770   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8771   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8772   if (isLHSFuncPtr || isRHSFuncPtr) {
8773     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8774     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8775                                                                 RHSExpr);
8776     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8777 
8778     return !S.getLangOpts().CPlusPlus;
8779   }
8780 
8781   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8782     return false;
8783   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8784     return false;
8785 
8786   return true;
8787 }
8788 
8789 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8790 /// literal.
8791 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8792                                   Expr *LHSExpr, Expr *RHSExpr) {
8793   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8794   Expr* IndexExpr = RHSExpr;
8795   if (!StrExpr) {
8796     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8797     IndexExpr = LHSExpr;
8798   }
8799 
8800   bool IsStringPlusInt = StrExpr &&
8801       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8802   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8803     return;
8804 
8805   llvm::APSInt index;
8806   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8807     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8808     if (index.isNonNegative() &&
8809         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8810                               index.isUnsigned()))
8811       return;
8812   }
8813 
8814   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8815   Self.Diag(OpLoc, diag::warn_string_plus_int)
8816       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8817 
8818   // Only print a fixit for "str" + int, not for int + "str".
8819   if (IndexExpr == RHSExpr) {
8820     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8821     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8822         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8823         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8824         << FixItHint::CreateInsertion(EndLoc, "]");
8825   } else
8826     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8827 }
8828 
8829 /// \brief Emit a warning when adding a char literal to a string.
8830 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8831                                    Expr *LHSExpr, Expr *RHSExpr) {
8832   const Expr *StringRefExpr = LHSExpr;
8833   const CharacterLiteral *CharExpr =
8834       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8835 
8836   if (!CharExpr) {
8837     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8838     StringRefExpr = RHSExpr;
8839   }
8840 
8841   if (!CharExpr || !StringRefExpr)
8842     return;
8843 
8844   const QualType StringType = StringRefExpr->getType();
8845 
8846   // Return if not a PointerType.
8847   if (!StringType->isAnyPointerType())
8848     return;
8849 
8850   // Return if not a CharacterType.
8851   if (!StringType->getPointeeType()->isAnyCharacterType())
8852     return;
8853 
8854   ASTContext &Ctx = Self.getASTContext();
8855   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8856 
8857   const QualType CharType = CharExpr->getType();
8858   if (!CharType->isAnyCharacterType() &&
8859       CharType->isIntegerType() &&
8860       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8861     Self.Diag(OpLoc, diag::warn_string_plus_char)
8862         << DiagRange << Ctx.CharTy;
8863   } else {
8864     Self.Diag(OpLoc, diag::warn_string_plus_char)
8865         << DiagRange << CharExpr->getType();
8866   }
8867 
8868   // Only print a fixit for str + char, not for char + str.
8869   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8870     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8871     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8872         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8873         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8874         << FixItHint::CreateInsertion(EndLoc, "]");
8875   } else {
8876     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8877   }
8878 }
8879 
8880 /// \brief Emit error when two pointers are incompatible.
8881 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8882                                            Expr *LHSExpr, Expr *RHSExpr) {
8883   assert(LHSExpr->getType()->isAnyPointerType());
8884   assert(RHSExpr->getType()->isAnyPointerType());
8885   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8886     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8887     << RHSExpr->getSourceRange();
8888 }
8889 
8890 // C99 6.5.6
8891 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8892                                      SourceLocation Loc, BinaryOperatorKind Opc,
8893                                      QualType* CompLHSTy) {
8894   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8895 
8896   if (LHS.get()->getType()->isVectorType() ||
8897       RHS.get()->getType()->isVectorType()) {
8898     QualType compType = CheckVectorOperands(
8899         LHS, RHS, Loc, CompLHSTy,
8900         /*AllowBothBool*/getLangOpts().AltiVec,
8901         /*AllowBoolConversions*/getLangOpts().ZVector);
8902     if (CompLHSTy) *CompLHSTy = compType;
8903     return compType;
8904   }
8905 
8906   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8907   if (LHS.isInvalid() || RHS.isInvalid())
8908     return QualType();
8909 
8910   // Diagnose "string literal" '+' int and string '+' "char literal".
8911   if (Opc == BO_Add) {
8912     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8913     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8914   }
8915 
8916   // handle the common case first (both operands are arithmetic).
8917   if (!compType.isNull() && compType->isArithmeticType()) {
8918     if (CompLHSTy) *CompLHSTy = compType;
8919     return compType;
8920   }
8921 
8922   // Type-checking.  Ultimately the pointer's going to be in PExp;
8923   // note that we bias towards the LHS being the pointer.
8924   Expr *PExp = LHS.get(), *IExp = RHS.get();
8925 
8926   bool isObjCPointer;
8927   if (PExp->getType()->isPointerType()) {
8928     isObjCPointer = false;
8929   } else if (PExp->getType()->isObjCObjectPointerType()) {
8930     isObjCPointer = true;
8931   } else {
8932     std::swap(PExp, IExp);
8933     if (PExp->getType()->isPointerType()) {
8934       isObjCPointer = false;
8935     } else if (PExp->getType()->isObjCObjectPointerType()) {
8936       isObjCPointer = true;
8937     } else {
8938       return InvalidOperands(Loc, LHS, RHS);
8939     }
8940   }
8941   assert(PExp->getType()->isAnyPointerType());
8942 
8943   if (!IExp->getType()->isIntegerType())
8944     return InvalidOperands(Loc, LHS, RHS);
8945 
8946   // Adding to a null pointer results in undefined behavior.
8947   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
8948           Context, Expr::NPC_ValueDependentIsNotNull)) {
8949     // In C++ adding zero to a null pointer is defined.
8950     llvm::APSInt KnownVal;
8951     if (!getLangOpts().CPlusPlus ||
8952         (!IExp->isValueDependent() &&
8953          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
8954       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
8955       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
8956           Context, BO_Add, PExp, IExp);
8957       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
8958     }
8959   }
8960 
8961   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8962     return QualType();
8963 
8964   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8965     return QualType();
8966 
8967   // Check array bounds for pointer arithemtic
8968   CheckArrayAccess(PExp, IExp);
8969 
8970   if (CompLHSTy) {
8971     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8972     if (LHSTy.isNull()) {
8973       LHSTy = LHS.get()->getType();
8974       if (LHSTy->isPromotableIntegerType())
8975         LHSTy = Context.getPromotedIntegerType(LHSTy);
8976     }
8977     *CompLHSTy = LHSTy;
8978   }
8979 
8980   return PExp->getType();
8981 }
8982 
8983 // C99 6.5.6
8984 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8985                                         SourceLocation Loc,
8986                                         QualType* CompLHSTy) {
8987   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8988 
8989   if (LHS.get()->getType()->isVectorType() ||
8990       RHS.get()->getType()->isVectorType()) {
8991     QualType compType = CheckVectorOperands(
8992         LHS, RHS, Loc, CompLHSTy,
8993         /*AllowBothBool*/getLangOpts().AltiVec,
8994         /*AllowBoolConversions*/getLangOpts().ZVector);
8995     if (CompLHSTy) *CompLHSTy = compType;
8996     return compType;
8997   }
8998 
8999   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9000   if (LHS.isInvalid() || RHS.isInvalid())
9001     return QualType();
9002 
9003   // Enforce type constraints: C99 6.5.6p3.
9004 
9005   // Handle the common case first (both operands are arithmetic).
9006   if (!compType.isNull() && compType->isArithmeticType()) {
9007     if (CompLHSTy) *CompLHSTy = compType;
9008     return compType;
9009   }
9010 
9011   // Either ptr - int   or   ptr - ptr.
9012   if (LHS.get()->getType()->isAnyPointerType()) {
9013     QualType lpointee = LHS.get()->getType()->getPointeeType();
9014 
9015     // Diagnose bad cases where we step over interface counts.
9016     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9017         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9018       return QualType();
9019 
9020     // The result type of a pointer-int computation is the pointer type.
9021     if (RHS.get()->getType()->isIntegerType()) {
9022       // Subtracting from a null pointer should produce a warning.
9023       // The last argument to the diagnose call says this doesn't match the
9024       // GNU int-to-pointer idiom.
9025       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9026                                            Expr::NPC_ValueDependentIsNotNull)) {
9027         // In C++ adding zero to a null pointer is defined.
9028         llvm::APSInt KnownVal;
9029         if (!getLangOpts().CPlusPlus ||
9030             (!RHS.get()->isValueDependent() &&
9031              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9032           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9033         }
9034       }
9035 
9036       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9037         return QualType();
9038 
9039       // Check array bounds for pointer arithemtic
9040       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9041                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9042 
9043       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9044       return LHS.get()->getType();
9045     }
9046 
9047     // Handle pointer-pointer subtractions.
9048     if (const PointerType *RHSPTy
9049           = RHS.get()->getType()->getAs<PointerType>()) {
9050       QualType rpointee = RHSPTy->getPointeeType();
9051 
9052       if (getLangOpts().CPlusPlus) {
9053         // Pointee types must be the same: C++ [expr.add]
9054         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9055           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9056         }
9057       } else {
9058         // Pointee types must be compatible C99 6.5.6p3
9059         if (!Context.typesAreCompatible(
9060                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9061                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9062           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9063           return QualType();
9064         }
9065       }
9066 
9067       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9068                                                LHS.get(), RHS.get()))
9069         return QualType();
9070 
9071       // FIXME: Add warnings for nullptr - ptr.
9072 
9073       // The pointee type may have zero size.  As an extension, a structure or
9074       // union may have zero size or an array may have zero length.  In this
9075       // case subtraction does not make sense.
9076       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9077         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9078         if (ElementSize.isZero()) {
9079           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9080             << rpointee.getUnqualifiedType()
9081             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9082         }
9083       }
9084 
9085       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9086       return Context.getPointerDiffType();
9087     }
9088   }
9089 
9090   return InvalidOperands(Loc, LHS, RHS);
9091 }
9092 
9093 static bool isScopedEnumerationType(QualType T) {
9094   if (const EnumType *ET = T->getAs<EnumType>())
9095     return ET->getDecl()->isScoped();
9096   return false;
9097 }
9098 
9099 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9100                                    SourceLocation Loc, BinaryOperatorKind Opc,
9101                                    QualType LHSType) {
9102   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9103   // so skip remaining warnings as we don't want to modify values within Sema.
9104   if (S.getLangOpts().OpenCL)
9105     return;
9106 
9107   llvm::APSInt Right;
9108   // Check right/shifter operand
9109   if (RHS.get()->isValueDependent() ||
9110       !RHS.get()->EvaluateAsInt(Right, S.Context))
9111     return;
9112 
9113   if (Right.isNegative()) {
9114     S.DiagRuntimeBehavior(Loc, RHS.get(),
9115                           S.PDiag(diag::warn_shift_negative)
9116                             << RHS.get()->getSourceRange());
9117     return;
9118   }
9119   llvm::APInt LeftBits(Right.getBitWidth(),
9120                        S.Context.getTypeSize(LHS.get()->getType()));
9121   if (Right.uge(LeftBits)) {
9122     S.DiagRuntimeBehavior(Loc, RHS.get(),
9123                           S.PDiag(diag::warn_shift_gt_typewidth)
9124                             << RHS.get()->getSourceRange());
9125     return;
9126   }
9127   if (Opc != BO_Shl)
9128     return;
9129 
9130   // When left shifting an ICE which is signed, we can check for overflow which
9131   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9132   // integers have defined behavior modulo one more than the maximum value
9133   // representable in the result type, so never warn for those.
9134   llvm::APSInt Left;
9135   if (LHS.get()->isValueDependent() ||
9136       LHSType->hasUnsignedIntegerRepresentation() ||
9137       !LHS.get()->EvaluateAsInt(Left, S.Context))
9138     return;
9139 
9140   // If LHS does not have a signed type and non-negative value
9141   // then, the behavior is undefined. Warn about it.
9142   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9143     S.DiagRuntimeBehavior(Loc, LHS.get(),
9144                           S.PDiag(diag::warn_shift_lhs_negative)
9145                             << LHS.get()->getSourceRange());
9146     return;
9147   }
9148 
9149   llvm::APInt ResultBits =
9150       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9151   if (LeftBits.uge(ResultBits))
9152     return;
9153   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9154   Result = Result.shl(Right);
9155 
9156   // Print the bit representation of the signed integer as an unsigned
9157   // hexadecimal number.
9158   SmallString<40> HexResult;
9159   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9160 
9161   // If we are only missing a sign bit, this is less likely to result in actual
9162   // bugs -- if the result is cast back to an unsigned type, it will have the
9163   // expected value. Thus we place this behind a different warning that can be
9164   // turned off separately if needed.
9165   if (LeftBits == ResultBits - 1) {
9166     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9167         << HexResult << LHSType
9168         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9169     return;
9170   }
9171 
9172   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9173     << HexResult.str() << Result.getMinSignedBits() << LHSType
9174     << Left.getBitWidth() << LHS.get()->getSourceRange()
9175     << RHS.get()->getSourceRange();
9176 }
9177 
9178 /// \brief Return the resulting type when a vector is shifted
9179 ///        by a scalar or vector shift amount.
9180 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9181                                  SourceLocation Loc, bool IsCompAssign) {
9182   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9183   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9184       !LHS.get()->getType()->isVectorType()) {
9185     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9186       << RHS.get()->getType() << LHS.get()->getType()
9187       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9188     return QualType();
9189   }
9190 
9191   if (!IsCompAssign) {
9192     LHS = S.UsualUnaryConversions(LHS.get());
9193     if (LHS.isInvalid()) return QualType();
9194   }
9195 
9196   RHS = S.UsualUnaryConversions(RHS.get());
9197   if (RHS.isInvalid()) return QualType();
9198 
9199   QualType LHSType = LHS.get()->getType();
9200   // Note that LHS might be a scalar because the routine calls not only in
9201   // OpenCL case.
9202   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9203   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9204 
9205   // Note that RHS might not be a vector.
9206   QualType RHSType = RHS.get()->getType();
9207   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9208   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9209 
9210   // The operands need to be integers.
9211   if (!LHSEleType->isIntegerType()) {
9212     S.Diag(Loc, diag::err_typecheck_expect_int)
9213       << LHS.get()->getType() << LHS.get()->getSourceRange();
9214     return QualType();
9215   }
9216 
9217   if (!RHSEleType->isIntegerType()) {
9218     S.Diag(Loc, diag::err_typecheck_expect_int)
9219       << RHS.get()->getType() << RHS.get()->getSourceRange();
9220     return QualType();
9221   }
9222 
9223   if (!LHSVecTy) {
9224     assert(RHSVecTy);
9225     if (IsCompAssign)
9226       return RHSType;
9227     if (LHSEleType != RHSEleType) {
9228       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9229       LHSEleType = RHSEleType;
9230     }
9231     QualType VecTy =
9232         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9233     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9234     LHSType = VecTy;
9235   } else if (RHSVecTy) {
9236     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9237     // are applied component-wise. So if RHS is a vector, then ensure
9238     // that the number of elements is the same as LHS...
9239     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9240       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9241         << LHS.get()->getType() << RHS.get()->getType()
9242         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9243       return QualType();
9244     }
9245     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9246       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9247       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9248       if (LHSBT != RHSBT &&
9249           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9250         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9251             << LHS.get()->getType() << RHS.get()->getType()
9252             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9253       }
9254     }
9255   } else {
9256     // ...else expand RHS to match the number of elements in LHS.
9257     QualType VecTy =
9258       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9259     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9260   }
9261 
9262   return LHSType;
9263 }
9264 
9265 // C99 6.5.7
9266 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9267                                   SourceLocation Loc, BinaryOperatorKind Opc,
9268                                   bool IsCompAssign) {
9269   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9270 
9271   // Vector shifts promote their scalar inputs to vector type.
9272   if (LHS.get()->getType()->isVectorType() ||
9273       RHS.get()->getType()->isVectorType()) {
9274     if (LangOpts.ZVector) {
9275       // The shift operators for the z vector extensions work basically
9276       // like general shifts, except that neither the LHS nor the RHS is
9277       // allowed to be a "vector bool".
9278       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9279         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9280           return InvalidOperands(Loc, LHS, RHS);
9281       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9282         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9283           return InvalidOperands(Loc, LHS, RHS);
9284     }
9285     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9286   }
9287 
9288   // Shifts don't perform usual arithmetic conversions, they just do integer
9289   // promotions on each operand. C99 6.5.7p3
9290 
9291   // For the LHS, do usual unary conversions, but then reset them away
9292   // if this is a compound assignment.
9293   ExprResult OldLHS = LHS;
9294   LHS = UsualUnaryConversions(LHS.get());
9295   if (LHS.isInvalid())
9296     return QualType();
9297   QualType LHSType = LHS.get()->getType();
9298   if (IsCompAssign) LHS = OldLHS;
9299 
9300   // The RHS is simpler.
9301   RHS = UsualUnaryConversions(RHS.get());
9302   if (RHS.isInvalid())
9303     return QualType();
9304   QualType RHSType = RHS.get()->getType();
9305 
9306   // C99 6.5.7p2: Each of the operands shall have integer type.
9307   if (!LHSType->hasIntegerRepresentation() ||
9308       !RHSType->hasIntegerRepresentation())
9309     return InvalidOperands(Loc, LHS, RHS);
9310 
9311   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9312   // hasIntegerRepresentation() above instead of this.
9313   if (isScopedEnumerationType(LHSType) ||
9314       isScopedEnumerationType(RHSType)) {
9315     return InvalidOperands(Loc, LHS, RHS);
9316   }
9317   // Sanity-check shift operands
9318   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9319 
9320   // "The type of the result is that of the promoted left operand."
9321   return LHSType;
9322 }
9323 
9324 /// If two different enums are compared, raise a warning.
9325 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9326                                 Expr *RHS) {
9327   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9328   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9329 
9330   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9331   if (!LHSEnumType)
9332     return;
9333   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9334   if (!RHSEnumType)
9335     return;
9336 
9337   // Ignore anonymous enums.
9338   if (!LHSEnumType->getDecl()->getIdentifier() &&
9339       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9340     return;
9341   if (!RHSEnumType->getDecl()->getIdentifier() &&
9342       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9343     return;
9344 
9345   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9346     return;
9347 
9348   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9349       << LHSStrippedType << RHSStrippedType
9350       << LHS->getSourceRange() << RHS->getSourceRange();
9351 }
9352 
9353 /// \brief Diagnose bad pointer comparisons.
9354 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9355                                               ExprResult &LHS, ExprResult &RHS,
9356                                               bool IsError) {
9357   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9358                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9359     << LHS.get()->getType() << RHS.get()->getType()
9360     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9361 }
9362 
9363 /// \brief Returns false if the pointers are converted to a composite type,
9364 /// true otherwise.
9365 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9366                                            ExprResult &LHS, ExprResult &RHS) {
9367   // C++ [expr.rel]p2:
9368   //   [...] Pointer conversions (4.10) and qualification
9369   //   conversions (4.4) are performed on pointer operands (or on
9370   //   a pointer operand and a null pointer constant) to bring
9371   //   them to their composite pointer type. [...]
9372   //
9373   // C++ [expr.eq]p1 uses the same notion for (in)equality
9374   // comparisons of pointers.
9375 
9376   QualType LHSType = LHS.get()->getType();
9377   QualType RHSType = RHS.get()->getType();
9378   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9379          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9380 
9381   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9382   if (T.isNull()) {
9383     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9384         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9385       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9386     else
9387       S.InvalidOperands(Loc, LHS, RHS);
9388     return true;
9389   }
9390 
9391   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9392   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9393   return false;
9394 }
9395 
9396 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9397                                                     ExprResult &LHS,
9398                                                     ExprResult &RHS,
9399                                                     bool IsError) {
9400   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9401                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9402     << LHS.get()->getType() << RHS.get()->getType()
9403     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9404 }
9405 
9406 static bool isObjCObjectLiteral(ExprResult &E) {
9407   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9408   case Stmt::ObjCArrayLiteralClass:
9409   case Stmt::ObjCDictionaryLiteralClass:
9410   case Stmt::ObjCStringLiteralClass:
9411   case Stmt::ObjCBoxedExprClass:
9412     return true;
9413   default:
9414     // Note that ObjCBoolLiteral is NOT an object literal!
9415     return false;
9416   }
9417 }
9418 
9419 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9420   const ObjCObjectPointerType *Type =
9421     LHS->getType()->getAs<ObjCObjectPointerType>();
9422 
9423   // If this is not actually an Objective-C object, bail out.
9424   if (!Type)
9425     return false;
9426 
9427   // Get the LHS object's interface type.
9428   QualType InterfaceType = Type->getPointeeType();
9429 
9430   // If the RHS isn't an Objective-C object, bail out.
9431   if (!RHS->getType()->isObjCObjectPointerType())
9432     return false;
9433 
9434   // Try to find the -isEqual: method.
9435   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9436   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9437                                                       InterfaceType,
9438                                                       /*instance=*/true);
9439   if (!Method) {
9440     if (Type->isObjCIdType()) {
9441       // For 'id', just check the global pool.
9442       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9443                                                   /*receiverId=*/true);
9444     } else {
9445       // Check protocols.
9446       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9447                                              /*instance=*/true);
9448     }
9449   }
9450 
9451   if (!Method)
9452     return false;
9453 
9454   QualType T = Method->parameters()[0]->getType();
9455   if (!T->isObjCObjectPointerType())
9456     return false;
9457 
9458   QualType R = Method->getReturnType();
9459   if (!R->isScalarType())
9460     return false;
9461 
9462   return true;
9463 }
9464 
9465 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9466   FromE = FromE->IgnoreParenImpCasts();
9467   switch (FromE->getStmtClass()) {
9468     default:
9469       break;
9470     case Stmt::ObjCStringLiteralClass:
9471       // "string literal"
9472       return LK_String;
9473     case Stmt::ObjCArrayLiteralClass:
9474       // "array literal"
9475       return LK_Array;
9476     case Stmt::ObjCDictionaryLiteralClass:
9477       // "dictionary literal"
9478       return LK_Dictionary;
9479     case Stmt::BlockExprClass:
9480       return LK_Block;
9481     case Stmt::ObjCBoxedExprClass: {
9482       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9483       switch (Inner->getStmtClass()) {
9484         case Stmt::IntegerLiteralClass:
9485         case Stmt::FloatingLiteralClass:
9486         case Stmt::CharacterLiteralClass:
9487         case Stmt::ObjCBoolLiteralExprClass:
9488         case Stmt::CXXBoolLiteralExprClass:
9489           // "numeric literal"
9490           return LK_Numeric;
9491         case Stmt::ImplicitCastExprClass: {
9492           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9493           // Boolean literals can be represented by implicit casts.
9494           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9495             return LK_Numeric;
9496           break;
9497         }
9498         default:
9499           break;
9500       }
9501       return LK_Boxed;
9502     }
9503   }
9504   return LK_None;
9505 }
9506 
9507 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9508                                           ExprResult &LHS, ExprResult &RHS,
9509                                           BinaryOperator::Opcode Opc){
9510   Expr *Literal;
9511   Expr *Other;
9512   if (isObjCObjectLiteral(LHS)) {
9513     Literal = LHS.get();
9514     Other = RHS.get();
9515   } else {
9516     Literal = RHS.get();
9517     Other = LHS.get();
9518   }
9519 
9520   // Don't warn on comparisons against nil.
9521   Other = Other->IgnoreParenCasts();
9522   if (Other->isNullPointerConstant(S.getASTContext(),
9523                                    Expr::NPC_ValueDependentIsNotNull))
9524     return;
9525 
9526   // This should be kept in sync with warn_objc_literal_comparison.
9527   // LK_String should always be after the other literals, since it has its own
9528   // warning flag.
9529   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9530   assert(LiteralKind != Sema::LK_Block);
9531   if (LiteralKind == Sema::LK_None) {
9532     llvm_unreachable("Unknown Objective-C object literal kind");
9533   }
9534 
9535   if (LiteralKind == Sema::LK_String)
9536     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9537       << Literal->getSourceRange();
9538   else
9539     S.Diag(Loc, diag::warn_objc_literal_comparison)
9540       << LiteralKind << Literal->getSourceRange();
9541 
9542   if (BinaryOperator::isEqualityOp(Opc) &&
9543       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9544     SourceLocation Start = LHS.get()->getLocStart();
9545     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9546     CharSourceRange OpRange =
9547       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9548 
9549     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9550       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9551       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9552       << FixItHint::CreateInsertion(End, "]");
9553   }
9554 }
9555 
9556 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9557 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9558                                            ExprResult &RHS, SourceLocation Loc,
9559                                            BinaryOperatorKind Opc) {
9560   // Check that left hand side is !something.
9561   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9562   if (!UO || UO->getOpcode() != UO_LNot) return;
9563 
9564   // Only check if the right hand side is non-bool arithmetic type.
9565   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9566 
9567   // Make sure that the something in !something is not bool.
9568   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9569   if (SubExpr->isKnownToHaveBooleanValue()) return;
9570 
9571   // Emit warning.
9572   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9573   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9574       << Loc << IsBitwiseOp;
9575 
9576   // First note suggest !(x < y)
9577   SourceLocation FirstOpen = SubExpr->getLocStart();
9578   SourceLocation FirstClose = RHS.get()->getLocEnd();
9579   FirstClose = S.getLocForEndOfToken(FirstClose);
9580   if (FirstClose.isInvalid())
9581     FirstOpen = SourceLocation();
9582   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9583       << IsBitwiseOp
9584       << FixItHint::CreateInsertion(FirstOpen, "(")
9585       << FixItHint::CreateInsertion(FirstClose, ")");
9586 
9587   // Second note suggests (!x) < y
9588   SourceLocation SecondOpen = LHS.get()->getLocStart();
9589   SourceLocation SecondClose = LHS.get()->getLocEnd();
9590   SecondClose = S.getLocForEndOfToken(SecondClose);
9591   if (SecondClose.isInvalid())
9592     SecondOpen = SourceLocation();
9593   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9594       << FixItHint::CreateInsertion(SecondOpen, "(")
9595       << FixItHint::CreateInsertion(SecondClose, ")");
9596 }
9597 
9598 // Get the decl for a simple expression: a reference to a variable,
9599 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9600 static ValueDecl *getCompareDecl(Expr *E) {
9601   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9602     return DR->getDecl();
9603   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9604     if (Ivar->isFreeIvar())
9605       return Ivar->getDecl();
9606   }
9607   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9608     if (Mem->isImplicitAccess())
9609       return Mem->getMemberDecl();
9610   }
9611   return nullptr;
9612 }
9613 
9614 /// Diagnose some forms of syntactically-obvious tautological comparison.
9615 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9616                                            Expr *LHS, Expr *RHS,
9617                                            BinaryOperatorKind Opc) {
9618   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9619   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9620 
9621   QualType LHSType = LHS->getType();
9622   if (LHSType->hasFloatingRepresentation() ||
9623       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9624       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9625       S.inTemplateInstantiation())
9626     return;
9627 
9628   // For non-floating point types, check for self-comparisons of the form
9629   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9630   // often indicate logic errors in the program.
9631   //
9632   // NOTE: Don't warn about comparison expressions resulting from macro
9633   // expansion. Also don't warn about comparisons which are only self
9634   // comparisons within a template instantiation. The warnings should catch
9635   // obvious cases in the definition of the template anyways. The idea is to
9636   // warn when the typed comparison operator will always evaluate to the same
9637   // result.
9638   ValueDecl *DL = getCompareDecl(LHSStripped);
9639   ValueDecl *DR = getCompareDecl(RHSStripped);
9640   if (DL && DR && declaresSameEntity(DL, DR)) {
9641     StringRef Result;
9642     switch (Opc) {
9643     case BO_EQ: case BO_LE: case BO_GE:
9644       Result = "true";
9645       break;
9646     case BO_NE: case BO_LT: case BO_GT:
9647       Result = "false";
9648       break;
9649     case BO_Cmp:
9650       Result = "'std::strong_ordering::equal'";
9651       break;
9652     default:
9653       break;
9654     }
9655     S.DiagRuntimeBehavior(Loc, nullptr,
9656                           S.PDiag(diag::warn_comparison_always)
9657                               << 0 /*self-comparison*/ << !Result.empty()
9658                               << Result);
9659   } else if (DL && DR &&
9660              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9661              !DL->isWeak() && !DR->isWeak()) {
9662     // What is it always going to evaluate to?
9663     StringRef Result;
9664     switch(Opc) {
9665     case BO_EQ: // e.g. array1 == array2
9666       Result = "false";
9667       break;
9668     case BO_NE: // e.g. array1 != array2
9669       Result = "true";
9670       break;
9671     default: // e.g. array1 <= array2
9672       // The best we can say is 'a constant'
9673       break;
9674     }
9675     S.DiagRuntimeBehavior(Loc, nullptr,
9676                           S.PDiag(diag::warn_comparison_always)
9677                               << 1 /*array comparison*/
9678                               << !Result.empty() << Result);
9679   }
9680 
9681   if (isa<CastExpr>(LHSStripped))
9682     LHSStripped = LHSStripped->IgnoreParenCasts();
9683   if (isa<CastExpr>(RHSStripped))
9684     RHSStripped = RHSStripped->IgnoreParenCasts();
9685 
9686   // Warn about comparisons against a string constant (unless the other
9687   // operand is null); the user probably wants strcmp.
9688   Expr *LiteralString = nullptr;
9689   Expr *LiteralStringStripped = nullptr;
9690   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9691       !RHSStripped->isNullPointerConstant(S.Context,
9692                                           Expr::NPC_ValueDependentIsNull)) {
9693     LiteralString = LHS;
9694     LiteralStringStripped = LHSStripped;
9695   } else if ((isa<StringLiteral>(RHSStripped) ||
9696               isa<ObjCEncodeExpr>(RHSStripped)) &&
9697              !LHSStripped->isNullPointerConstant(S.Context,
9698                                           Expr::NPC_ValueDependentIsNull)) {
9699     LiteralString = RHS;
9700     LiteralStringStripped = RHSStripped;
9701   }
9702 
9703   if (LiteralString) {
9704     S.DiagRuntimeBehavior(Loc, nullptr,
9705                           S.PDiag(diag::warn_stringcompare)
9706                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9707                               << LiteralString->getSourceRange());
9708   }
9709 }
9710 
9711 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9712                                                  ExprResult &RHS,
9713                                                  SourceLocation Loc,
9714                                                  BinaryOperatorKind Opc) {
9715   // C99 6.5.8p3 / C99 6.5.9p4
9716   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9717   if (LHS.isInvalid() || RHS.isInvalid())
9718     return QualType();
9719   if (Type.isNull())
9720     return S.InvalidOperands(Loc, LHS, RHS);
9721   assert(Type->isArithmeticType() || Type->isEnumeralType());
9722 
9723   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
9724 
9725   enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering;
9726   if (Type->isAnyComplexType())
9727     Ordering = StrongEquality;
9728   else if (Type->isFloatingType())
9729     Ordering = PartialOrdering;
9730   else
9731     Ordering = StrongOrdering;
9732 
9733   if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc))
9734     return S.InvalidOperands(Loc, LHS, RHS);
9735 
9736   // Check for comparisons of floating point operands using != and ==.
9737   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
9738     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
9739 
9740   // The result of comparisons is 'bool' in C++, 'int' in C.
9741   // FIXME: For BO_Cmp, return the relevant comparison category type.
9742   return S.Context.getLogicalOperationType();
9743 }
9744 
9745 // C99 6.5.8, C++ [expr.rel]
9746 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9747                                     SourceLocation Loc, BinaryOperatorKind Opc,
9748                                     bool IsRelational) {
9749   // Comparisons expect an rvalue, so convert to rvalue before any
9750   // type-related checks.
9751   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9752   if (LHS.isInvalid())
9753     return QualType();
9754   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9755   if (RHS.isInvalid())
9756     return QualType();
9757 
9758   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9759 
9760   // Handle vector comparisons separately.
9761   if (LHS.get()->getType()->isVectorType() ||
9762       RHS.get()->getType()->isVectorType())
9763     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
9764 
9765   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9766   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
9767 
9768   QualType LHSType = LHS.get()->getType();
9769   QualType RHSType = RHS.get()->getType();
9770   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
9771       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
9772     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
9773 
9774   QualType ResultTy = Context.getLogicalOperationType();
9775 
9776   const Expr::NullPointerConstantKind LHSNullKind =
9777       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9778   const Expr::NullPointerConstantKind RHSNullKind =
9779       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9780   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9781   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9782 
9783   if (!IsRelational && LHSIsNull != RHSIsNull) {
9784     bool IsEquality = Opc == BO_EQ;
9785     if (RHSIsNull)
9786       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9787                                    RHS.get()->getSourceRange());
9788     else
9789       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9790                                    LHS.get()->getSourceRange());
9791   }
9792 
9793   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9794       (RHSType->isIntegerType() && !RHSIsNull)) {
9795     // Skip normal pointer conversion checks in this case; we have better
9796     // diagnostics for this below.
9797   } else if (getLangOpts().CPlusPlus) {
9798     // Equality comparison of a function pointer to a void pointer is invalid,
9799     // but we allow it as an extension.
9800     // FIXME: If we really want to allow this, should it be part of composite
9801     // pointer type computation so it works in conditionals too?
9802     if (!IsRelational &&
9803         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9804          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9805       // This is a gcc extension compatibility comparison.
9806       // In a SFINAE context, we treat this as a hard error to maintain
9807       // conformance with the C++ standard.
9808       diagnoseFunctionPointerToVoidComparison(
9809           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9810 
9811       if (isSFINAEContext())
9812         return QualType();
9813 
9814       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9815       return ResultTy;
9816     }
9817 
9818     // C++ [expr.eq]p2:
9819     //   If at least one operand is a pointer [...] bring them to their
9820     //   composite pointer type.
9821     // C++ [expr.rel]p2:
9822     //   If both operands are pointers, [...] bring them to their composite
9823     //   pointer type.
9824     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9825             (IsRelational ? 2 : 1) &&
9826         (!LangOpts.ObjCAutoRefCount ||
9827          !(LHSType->isObjCObjectPointerType() ||
9828            RHSType->isObjCObjectPointerType()))) {
9829       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9830         return QualType();
9831       else
9832         return ResultTy;
9833     }
9834   } else if (LHSType->isPointerType() &&
9835              RHSType->isPointerType()) { // C99 6.5.8p2
9836     // All of the following pointer-related warnings are GCC extensions, except
9837     // when handling null pointer constants.
9838     QualType LCanPointeeTy =
9839       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9840     QualType RCanPointeeTy =
9841       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9842 
9843     // C99 6.5.9p2 and C99 6.5.8p2
9844     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9845                                    RCanPointeeTy.getUnqualifiedType())) {
9846       // Valid unless a relational comparison of function pointers
9847       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9848         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9849           << LHSType << RHSType << LHS.get()->getSourceRange()
9850           << RHS.get()->getSourceRange();
9851       }
9852     } else if (!IsRelational &&
9853                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9854       // Valid unless comparison between non-null pointer and function pointer
9855       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9856           && !LHSIsNull && !RHSIsNull)
9857         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9858                                                 /*isError*/false);
9859     } else {
9860       // Invalid
9861       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9862     }
9863     if (LCanPointeeTy != RCanPointeeTy) {
9864       // Treat NULL constant as a special case in OpenCL.
9865       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9866         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9867         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9868           Diag(Loc,
9869                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9870               << LHSType << RHSType << 0 /* comparison */
9871               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9872         }
9873       }
9874       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
9875       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
9876       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9877                                                : CK_BitCast;
9878       if (LHSIsNull && !RHSIsNull)
9879         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9880       else
9881         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9882     }
9883     return ResultTy;
9884   }
9885 
9886   if (getLangOpts().CPlusPlus) {
9887     // C++ [expr.eq]p4:
9888     //   Two operands of type std::nullptr_t or one operand of type
9889     //   std::nullptr_t and the other a null pointer constant compare equal.
9890     if (!IsRelational && LHSIsNull && RHSIsNull) {
9891       if (LHSType->isNullPtrType()) {
9892         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9893         return ResultTy;
9894       }
9895       if (RHSType->isNullPtrType()) {
9896         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9897         return ResultTy;
9898       }
9899     }
9900 
9901     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9902     // These aren't covered by the composite pointer type rules.
9903     if (!IsRelational && RHSType->isNullPtrType() &&
9904         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9905       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9906       return ResultTy;
9907     }
9908     if (!IsRelational && LHSType->isNullPtrType() &&
9909         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9910       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9911       return ResultTy;
9912     }
9913 
9914     if (IsRelational &&
9915         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9916          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9917       // HACK: Relational comparison of nullptr_t against a pointer type is
9918       // invalid per DR583, but we allow it within std::less<> and friends,
9919       // since otherwise common uses of it break.
9920       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9921       // friends to have std::nullptr_t overload candidates.
9922       DeclContext *DC = CurContext;
9923       if (isa<FunctionDecl>(DC))
9924         DC = DC->getParent();
9925       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9926         if (CTSD->isInStdNamespace() &&
9927             llvm::StringSwitch<bool>(CTSD->getName())
9928                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9929                 .Default(false)) {
9930           if (RHSType->isNullPtrType())
9931             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9932           else
9933             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9934           return ResultTy;
9935         }
9936       }
9937     }
9938 
9939     // C++ [expr.eq]p2:
9940     //   If at least one operand is a pointer to member, [...] bring them to
9941     //   their composite pointer type.
9942     if (!IsRelational &&
9943         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9944       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9945         return QualType();
9946       else
9947         return ResultTy;
9948     }
9949   }
9950 
9951   // Handle block pointer types.
9952   if (!IsRelational && LHSType->isBlockPointerType() &&
9953       RHSType->isBlockPointerType()) {
9954     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9955     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9956 
9957     if (!LHSIsNull && !RHSIsNull &&
9958         !Context.typesAreCompatible(lpointee, rpointee)) {
9959       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9960         << LHSType << RHSType << LHS.get()->getSourceRange()
9961         << RHS.get()->getSourceRange();
9962     }
9963     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9964     return ResultTy;
9965   }
9966 
9967   // Allow block pointers to be compared with null pointer constants.
9968   if (!IsRelational
9969       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9970           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9971     if (!LHSIsNull && !RHSIsNull) {
9972       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9973              ->getPointeeType()->isVoidType())
9974             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9975                 ->getPointeeType()->isVoidType())))
9976         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9977           << LHSType << RHSType << LHS.get()->getSourceRange()
9978           << RHS.get()->getSourceRange();
9979     }
9980     if (LHSIsNull && !RHSIsNull)
9981       LHS = ImpCastExprToType(LHS.get(), RHSType,
9982                               RHSType->isPointerType() ? CK_BitCast
9983                                 : CK_AnyPointerToBlockPointerCast);
9984     else
9985       RHS = ImpCastExprToType(RHS.get(), LHSType,
9986                               LHSType->isPointerType() ? CK_BitCast
9987                                 : CK_AnyPointerToBlockPointerCast);
9988     return ResultTy;
9989   }
9990 
9991   if (LHSType->isObjCObjectPointerType() ||
9992       RHSType->isObjCObjectPointerType()) {
9993     const PointerType *LPT = LHSType->getAs<PointerType>();
9994     const PointerType *RPT = RHSType->getAs<PointerType>();
9995     if (LPT || RPT) {
9996       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9997       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9998 
9999       if (!LPtrToVoid && !RPtrToVoid &&
10000           !Context.typesAreCompatible(LHSType, RHSType)) {
10001         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10002                                           /*isError*/false);
10003       }
10004       if (LHSIsNull && !RHSIsNull) {
10005         Expr *E = LHS.get();
10006         if (getLangOpts().ObjCAutoRefCount)
10007           CheckObjCConversion(SourceRange(), RHSType, E,
10008                               CCK_ImplicitConversion);
10009         LHS = ImpCastExprToType(E, RHSType,
10010                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10011       }
10012       else {
10013         Expr *E = RHS.get();
10014         if (getLangOpts().ObjCAutoRefCount)
10015           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10016                               /*Diagnose=*/true,
10017                               /*DiagnoseCFAudited=*/false, Opc);
10018         RHS = ImpCastExprToType(E, LHSType,
10019                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10020       }
10021       return ResultTy;
10022     }
10023     if (LHSType->isObjCObjectPointerType() &&
10024         RHSType->isObjCObjectPointerType()) {
10025       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10026         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10027                                           /*isError*/false);
10028       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10029         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10030 
10031       if (LHSIsNull && !RHSIsNull)
10032         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10033       else
10034         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10035       return ResultTy;
10036     }
10037 
10038     if (!IsRelational && LHSType->isBlockPointerType() &&
10039         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10040       LHS = ImpCastExprToType(LHS.get(), RHSType,
10041                               CK_BlockPointerToObjCPointerCast);
10042       return ResultTy;
10043     } else if (!IsRelational &&
10044                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10045                RHSType->isBlockPointerType()) {
10046       RHS = ImpCastExprToType(RHS.get(), LHSType,
10047                               CK_BlockPointerToObjCPointerCast);
10048       return ResultTy;
10049     }
10050   }
10051   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10052       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10053     unsigned DiagID = 0;
10054     bool isError = false;
10055     if (LangOpts.DebuggerSupport) {
10056       // Under a debugger, allow the comparison of pointers to integers,
10057       // since users tend to want to compare addresses.
10058     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10059                (RHSIsNull && RHSType->isIntegerType())) {
10060       if (IsRelational) {
10061         isError = getLangOpts().CPlusPlus;
10062         DiagID =
10063           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10064                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10065       }
10066     } else if (getLangOpts().CPlusPlus) {
10067       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10068       isError = true;
10069     } else if (IsRelational)
10070       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10071     else
10072       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10073 
10074     if (DiagID) {
10075       Diag(Loc, DiagID)
10076         << LHSType << RHSType << LHS.get()->getSourceRange()
10077         << RHS.get()->getSourceRange();
10078       if (isError)
10079         return QualType();
10080     }
10081 
10082     if (LHSType->isIntegerType())
10083       LHS = ImpCastExprToType(LHS.get(), RHSType,
10084                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10085     else
10086       RHS = ImpCastExprToType(RHS.get(), LHSType,
10087                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10088     return ResultTy;
10089   }
10090 
10091   // Handle block pointers.
10092   if (!IsRelational && RHSIsNull
10093       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10094     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10095     return ResultTy;
10096   }
10097   if (!IsRelational && LHSIsNull
10098       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10099     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10100     return ResultTy;
10101   }
10102 
10103   if (getLangOpts().OpenCLVersion >= 200) {
10104     if (LHSIsNull && RHSType->isQueueT()) {
10105       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10106       return ResultTy;
10107     }
10108 
10109     if (LHSType->isQueueT() && RHSIsNull) {
10110       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10111       return ResultTy;
10112     }
10113   }
10114 
10115   return InvalidOperands(Loc, LHS, RHS);
10116 }
10117 
10118 // Return a signed ext_vector_type that is of identical size and number of
10119 // elements. For floating point vectors, return an integer type of identical
10120 // size and number of elements. In the non ext_vector_type case, search from
10121 // the largest type to the smallest type to avoid cases where long long == long,
10122 // where long gets picked over long long.
10123 QualType Sema::GetSignedVectorType(QualType V) {
10124   const VectorType *VTy = V->getAs<VectorType>();
10125   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10126 
10127   if (isa<ExtVectorType>(VTy)) {
10128     if (TypeSize == Context.getTypeSize(Context.CharTy))
10129       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10130     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10131       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10132     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10133       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10134     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10135       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10136     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10137            "Unhandled vector element size in vector compare");
10138     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10139   }
10140 
10141   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10142     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10143                                  VectorType::GenericVector);
10144   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10145     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10146                                  VectorType::GenericVector);
10147   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10148     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10149                                  VectorType::GenericVector);
10150   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10151     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10152                                  VectorType::GenericVector);
10153   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10154          "Unhandled vector element size in vector compare");
10155   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10156                                VectorType::GenericVector);
10157 }
10158 
10159 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10160 /// operates on extended vector types.  Instead of producing an IntTy result,
10161 /// like a scalar comparison, a vector comparison produces a vector of integer
10162 /// types.
10163 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10164                                           SourceLocation Loc,
10165                                           BinaryOperatorKind Opc) {
10166   // Check to make sure we're operating on vectors of the same type and width,
10167   // Allowing one side to be a scalar of element type.
10168   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10169                               /*AllowBothBool*/true,
10170                               /*AllowBoolConversions*/getLangOpts().ZVector);
10171   if (vType.isNull())
10172     return vType;
10173 
10174   QualType LHSType = LHS.get()->getType();
10175 
10176   // If AltiVec, the comparison results in a numeric type, i.e.
10177   // bool for C++, int for C
10178   if (getLangOpts().AltiVec &&
10179       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10180     return Context.getLogicalOperationType();
10181 
10182   // For non-floating point types, check for self-comparisons of the form
10183   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10184   // often indicate logic errors in the program.
10185   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10186 
10187   // Check for comparisons of floating point operands using != and ==.
10188   if (BinaryOperator::isEqualityOp(Opc) &&
10189       LHSType->hasFloatingRepresentation()) {
10190     assert(RHS.get()->getType()->hasFloatingRepresentation());
10191     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10192   }
10193 
10194   // Return a signed type for the vector.
10195   return GetSignedVectorType(vType);
10196 }
10197 
10198 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10199                                           SourceLocation Loc) {
10200   // Ensure that either both operands are of the same vector type, or
10201   // one operand is of a vector type and the other is of its element type.
10202   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10203                                        /*AllowBothBool*/true,
10204                                        /*AllowBoolConversions*/false);
10205   if (vType.isNull())
10206     return InvalidOperands(Loc, LHS, RHS);
10207   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10208       vType->hasFloatingRepresentation())
10209     return InvalidOperands(Loc, LHS, RHS);
10210   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10211   //        usage of the logical operators && and || with vectors in C. This
10212   //        check could be notionally dropped.
10213   if (!getLangOpts().CPlusPlus &&
10214       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10215     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10216 
10217   return GetSignedVectorType(LHS.get()->getType());
10218 }
10219 
10220 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10221                                            SourceLocation Loc,
10222                                            BinaryOperatorKind Opc) {
10223   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10224 
10225   bool IsCompAssign =
10226       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10227 
10228   if (LHS.get()->getType()->isVectorType() ||
10229       RHS.get()->getType()->isVectorType()) {
10230     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10231         RHS.get()->getType()->hasIntegerRepresentation())
10232       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10233                         /*AllowBothBool*/true,
10234                         /*AllowBoolConversions*/getLangOpts().ZVector);
10235     return InvalidOperands(Loc, LHS, RHS);
10236   }
10237 
10238   if (Opc == BO_And)
10239     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10240 
10241   ExprResult LHSResult = LHS, RHSResult = RHS;
10242   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10243                                                  IsCompAssign);
10244   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10245     return QualType();
10246   LHS = LHSResult.get();
10247   RHS = RHSResult.get();
10248 
10249   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10250     return compType;
10251   return InvalidOperands(Loc, LHS, RHS);
10252 }
10253 
10254 // C99 6.5.[13,14]
10255 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10256                                            SourceLocation Loc,
10257                                            BinaryOperatorKind Opc) {
10258   // Check vector operands differently.
10259   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10260     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10261 
10262   // Diagnose cases where the user write a logical and/or but probably meant a
10263   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10264   // is a constant.
10265   if (LHS.get()->getType()->isIntegerType() &&
10266       !LHS.get()->getType()->isBooleanType() &&
10267       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10268       // Don't warn in macros or template instantiations.
10269       !Loc.isMacroID() && !inTemplateInstantiation()) {
10270     // If the RHS can be constant folded, and if it constant folds to something
10271     // that isn't 0 or 1 (which indicate a potential logical operation that
10272     // happened to fold to true/false) then warn.
10273     // Parens on the RHS are ignored.
10274     llvm::APSInt Result;
10275     if (RHS.get()->EvaluateAsInt(Result, Context))
10276       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10277            !RHS.get()->getExprLoc().isMacroID()) ||
10278           (Result != 0 && Result != 1)) {
10279         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10280           << RHS.get()->getSourceRange()
10281           << (Opc == BO_LAnd ? "&&" : "||");
10282         // Suggest replacing the logical operator with the bitwise version
10283         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10284             << (Opc == BO_LAnd ? "&" : "|")
10285             << FixItHint::CreateReplacement(SourceRange(
10286                                                  Loc, getLocForEndOfToken(Loc)),
10287                                             Opc == BO_LAnd ? "&" : "|");
10288         if (Opc == BO_LAnd)
10289           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10290           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10291               << FixItHint::CreateRemoval(
10292                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10293                               RHS.get()->getLocEnd()));
10294       }
10295   }
10296 
10297   if (!Context.getLangOpts().CPlusPlus) {
10298     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10299     // not operate on the built-in scalar and vector float types.
10300     if (Context.getLangOpts().OpenCL &&
10301         Context.getLangOpts().OpenCLVersion < 120) {
10302       if (LHS.get()->getType()->isFloatingType() ||
10303           RHS.get()->getType()->isFloatingType())
10304         return InvalidOperands(Loc, LHS, RHS);
10305     }
10306 
10307     LHS = UsualUnaryConversions(LHS.get());
10308     if (LHS.isInvalid())
10309       return QualType();
10310 
10311     RHS = UsualUnaryConversions(RHS.get());
10312     if (RHS.isInvalid())
10313       return QualType();
10314 
10315     if (!LHS.get()->getType()->isScalarType() ||
10316         !RHS.get()->getType()->isScalarType())
10317       return InvalidOperands(Loc, LHS, RHS);
10318 
10319     return Context.IntTy;
10320   }
10321 
10322   // The following is safe because we only use this method for
10323   // non-overloadable operands.
10324 
10325   // C++ [expr.log.and]p1
10326   // C++ [expr.log.or]p1
10327   // The operands are both contextually converted to type bool.
10328   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10329   if (LHSRes.isInvalid())
10330     return InvalidOperands(Loc, LHS, RHS);
10331   LHS = LHSRes;
10332 
10333   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10334   if (RHSRes.isInvalid())
10335     return InvalidOperands(Loc, LHS, RHS);
10336   RHS = RHSRes;
10337 
10338   // C++ [expr.log.and]p2
10339   // C++ [expr.log.or]p2
10340   // The result is a bool.
10341   return Context.BoolTy;
10342 }
10343 
10344 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10345   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10346   if (!ME) return false;
10347   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10348   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10349       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10350   if (!Base) return false;
10351   return Base->getMethodDecl() != nullptr;
10352 }
10353 
10354 /// Is the given expression (which must be 'const') a reference to a
10355 /// variable which was originally non-const, but which has become
10356 /// 'const' due to being captured within a block?
10357 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10358 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10359   assert(E->isLValue() && E->getType().isConstQualified());
10360   E = E->IgnoreParens();
10361 
10362   // Must be a reference to a declaration from an enclosing scope.
10363   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10364   if (!DRE) return NCCK_None;
10365   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10366 
10367   // The declaration must be a variable which is not declared 'const'.
10368   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10369   if (!var) return NCCK_None;
10370   if (var->getType().isConstQualified()) return NCCK_None;
10371   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10372 
10373   // Decide whether the first capture was for a block or a lambda.
10374   DeclContext *DC = S.CurContext, *Prev = nullptr;
10375   // Decide whether the first capture was for a block or a lambda.
10376   while (DC) {
10377     // For init-capture, it is possible that the variable belongs to the
10378     // template pattern of the current context.
10379     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10380       if (var->isInitCapture() &&
10381           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10382         break;
10383     if (DC == var->getDeclContext())
10384       break;
10385     Prev = DC;
10386     DC = DC->getParent();
10387   }
10388   // Unless we have an init-capture, we've gone one step too far.
10389   if (!var->isInitCapture())
10390     DC = Prev;
10391   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10392 }
10393 
10394 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10395   Ty = Ty.getNonReferenceType();
10396   if (IsDereference && Ty->isPointerType())
10397     Ty = Ty->getPointeeType();
10398   return !Ty.isConstQualified();
10399 }
10400 
10401 // Update err_typecheck_assign_const and note_typecheck_assign_const
10402 // when this enum is changed.
10403 enum {
10404   ConstFunction,
10405   ConstVariable,
10406   ConstMember,
10407   ConstMethod,
10408   NestedConstMember,
10409   ConstUnknown,  // Keep as last element
10410 };
10411 
10412 /// Emit the "read-only variable not assignable" error and print notes to give
10413 /// more information about why the variable is not assignable, such as pointing
10414 /// to the declaration of a const variable, showing that a method is const, or
10415 /// that the function is returning a const reference.
10416 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10417                                     SourceLocation Loc) {
10418   SourceRange ExprRange = E->getSourceRange();
10419 
10420   // Only emit one error on the first const found.  All other consts will emit
10421   // a note to the error.
10422   bool DiagnosticEmitted = false;
10423 
10424   // Track if the current expression is the result of a dereference, and if the
10425   // next checked expression is the result of a dereference.
10426   bool IsDereference = false;
10427   bool NextIsDereference = false;
10428 
10429   // Loop to process MemberExpr chains.
10430   while (true) {
10431     IsDereference = NextIsDereference;
10432 
10433     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10434     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10435       NextIsDereference = ME->isArrow();
10436       const ValueDecl *VD = ME->getMemberDecl();
10437       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10438         // Mutable fields can be modified even if the class is const.
10439         if (Field->isMutable()) {
10440           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10441           break;
10442         }
10443 
10444         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10445           if (!DiagnosticEmitted) {
10446             S.Diag(Loc, diag::err_typecheck_assign_const)
10447                 << ExprRange << ConstMember << false /*static*/ << Field
10448                 << Field->getType();
10449             DiagnosticEmitted = true;
10450           }
10451           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10452               << ConstMember << false /*static*/ << Field << Field->getType()
10453               << Field->getSourceRange();
10454         }
10455         E = ME->getBase();
10456         continue;
10457       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10458         if (VDecl->getType().isConstQualified()) {
10459           if (!DiagnosticEmitted) {
10460             S.Diag(Loc, diag::err_typecheck_assign_const)
10461                 << ExprRange << ConstMember << true /*static*/ << VDecl
10462                 << VDecl->getType();
10463             DiagnosticEmitted = true;
10464           }
10465           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10466               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10467               << VDecl->getSourceRange();
10468         }
10469         // Static fields do not inherit constness from parents.
10470         break;
10471       }
10472       break; // End MemberExpr
10473     } else if (const ArraySubscriptExpr *ASE =
10474                    dyn_cast<ArraySubscriptExpr>(E)) {
10475       E = ASE->getBase()->IgnoreParenImpCasts();
10476       continue;
10477     } else if (const ExtVectorElementExpr *EVE =
10478                    dyn_cast<ExtVectorElementExpr>(E)) {
10479       E = EVE->getBase()->IgnoreParenImpCasts();
10480       continue;
10481     }
10482     break;
10483   }
10484 
10485   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10486     // Function calls
10487     const FunctionDecl *FD = CE->getDirectCallee();
10488     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10489       if (!DiagnosticEmitted) {
10490         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10491                                                       << ConstFunction << FD;
10492         DiagnosticEmitted = true;
10493       }
10494       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10495              diag::note_typecheck_assign_const)
10496           << ConstFunction << FD << FD->getReturnType()
10497           << FD->getReturnTypeSourceRange();
10498     }
10499   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10500     // Point to variable declaration.
10501     if (const ValueDecl *VD = DRE->getDecl()) {
10502       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10503         if (!DiagnosticEmitted) {
10504           S.Diag(Loc, diag::err_typecheck_assign_const)
10505               << ExprRange << ConstVariable << VD << VD->getType();
10506           DiagnosticEmitted = true;
10507         }
10508         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10509             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10510       }
10511     }
10512   } else if (isa<CXXThisExpr>(E)) {
10513     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10514       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10515         if (MD->isConst()) {
10516           if (!DiagnosticEmitted) {
10517             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10518                                                           << ConstMethod << MD;
10519             DiagnosticEmitted = true;
10520           }
10521           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10522               << ConstMethod << MD << MD->getSourceRange();
10523         }
10524       }
10525     }
10526   }
10527 
10528   if (DiagnosticEmitted)
10529     return;
10530 
10531   // Can't determine a more specific message, so display the generic error.
10532   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10533 }
10534 
10535 enum OriginalExprKind {
10536   OEK_Variable,
10537   OEK_Member,
10538   OEK_LValue
10539 };
10540 
10541 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10542                                          const RecordType *Ty,
10543                                          SourceLocation Loc, SourceRange Range,
10544                                          OriginalExprKind OEK,
10545                                          bool &DiagnosticEmitted,
10546                                          bool IsNested = false) {
10547   // We walk the record hierarchy breadth-first to ensure that we print
10548   // diagnostics in field nesting order.
10549   // First, check every field for constness.
10550   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10551     if (Field->getType().isConstQualified()) {
10552       if (!DiagnosticEmitted) {
10553         S.Diag(Loc, diag::err_typecheck_assign_const)
10554             << Range << NestedConstMember << OEK << VD
10555             << IsNested << Field;
10556         DiagnosticEmitted = true;
10557       }
10558       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10559           << NestedConstMember << IsNested << Field
10560           << Field->getType() << Field->getSourceRange();
10561     }
10562   }
10563   // Then, recurse.
10564   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10565     QualType FTy = Field->getType();
10566     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10567       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10568                                    OEK, DiagnosticEmitted, true);
10569   }
10570 }
10571 
10572 /// Emit an error for the case where a record we are trying to assign to has a
10573 /// const-qualified field somewhere in its hierarchy.
10574 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10575                                          SourceLocation Loc) {
10576   QualType Ty = E->getType();
10577   assert(Ty->isRecordType() && "lvalue was not record?");
10578   SourceRange Range = E->getSourceRange();
10579   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10580   bool DiagEmitted = false;
10581 
10582   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10583     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10584             Range, OEK_Member, DiagEmitted);
10585   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10586     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10587             Range, OEK_Variable, DiagEmitted);
10588   else
10589     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10590             Range, OEK_LValue, DiagEmitted);
10591   if (!DiagEmitted)
10592     DiagnoseConstAssignment(S, E, Loc);
10593 }
10594 
10595 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10596 /// emit an error and return true.  If so, return false.
10597 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10598   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10599 
10600   S.CheckShadowingDeclModification(E, Loc);
10601 
10602   SourceLocation OrigLoc = Loc;
10603   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10604                                                               &Loc);
10605   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10606     IsLV = Expr::MLV_InvalidMessageExpression;
10607   if (IsLV == Expr::MLV_Valid)
10608     return false;
10609 
10610   unsigned DiagID = 0;
10611   bool NeedType = false;
10612   switch (IsLV) { // C99 6.5.16p2
10613   case Expr::MLV_ConstQualified:
10614     // Use a specialized diagnostic when we're assigning to an object
10615     // from an enclosing function or block.
10616     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10617       if (NCCK == NCCK_Block)
10618         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10619       else
10620         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10621       break;
10622     }
10623 
10624     // In ARC, use some specialized diagnostics for occasions where we
10625     // infer 'const'.  These are always pseudo-strong variables.
10626     if (S.getLangOpts().ObjCAutoRefCount) {
10627       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10628       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10629         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10630 
10631         // Use the normal diagnostic if it's pseudo-__strong but the
10632         // user actually wrote 'const'.
10633         if (var->isARCPseudoStrong() &&
10634             (!var->getTypeSourceInfo() ||
10635              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10636           // There are two pseudo-strong cases:
10637           //  - self
10638           ObjCMethodDecl *method = S.getCurMethodDecl();
10639           if (method && var == method->getSelfDecl())
10640             DiagID = method->isClassMethod()
10641               ? diag::err_typecheck_arc_assign_self_class_method
10642               : diag::err_typecheck_arc_assign_self;
10643 
10644           //  - fast enumeration variables
10645           else
10646             DiagID = diag::err_typecheck_arr_assign_enumeration;
10647 
10648           SourceRange Assign;
10649           if (Loc != OrigLoc)
10650             Assign = SourceRange(OrigLoc, OrigLoc);
10651           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10652           // We need to preserve the AST regardless, so migration tool
10653           // can do its job.
10654           return false;
10655         }
10656       }
10657     }
10658 
10659     // If none of the special cases above are triggered, then this is a
10660     // simple const assignment.
10661     if (DiagID == 0) {
10662       DiagnoseConstAssignment(S, E, Loc);
10663       return true;
10664     }
10665 
10666     break;
10667   case Expr::MLV_ConstAddrSpace:
10668     DiagnoseConstAssignment(S, E, Loc);
10669     return true;
10670   case Expr::MLV_ConstQualifiedField:
10671     DiagnoseRecursiveConstFields(S, E, Loc);
10672     return true;
10673   case Expr::MLV_ArrayType:
10674   case Expr::MLV_ArrayTemporary:
10675     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10676     NeedType = true;
10677     break;
10678   case Expr::MLV_NotObjectType:
10679     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10680     NeedType = true;
10681     break;
10682   case Expr::MLV_LValueCast:
10683     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10684     break;
10685   case Expr::MLV_Valid:
10686     llvm_unreachable("did not take early return for MLV_Valid");
10687   case Expr::MLV_InvalidExpression:
10688   case Expr::MLV_MemberFunction:
10689   case Expr::MLV_ClassTemporary:
10690     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10691     break;
10692   case Expr::MLV_IncompleteType:
10693   case Expr::MLV_IncompleteVoidType:
10694     return S.RequireCompleteType(Loc, E->getType(),
10695              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10696   case Expr::MLV_DuplicateVectorComponents:
10697     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10698     break;
10699   case Expr::MLV_NoSetterProperty:
10700     llvm_unreachable("readonly properties should be processed differently");
10701   case Expr::MLV_InvalidMessageExpression:
10702     DiagID = diag::err_readonly_message_assignment;
10703     break;
10704   case Expr::MLV_SubObjCPropertySetting:
10705     DiagID = diag::err_no_subobject_property_setting;
10706     break;
10707   }
10708 
10709   SourceRange Assign;
10710   if (Loc != OrigLoc)
10711     Assign = SourceRange(OrigLoc, OrigLoc);
10712   if (NeedType)
10713     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10714   else
10715     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10716   return true;
10717 }
10718 
10719 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10720                                          SourceLocation Loc,
10721                                          Sema &Sema) {
10722   if (Sema.inTemplateInstantiation())
10723     return;
10724   if (Sema.isUnevaluatedContext())
10725     return;
10726   if (Loc.isInvalid() || Loc.isMacroID())
10727     return;
10728   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
10729     return;
10730 
10731   // C / C++ fields
10732   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10733   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10734   if (ML && MR) {
10735     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
10736       return;
10737     const ValueDecl *LHSDecl =
10738         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
10739     const ValueDecl *RHSDecl =
10740         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
10741     if (LHSDecl != RHSDecl)
10742       return;
10743     if (LHSDecl->getType().isVolatileQualified())
10744       return;
10745     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10746       if (RefTy->getPointeeType().isVolatileQualified())
10747         return;
10748 
10749     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10750   }
10751 
10752   // Objective-C instance variables
10753   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10754   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10755   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10756     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10757     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10758     if (RL && RR && RL->getDecl() == RR->getDecl())
10759       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10760   }
10761 }
10762 
10763 // C99 6.5.16.1
10764 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10765                                        SourceLocation Loc,
10766                                        QualType CompoundType) {
10767   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10768 
10769   // Verify that LHS is a modifiable lvalue, and emit error if not.
10770   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10771     return QualType();
10772 
10773   QualType LHSType = LHSExpr->getType();
10774   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10775                                              CompoundType;
10776   // OpenCL v1.2 s6.1.1.1 p2:
10777   // The half data type can only be used to declare a pointer to a buffer that
10778   // contains half values
10779   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10780     LHSType->isHalfType()) {
10781     Diag(Loc, diag::err_opencl_half_load_store) << 1
10782         << LHSType.getUnqualifiedType();
10783     return QualType();
10784   }
10785 
10786   AssignConvertType ConvTy;
10787   if (CompoundType.isNull()) {
10788     Expr *RHSCheck = RHS.get();
10789 
10790     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10791 
10792     QualType LHSTy(LHSType);
10793     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10794     if (RHS.isInvalid())
10795       return QualType();
10796     // Special case of NSObject attributes on c-style pointer types.
10797     if (ConvTy == IncompatiblePointer &&
10798         ((Context.isObjCNSObjectType(LHSType) &&
10799           RHSType->isObjCObjectPointerType()) ||
10800          (Context.isObjCNSObjectType(RHSType) &&
10801           LHSType->isObjCObjectPointerType())))
10802       ConvTy = Compatible;
10803 
10804     if (ConvTy == Compatible &&
10805         LHSType->isObjCObjectType())
10806         Diag(Loc, diag::err_objc_object_assignment)
10807           << LHSType;
10808 
10809     // If the RHS is a unary plus or minus, check to see if they = and + are
10810     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10811     // instead of "x += 4".
10812     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10813       RHSCheck = ICE->getSubExpr();
10814     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10815       if ((UO->getOpcode() == UO_Plus ||
10816            UO->getOpcode() == UO_Minus) &&
10817           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10818           // Only if the two operators are exactly adjacent.
10819           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10820           // And there is a space or other character before the subexpr of the
10821           // unary +/-.  We don't want to warn on "x=-1".
10822           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10823           UO->getSubExpr()->getLocStart().isFileID()) {
10824         Diag(Loc, diag::warn_not_compound_assign)
10825           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10826           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10827       }
10828     }
10829 
10830     if (ConvTy == Compatible) {
10831       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10832         // Warn about retain cycles where a block captures the LHS, but
10833         // not if the LHS is a simple variable into which the block is
10834         // being stored...unless that variable can be captured by reference!
10835         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10836         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10837         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10838           checkRetainCycles(LHSExpr, RHS.get());
10839       }
10840 
10841       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10842           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10843         // It is safe to assign a weak reference into a strong variable.
10844         // Although this code can still have problems:
10845         //   id x = self.weakProp;
10846         //   id y = self.weakProp;
10847         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10848         // paths through the function. This should be revisited if
10849         // -Wrepeated-use-of-weak is made flow-sensitive.
10850         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10851         // variable, which will be valid for the current autorelease scope.
10852         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10853                              RHS.get()->getLocStart()))
10854           getCurFunction()->markSafeWeakUse(RHS.get());
10855 
10856       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10857         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10858       }
10859     }
10860   } else {
10861     // Compound assignment "x += y"
10862     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10863   }
10864 
10865   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10866                                RHS.get(), AA_Assigning))
10867     return QualType();
10868 
10869   CheckForNullPointerDereference(*this, LHSExpr);
10870 
10871   // C99 6.5.16p3: The type of an assignment expression is the type of the
10872   // left operand unless the left operand has qualified type, in which case
10873   // it is the unqualified version of the type of the left operand.
10874   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10875   // is converted to the type of the assignment expression (above).
10876   // C++ 5.17p1: the type of the assignment expression is that of its left
10877   // operand.
10878   return (getLangOpts().CPlusPlus
10879           ? LHSType : LHSType.getUnqualifiedType());
10880 }
10881 
10882 // Only ignore explicit casts to void.
10883 static bool IgnoreCommaOperand(const Expr *E) {
10884   E = E->IgnoreParens();
10885 
10886   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10887     if (CE->getCastKind() == CK_ToVoid) {
10888       return true;
10889     }
10890   }
10891 
10892   return false;
10893 }
10894 
10895 // Look for instances where it is likely the comma operator is confused with
10896 // another operator.  There is a whitelist of acceptable expressions for the
10897 // left hand side of the comma operator, otherwise emit a warning.
10898 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10899   // No warnings in macros
10900   if (Loc.isMacroID())
10901     return;
10902 
10903   // Don't warn in template instantiations.
10904   if (inTemplateInstantiation())
10905     return;
10906 
10907   // Scope isn't fine-grained enough to whitelist the specific cases, so
10908   // instead, skip more than needed, then call back into here with the
10909   // CommaVisitor in SemaStmt.cpp.
10910   // The whitelisted locations are the initialization and increment portions
10911   // of a for loop.  The additional checks are on the condition of
10912   // if statements, do/while loops, and for loops.
10913   const unsigned ForIncrementFlags =
10914       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10915   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10916   const unsigned ScopeFlags = getCurScope()->getFlags();
10917   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10918       (ScopeFlags & ForInitFlags) == ForInitFlags)
10919     return;
10920 
10921   // If there are multiple comma operators used together, get the RHS of the
10922   // of the comma operator as the LHS.
10923   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10924     if (BO->getOpcode() != BO_Comma)
10925       break;
10926     LHS = BO->getRHS();
10927   }
10928 
10929   // Only allow some expressions on LHS to not warn.
10930   if (IgnoreCommaOperand(LHS))
10931     return;
10932 
10933   Diag(Loc, diag::warn_comma_operator);
10934   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10935       << LHS->getSourceRange()
10936       << FixItHint::CreateInsertion(LHS->getLocStart(),
10937                                     LangOpts.CPlusPlus ? "static_cast<void>("
10938                                                        : "(void)(")
10939       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10940                                     ")");
10941 }
10942 
10943 // C99 6.5.17
10944 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10945                                    SourceLocation Loc) {
10946   LHS = S.CheckPlaceholderExpr(LHS.get());
10947   RHS = S.CheckPlaceholderExpr(RHS.get());
10948   if (LHS.isInvalid() || RHS.isInvalid())
10949     return QualType();
10950 
10951   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10952   // operands, but not unary promotions.
10953   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10954 
10955   // So we treat the LHS as a ignored value, and in C++ we allow the
10956   // containing site to determine what should be done with the RHS.
10957   LHS = S.IgnoredValueConversions(LHS.get());
10958   if (LHS.isInvalid())
10959     return QualType();
10960 
10961   S.DiagnoseUnusedExprResult(LHS.get());
10962 
10963   if (!S.getLangOpts().CPlusPlus) {
10964     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10965     if (RHS.isInvalid())
10966       return QualType();
10967     if (!RHS.get()->getType()->isVoidType())
10968       S.RequireCompleteType(Loc, RHS.get()->getType(),
10969                             diag::err_incomplete_type);
10970   }
10971 
10972   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10973     S.DiagnoseCommaOperator(LHS.get(), Loc);
10974 
10975   return RHS.get()->getType();
10976 }
10977 
10978 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10979 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10980 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10981                                                ExprValueKind &VK,
10982                                                ExprObjectKind &OK,
10983                                                SourceLocation OpLoc,
10984                                                bool IsInc, bool IsPrefix) {
10985   if (Op->isTypeDependent())
10986     return S.Context.DependentTy;
10987 
10988   QualType ResType = Op->getType();
10989   // Atomic types can be used for increment / decrement where the non-atomic
10990   // versions can, so ignore the _Atomic() specifier for the purpose of
10991   // checking.
10992   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10993     ResType = ResAtomicType->getValueType();
10994 
10995   assert(!ResType.isNull() && "no type for increment/decrement expression");
10996 
10997   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10998     // Decrement of bool is not allowed.
10999     if (!IsInc) {
11000       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11001       return QualType();
11002     }
11003     // Increment of bool sets it to true, but is deprecated.
11004     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11005                                               : diag::warn_increment_bool)
11006       << Op->getSourceRange();
11007   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11008     // Error on enum increments and decrements in C++ mode
11009     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11010     return QualType();
11011   } else if (ResType->isRealType()) {
11012     // OK!
11013   } else if (ResType->isPointerType()) {
11014     // C99 6.5.2.4p2, 6.5.6p2
11015     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11016       return QualType();
11017   } else if (ResType->isObjCObjectPointerType()) {
11018     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11019     // Otherwise, we just need a complete type.
11020     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11021         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11022       return QualType();
11023   } else if (ResType->isAnyComplexType()) {
11024     // C99 does not support ++/-- on complex types, we allow as an extension.
11025     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11026       << ResType << Op->getSourceRange();
11027   } else if (ResType->isPlaceholderType()) {
11028     ExprResult PR = S.CheckPlaceholderExpr(Op);
11029     if (PR.isInvalid()) return QualType();
11030     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11031                                           IsInc, IsPrefix);
11032   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11033     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11034   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11035              (ResType->getAs<VectorType>()->getVectorKind() !=
11036               VectorType::AltiVecBool)) {
11037     // The z vector extensions allow ++ and -- for non-bool vectors.
11038   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11039             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11040     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11041   } else {
11042     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11043       << ResType << int(IsInc) << Op->getSourceRange();
11044     return QualType();
11045   }
11046   // At this point, we know we have a real, complex or pointer type.
11047   // Now make sure the operand is a modifiable lvalue.
11048   if (CheckForModifiableLvalue(Op, OpLoc, S))
11049     return QualType();
11050   // In C++, a prefix increment is the same type as the operand. Otherwise
11051   // (in C or with postfix), the increment is the unqualified type of the
11052   // operand.
11053   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11054     VK = VK_LValue;
11055     OK = Op->getObjectKind();
11056     return ResType;
11057   } else {
11058     VK = VK_RValue;
11059     return ResType.getUnqualifiedType();
11060   }
11061 }
11062 
11063 
11064 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11065 /// This routine allows us to typecheck complex/recursive expressions
11066 /// where the declaration is needed for type checking. We only need to
11067 /// handle cases when the expression references a function designator
11068 /// or is an lvalue. Here are some examples:
11069 ///  - &(x) => x
11070 ///  - &*****f => f for f a function designator.
11071 ///  - &s.xx => s
11072 ///  - &s.zz[1].yy -> s, if zz is an array
11073 ///  - *(x + 1) -> x, if x is an array
11074 ///  - &"123"[2] -> 0
11075 ///  - & __real__ x -> x
11076 static ValueDecl *getPrimaryDecl(Expr *E) {
11077   switch (E->getStmtClass()) {
11078   case Stmt::DeclRefExprClass:
11079     return cast<DeclRefExpr>(E)->getDecl();
11080   case Stmt::MemberExprClass:
11081     // If this is an arrow operator, the address is an offset from
11082     // the base's value, so the object the base refers to is
11083     // irrelevant.
11084     if (cast<MemberExpr>(E)->isArrow())
11085       return nullptr;
11086     // Otherwise, the expression refers to a part of the base
11087     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11088   case Stmt::ArraySubscriptExprClass: {
11089     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11090     // promotion of register arrays earlier.
11091     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11092     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11093       if (ICE->getSubExpr()->getType()->isArrayType())
11094         return getPrimaryDecl(ICE->getSubExpr());
11095     }
11096     return nullptr;
11097   }
11098   case Stmt::UnaryOperatorClass: {
11099     UnaryOperator *UO = cast<UnaryOperator>(E);
11100 
11101     switch(UO->getOpcode()) {
11102     case UO_Real:
11103     case UO_Imag:
11104     case UO_Extension:
11105       return getPrimaryDecl(UO->getSubExpr());
11106     default:
11107       return nullptr;
11108     }
11109   }
11110   case Stmt::ParenExprClass:
11111     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11112   case Stmt::ImplicitCastExprClass:
11113     // If the result of an implicit cast is an l-value, we care about
11114     // the sub-expression; otherwise, the result here doesn't matter.
11115     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11116   default:
11117     return nullptr;
11118   }
11119 }
11120 
11121 namespace {
11122   enum {
11123     AO_Bit_Field = 0,
11124     AO_Vector_Element = 1,
11125     AO_Property_Expansion = 2,
11126     AO_Register_Variable = 3,
11127     AO_No_Error = 4
11128   };
11129 }
11130 /// \brief Diagnose invalid operand for address of operations.
11131 ///
11132 /// \param Type The type of operand which cannot have its address taken.
11133 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11134                                          Expr *E, unsigned Type) {
11135   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11136 }
11137 
11138 /// CheckAddressOfOperand - The operand of & must be either a function
11139 /// designator or an lvalue designating an object. If it is an lvalue, the
11140 /// object cannot be declared with storage class register or be a bit field.
11141 /// Note: The usual conversions are *not* applied to the operand of the &
11142 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11143 /// In C++, the operand might be an overloaded function name, in which case
11144 /// we allow the '&' but retain the overloaded-function type.
11145 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11146   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11147     if (PTy->getKind() == BuiltinType::Overload) {
11148       Expr *E = OrigOp.get()->IgnoreParens();
11149       if (!isa<OverloadExpr>(E)) {
11150         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11151         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11152           << OrigOp.get()->getSourceRange();
11153         return QualType();
11154       }
11155 
11156       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11157       if (isa<UnresolvedMemberExpr>(Ovl))
11158         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11159           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11160             << OrigOp.get()->getSourceRange();
11161           return QualType();
11162         }
11163 
11164       return Context.OverloadTy;
11165     }
11166 
11167     if (PTy->getKind() == BuiltinType::UnknownAny)
11168       return Context.UnknownAnyTy;
11169 
11170     if (PTy->getKind() == BuiltinType::BoundMember) {
11171       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11172         << OrigOp.get()->getSourceRange();
11173       return QualType();
11174     }
11175 
11176     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11177     if (OrigOp.isInvalid()) return QualType();
11178   }
11179 
11180   if (OrigOp.get()->isTypeDependent())
11181     return Context.DependentTy;
11182 
11183   assert(!OrigOp.get()->getType()->isPlaceholderType());
11184 
11185   // Make sure to ignore parentheses in subsequent checks
11186   Expr *op = OrigOp.get()->IgnoreParens();
11187 
11188   // In OpenCL captures for blocks called as lambda functions
11189   // are located in the private address space. Blocks used in
11190   // enqueue_kernel can be located in a different address space
11191   // depending on a vendor implementation. Thus preventing
11192   // taking an address of the capture to avoid invalid AS casts.
11193   if (LangOpts.OpenCL) {
11194     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11195     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11196       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11197       return QualType();
11198     }
11199   }
11200 
11201   if (getLangOpts().C99) {
11202     // Implement C99-only parts of addressof rules.
11203     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11204       if (uOp->getOpcode() == UO_Deref)
11205         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11206         // (assuming the deref expression is valid).
11207         return uOp->getSubExpr()->getType();
11208     }
11209     // Technically, there should be a check for array subscript
11210     // expressions here, but the result of one is always an lvalue anyway.
11211   }
11212   ValueDecl *dcl = getPrimaryDecl(op);
11213 
11214   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11215     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11216                                            op->getLocStart()))
11217       return QualType();
11218 
11219   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11220   unsigned AddressOfError = AO_No_Error;
11221 
11222   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11223     bool sfinae = (bool)isSFINAEContext();
11224     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11225                                   : diag::ext_typecheck_addrof_temporary)
11226       << op->getType() << op->getSourceRange();
11227     if (sfinae)
11228       return QualType();
11229     // Materialize the temporary as an lvalue so that we can take its address.
11230     OrigOp = op =
11231         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11232   } else if (isa<ObjCSelectorExpr>(op)) {
11233     return Context.getPointerType(op->getType());
11234   } else if (lval == Expr::LV_MemberFunction) {
11235     // If it's an instance method, make a member pointer.
11236     // The expression must have exactly the form &A::foo.
11237 
11238     // If the underlying expression isn't a decl ref, give up.
11239     if (!isa<DeclRefExpr>(op)) {
11240       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11241         << OrigOp.get()->getSourceRange();
11242       return QualType();
11243     }
11244     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11245     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11246 
11247     // The id-expression was parenthesized.
11248     if (OrigOp.get() != DRE) {
11249       Diag(OpLoc, diag::err_parens_pointer_member_function)
11250         << OrigOp.get()->getSourceRange();
11251 
11252     // The method was named without a qualifier.
11253     } else if (!DRE->getQualifier()) {
11254       if (MD->getParent()->getName().empty())
11255         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11256           << op->getSourceRange();
11257       else {
11258         SmallString<32> Str;
11259         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11260         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11261           << op->getSourceRange()
11262           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11263       }
11264     }
11265 
11266     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11267     if (isa<CXXDestructorDecl>(MD))
11268       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11269 
11270     QualType MPTy = Context.getMemberPointerType(
11271         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11272     // Under the MS ABI, lock down the inheritance model now.
11273     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11274       (void)isCompleteType(OpLoc, MPTy);
11275     return MPTy;
11276   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11277     // C99 6.5.3.2p1
11278     // The operand must be either an l-value or a function designator
11279     if (!op->getType()->isFunctionType()) {
11280       // Use a special diagnostic for loads from property references.
11281       if (isa<PseudoObjectExpr>(op)) {
11282         AddressOfError = AO_Property_Expansion;
11283       } else {
11284         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11285           << op->getType() << op->getSourceRange();
11286         return QualType();
11287       }
11288     }
11289   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11290     // The operand cannot be a bit-field
11291     AddressOfError = AO_Bit_Field;
11292   } else if (op->getObjectKind() == OK_VectorComponent) {
11293     // The operand cannot be an element of a vector
11294     AddressOfError = AO_Vector_Element;
11295   } else if (dcl) { // C99 6.5.3.2p1
11296     // We have an lvalue with a decl. Make sure the decl is not declared
11297     // with the register storage-class specifier.
11298     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11299       // in C++ it is not error to take address of a register
11300       // variable (c++03 7.1.1P3)
11301       if (vd->getStorageClass() == SC_Register &&
11302           !getLangOpts().CPlusPlus) {
11303         AddressOfError = AO_Register_Variable;
11304       }
11305     } else if (isa<MSPropertyDecl>(dcl)) {
11306       AddressOfError = AO_Property_Expansion;
11307     } else if (isa<FunctionTemplateDecl>(dcl)) {
11308       return Context.OverloadTy;
11309     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11310       // Okay: we can take the address of a field.
11311       // Could be a pointer to member, though, if there is an explicit
11312       // scope qualifier for the class.
11313       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11314         DeclContext *Ctx = dcl->getDeclContext();
11315         if (Ctx && Ctx->isRecord()) {
11316           if (dcl->getType()->isReferenceType()) {
11317             Diag(OpLoc,
11318                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11319               << dcl->getDeclName() << dcl->getType();
11320             return QualType();
11321           }
11322 
11323           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11324             Ctx = Ctx->getParent();
11325 
11326           QualType MPTy = Context.getMemberPointerType(
11327               op->getType(),
11328               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11329           // Under the MS ABI, lock down the inheritance model now.
11330           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11331             (void)isCompleteType(OpLoc, MPTy);
11332           return MPTy;
11333         }
11334       }
11335     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11336                !isa<BindingDecl>(dcl))
11337       llvm_unreachable("Unknown/unexpected decl type");
11338   }
11339 
11340   if (AddressOfError != AO_No_Error) {
11341     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11342     return QualType();
11343   }
11344 
11345   if (lval == Expr::LV_IncompleteVoidType) {
11346     // Taking the address of a void variable is technically illegal, but we
11347     // allow it in cases which are otherwise valid.
11348     // Example: "extern void x; void* y = &x;".
11349     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11350   }
11351 
11352   // If the operand has type "type", the result has type "pointer to type".
11353   if (op->getType()->isObjCObjectType())
11354     return Context.getObjCObjectPointerType(op->getType());
11355 
11356   CheckAddressOfPackedMember(op);
11357 
11358   return Context.getPointerType(op->getType());
11359 }
11360 
11361 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11362   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11363   if (!DRE)
11364     return;
11365   const Decl *D = DRE->getDecl();
11366   if (!D)
11367     return;
11368   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11369   if (!Param)
11370     return;
11371   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11372     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11373       return;
11374   if (FunctionScopeInfo *FD = S.getCurFunction())
11375     if (!FD->ModifiedNonNullParams.count(Param))
11376       FD->ModifiedNonNullParams.insert(Param);
11377 }
11378 
11379 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11380 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11381                                         SourceLocation OpLoc) {
11382   if (Op->isTypeDependent())
11383     return S.Context.DependentTy;
11384 
11385   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11386   if (ConvResult.isInvalid())
11387     return QualType();
11388   Op = ConvResult.get();
11389   QualType OpTy = Op->getType();
11390   QualType Result;
11391 
11392   if (isa<CXXReinterpretCastExpr>(Op)) {
11393     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11394     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11395                                      Op->getSourceRange());
11396   }
11397 
11398   if (const PointerType *PT = OpTy->getAs<PointerType>())
11399   {
11400     Result = PT->getPointeeType();
11401   }
11402   else if (const ObjCObjectPointerType *OPT =
11403              OpTy->getAs<ObjCObjectPointerType>())
11404     Result = OPT->getPointeeType();
11405   else {
11406     ExprResult PR = S.CheckPlaceholderExpr(Op);
11407     if (PR.isInvalid()) return QualType();
11408     if (PR.get() != Op)
11409       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11410   }
11411 
11412   if (Result.isNull()) {
11413     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11414       << OpTy << Op->getSourceRange();
11415     return QualType();
11416   }
11417 
11418   // Note that per both C89 and C99, indirection is always legal, even if Result
11419   // is an incomplete type or void.  It would be possible to warn about
11420   // dereferencing a void pointer, but it's completely well-defined, and such a
11421   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11422   // for pointers to 'void' but is fine for any other pointer type:
11423   //
11424   // C++ [expr.unary.op]p1:
11425   //   [...] the expression to which [the unary * operator] is applied shall
11426   //   be a pointer to an object type, or a pointer to a function type
11427   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11428     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11429       << OpTy << Op->getSourceRange();
11430 
11431   // Dereferences are usually l-values...
11432   VK = VK_LValue;
11433 
11434   // ...except that certain expressions are never l-values in C.
11435   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11436     VK = VK_RValue;
11437 
11438   return Result;
11439 }
11440 
11441 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11442   BinaryOperatorKind Opc;
11443   switch (Kind) {
11444   default: llvm_unreachable("Unknown binop!");
11445   case tok::periodstar:           Opc = BO_PtrMemD; break;
11446   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11447   case tok::star:                 Opc = BO_Mul; break;
11448   case tok::slash:                Opc = BO_Div; break;
11449   case tok::percent:              Opc = BO_Rem; break;
11450   case tok::plus:                 Opc = BO_Add; break;
11451   case tok::minus:                Opc = BO_Sub; break;
11452   case tok::lessless:             Opc = BO_Shl; break;
11453   case tok::greatergreater:       Opc = BO_Shr; break;
11454   case tok::lessequal:            Opc = BO_LE; break;
11455   case tok::less:                 Opc = BO_LT; break;
11456   case tok::greaterequal:         Opc = BO_GE; break;
11457   case tok::greater:              Opc = BO_GT; break;
11458   case tok::exclaimequal:         Opc = BO_NE; break;
11459   case tok::equalequal:           Opc = BO_EQ; break;
11460   case tok::spaceship:            Opc = BO_Cmp; break;
11461   case tok::amp:                  Opc = BO_And; break;
11462   case tok::caret:                Opc = BO_Xor; break;
11463   case tok::pipe:                 Opc = BO_Or; break;
11464   case tok::ampamp:               Opc = BO_LAnd; break;
11465   case tok::pipepipe:             Opc = BO_LOr; break;
11466   case tok::equal:                Opc = BO_Assign; break;
11467   case tok::starequal:            Opc = BO_MulAssign; break;
11468   case tok::slashequal:           Opc = BO_DivAssign; break;
11469   case tok::percentequal:         Opc = BO_RemAssign; break;
11470   case tok::plusequal:            Opc = BO_AddAssign; break;
11471   case tok::minusequal:           Opc = BO_SubAssign; break;
11472   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11473   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11474   case tok::ampequal:             Opc = BO_AndAssign; break;
11475   case tok::caretequal:           Opc = BO_XorAssign; break;
11476   case tok::pipeequal:            Opc = BO_OrAssign; break;
11477   case tok::comma:                Opc = BO_Comma; break;
11478   }
11479   return Opc;
11480 }
11481 
11482 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11483   tok::TokenKind Kind) {
11484   UnaryOperatorKind Opc;
11485   switch (Kind) {
11486   default: llvm_unreachable("Unknown unary op!");
11487   case tok::plusplus:     Opc = UO_PreInc; break;
11488   case tok::minusminus:   Opc = UO_PreDec; break;
11489   case tok::amp:          Opc = UO_AddrOf; break;
11490   case tok::star:         Opc = UO_Deref; break;
11491   case tok::plus:         Opc = UO_Plus; break;
11492   case tok::minus:        Opc = UO_Minus; break;
11493   case tok::tilde:        Opc = UO_Not; break;
11494   case tok::exclaim:      Opc = UO_LNot; break;
11495   case tok::kw___real:    Opc = UO_Real; break;
11496   case tok::kw___imag:    Opc = UO_Imag; break;
11497   case tok::kw___extension__: Opc = UO_Extension; break;
11498   }
11499   return Opc;
11500 }
11501 
11502 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11503 /// This warning suppressed in the event of macro expansions.
11504 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11505                                    SourceLocation OpLoc, bool IsBuiltin) {
11506   if (S.inTemplateInstantiation())
11507     return;
11508   if (S.isUnevaluatedContext())
11509     return;
11510   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11511     return;
11512   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11513   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11514   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11515   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11516   if (!LHSDeclRef || !RHSDeclRef ||
11517       LHSDeclRef->getLocation().isMacroID() ||
11518       RHSDeclRef->getLocation().isMacroID())
11519     return;
11520   const ValueDecl *LHSDecl =
11521     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11522   const ValueDecl *RHSDecl =
11523     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11524   if (LHSDecl != RHSDecl)
11525     return;
11526   if (LHSDecl->getType().isVolatileQualified())
11527     return;
11528   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11529     if (RefTy->getPointeeType().isVolatileQualified())
11530       return;
11531 
11532   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11533                           : diag::warn_self_assignment_overloaded)
11534       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11535       << RHSExpr->getSourceRange();
11536 }
11537 
11538 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11539 /// is usually indicative of introspection within the Objective-C pointer.
11540 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11541                                           SourceLocation OpLoc) {
11542   if (!S.getLangOpts().ObjC1)
11543     return;
11544 
11545   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11546   const Expr *LHS = L.get();
11547   const Expr *RHS = R.get();
11548 
11549   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11550     ObjCPointerExpr = LHS;
11551     OtherExpr = RHS;
11552   }
11553   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11554     ObjCPointerExpr = RHS;
11555     OtherExpr = LHS;
11556   }
11557 
11558   // This warning is deliberately made very specific to reduce false
11559   // positives with logic that uses '&' for hashing.  This logic mainly
11560   // looks for code trying to introspect into tagged pointers, which
11561   // code should generally never do.
11562   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11563     unsigned Diag = diag::warn_objc_pointer_masking;
11564     // Determine if we are introspecting the result of performSelectorXXX.
11565     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11566     // Special case messages to -performSelector and friends, which
11567     // can return non-pointer values boxed in a pointer value.
11568     // Some clients may wish to silence warnings in this subcase.
11569     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11570       Selector S = ME->getSelector();
11571       StringRef SelArg0 = S.getNameForSlot(0);
11572       if (SelArg0.startswith("performSelector"))
11573         Diag = diag::warn_objc_pointer_masking_performSelector;
11574     }
11575 
11576     S.Diag(OpLoc, Diag)
11577       << ObjCPointerExpr->getSourceRange();
11578   }
11579 }
11580 
11581 static NamedDecl *getDeclFromExpr(Expr *E) {
11582   if (!E)
11583     return nullptr;
11584   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11585     return DRE->getDecl();
11586   if (auto *ME = dyn_cast<MemberExpr>(E))
11587     return ME->getMemberDecl();
11588   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11589     return IRE->getDecl();
11590   return nullptr;
11591 }
11592 
11593 // This helper function promotes a binary operator's operands (which are of a
11594 // half vector type) to a vector of floats and then truncates the result to
11595 // a vector of either half or short.
11596 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11597                                       BinaryOperatorKind Opc, QualType ResultTy,
11598                                       ExprValueKind VK, ExprObjectKind OK,
11599                                       bool IsCompAssign, SourceLocation OpLoc,
11600                                       FPOptions FPFeatures) {
11601   auto &Context = S.getASTContext();
11602   assert((isVector(ResultTy, Context.HalfTy) ||
11603           isVector(ResultTy, Context.ShortTy)) &&
11604          "Result must be a vector of half or short");
11605   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11606          isVector(RHS.get()->getType(), Context.HalfTy) &&
11607          "both operands expected to be a half vector");
11608 
11609   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11610   QualType BinOpResTy = RHS.get()->getType();
11611 
11612   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11613   // change BinOpResTy to a vector of ints.
11614   if (isVector(ResultTy, Context.ShortTy))
11615     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11616 
11617   if (IsCompAssign)
11618     return new (Context) CompoundAssignOperator(
11619         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11620         OpLoc, FPFeatures);
11621 
11622   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11623   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11624                                           VK, OK, OpLoc, FPFeatures);
11625   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11626 }
11627 
11628 static std::pair<ExprResult, ExprResult>
11629 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11630                            Expr *RHSExpr) {
11631   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11632   if (!S.getLangOpts().CPlusPlus) {
11633     // C cannot handle TypoExpr nodes on either side of a binop because it
11634     // doesn't handle dependent types properly, so make sure any TypoExprs have
11635     // been dealt with before checking the operands.
11636     LHS = S.CorrectDelayedTyposInExpr(LHS);
11637     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11638       if (Opc != BO_Assign)
11639         return ExprResult(E);
11640       // Avoid correcting the RHS to the same Expr as the LHS.
11641       Decl *D = getDeclFromExpr(E);
11642       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11643     });
11644   }
11645   return std::make_pair(LHS, RHS);
11646 }
11647 
11648 /// Returns true if conversion between vectors of halfs and vectors of floats
11649 /// is needed.
11650 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11651                                      QualType SrcType) {
11652   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11653          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11654          isVector(SrcType, Ctx.HalfTy);
11655 }
11656 
11657 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11658 /// operator @p Opc at location @c TokLoc. This routine only supports
11659 /// built-in operations; ActOnBinOp handles overloaded operators.
11660 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11661                                     BinaryOperatorKind Opc,
11662                                     Expr *LHSExpr, Expr *RHSExpr) {
11663   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11664     // The syntax only allows initializer lists on the RHS of assignment,
11665     // so we don't need to worry about accepting invalid code for
11666     // non-assignment operators.
11667     // C++11 5.17p9:
11668     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11669     //   of x = {} is x = T().
11670     InitializationKind Kind = InitializationKind::CreateDirectList(
11671         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
11672     InitializedEntity Entity =
11673         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11674     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11675     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11676     if (Init.isInvalid())
11677       return Init;
11678     RHSExpr = Init.get();
11679   }
11680 
11681   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11682   QualType ResultTy;     // Result type of the binary operator.
11683   // The following two variables are used for compound assignment operators
11684   QualType CompLHSTy;    // Type of LHS after promotions for computation
11685   QualType CompResultTy; // Type of computation result
11686   ExprValueKind VK = VK_RValue;
11687   ExprObjectKind OK = OK_Ordinary;
11688   bool ConvertHalfVec = false;
11689 
11690   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11691   if (!LHS.isUsable() || !RHS.isUsable())
11692     return ExprError();
11693 
11694   if (getLangOpts().OpenCL) {
11695     QualType LHSTy = LHSExpr->getType();
11696     QualType RHSTy = RHSExpr->getType();
11697     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11698     // the ATOMIC_VAR_INIT macro.
11699     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11700       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11701       if (BO_Assign == Opc)
11702         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11703       else
11704         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11705       return ExprError();
11706     }
11707 
11708     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11709     // only with a builtin functions and therefore should be disallowed here.
11710     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11711         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11712         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11713         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11714       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11715       return ExprError();
11716     }
11717   }
11718 
11719   switch (Opc) {
11720   case BO_Assign:
11721     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11722     if (getLangOpts().CPlusPlus &&
11723         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11724       VK = LHS.get()->getValueKind();
11725       OK = LHS.get()->getObjectKind();
11726     }
11727     if (!ResultTy.isNull()) {
11728       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11729       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11730     }
11731     RecordModifiableNonNullParam(*this, LHS.get());
11732     break;
11733   case BO_PtrMemD:
11734   case BO_PtrMemI:
11735     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11736                                             Opc == BO_PtrMemI);
11737     break;
11738   case BO_Mul:
11739   case BO_Div:
11740     ConvertHalfVec = true;
11741     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11742                                            Opc == BO_Div);
11743     break;
11744   case BO_Rem:
11745     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11746     break;
11747   case BO_Add:
11748     ConvertHalfVec = true;
11749     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11750     break;
11751   case BO_Sub:
11752     ConvertHalfVec = true;
11753     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11754     break;
11755   case BO_Shl:
11756   case BO_Shr:
11757     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11758     break;
11759   case BO_LE:
11760   case BO_LT:
11761   case BO_GE:
11762   case BO_GT:
11763     ConvertHalfVec = true;
11764     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11765     break;
11766   case BO_EQ:
11767   case BO_NE:
11768     ConvertHalfVec = true;
11769     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11770     break;
11771   case BO_Cmp:
11772     // FIXME: Implement proper semantic checking of '<=>'.
11773     ConvertHalfVec = true;
11774     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11775     if (!ResultTy.isNull())
11776       ResultTy = Context.VoidTy;
11777     break;
11778   case BO_And:
11779     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11780     LLVM_FALLTHROUGH;
11781   case BO_Xor:
11782   case BO_Or:
11783     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11784     break;
11785   case BO_LAnd:
11786   case BO_LOr:
11787     ConvertHalfVec = true;
11788     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11789     break;
11790   case BO_MulAssign:
11791   case BO_DivAssign:
11792     ConvertHalfVec = true;
11793     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11794                                                Opc == BO_DivAssign);
11795     CompLHSTy = CompResultTy;
11796     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11797       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11798     break;
11799   case BO_RemAssign:
11800     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11801     CompLHSTy = CompResultTy;
11802     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11803       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11804     break;
11805   case BO_AddAssign:
11806     ConvertHalfVec = true;
11807     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11808     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11809       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11810     break;
11811   case BO_SubAssign:
11812     ConvertHalfVec = true;
11813     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11814     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11815       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11816     break;
11817   case BO_ShlAssign:
11818   case BO_ShrAssign:
11819     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11820     CompLHSTy = CompResultTy;
11821     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11822       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11823     break;
11824   case BO_AndAssign:
11825   case BO_OrAssign: // fallthrough
11826     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11827     LLVM_FALLTHROUGH;
11828   case BO_XorAssign:
11829     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11830     CompLHSTy = CompResultTy;
11831     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11832       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11833     break;
11834   case BO_Comma:
11835     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11836     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11837       VK = RHS.get()->getValueKind();
11838       OK = RHS.get()->getObjectKind();
11839     }
11840     break;
11841   }
11842   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11843     return ExprError();
11844 
11845   // Some of the binary operations require promoting operands of half vector to
11846   // float vectors and truncating the result back to half vector. For now, we do
11847   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
11848   // arm64).
11849   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
11850          isVector(LHS.get()->getType(), Context.HalfTy) &&
11851          "both sides are half vectors or neither sides are");
11852   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
11853                                             LHS.get()->getType());
11854 
11855   // Check for array bounds violations for both sides of the BinaryOperator
11856   CheckArrayAccess(LHS.get());
11857   CheckArrayAccess(RHS.get());
11858 
11859   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11860     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11861                                                  &Context.Idents.get("object_setClass"),
11862                                                  SourceLocation(), LookupOrdinaryName);
11863     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11864       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11865       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11866       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11867       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11868       FixItHint::CreateInsertion(RHSLocEnd, ")");
11869     }
11870     else
11871       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11872   }
11873   else if (const ObjCIvarRefExpr *OIRE =
11874            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11875     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11876 
11877   // Opc is not a compound assignment if CompResultTy is null.
11878   if (CompResultTy.isNull()) {
11879     if (ConvertHalfVec)
11880       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
11881                                  OpLoc, FPFeatures);
11882     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11883                                         OK, OpLoc, FPFeatures);
11884   }
11885 
11886   // Handle compound assignments.
11887   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11888       OK_ObjCProperty) {
11889     VK = VK_LValue;
11890     OK = LHS.get()->getObjectKind();
11891   }
11892 
11893   if (ConvertHalfVec)
11894     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
11895                                OpLoc, FPFeatures);
11896 
11897   return new (Context) CompoundAssignOperator(
11898       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11899       OpLoc, FPFeatures);
11900 }
11901 
11902 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11903 /// operators are mixed in a way that suggests that the programmer forgot that
11904 /// comparison operators have higher precedence. The most typical example of
11905 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11906 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11907                                       SourceLocation OpLoc, Expr *LHSExpr,
11908                                       Expr *RHSExpr) {
11909   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11910   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11911 
11912   // Check that one of the sides is a comparison operator and the other isn't.
11913   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11914   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11915   if (isLeftComp == isRightComp)
11916     return;
11917 
11918   // Bitwise operations are sometimes used as eager logical ops.
11919   // Don't diagnose this.
11920   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11921   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11922   if (isLeftBitwise || isRightBitwise)
11923     return;
11924 
11925   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11926                                                    OpLoc)
11927                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11928   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11929   SourceRange ParensRange = isLeftComp ?
11930       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11931     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11932 
11933   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11934     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11935   SuggestParentheses(Self, OpLoc,
11936     Self.PDiag(diag::note_precedence_silence) << OpStr,
11937     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11938   SuggestParentheses(Self, OpLoc,
11939     Self.PDiag(diag::note_precedence_bitwise_first)
11940       << BinaryOperator::getOpcodeStr(Opc),
11941     ParensRange);
11942 }
11943 
11944 /// \brief It accepts a '&&' expr that is inside a '||' one.
11945 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11946 /// in parentheses.
11947 static void
11948 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11949                                        BinaryOperator *Bop) {
11950   assert(Bop->getOpcode() == BO_LAnd);
11951   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11952       << Bop->getSourceRange() << OpLoc;
11953   SuggestParentheses(Self, Bop->getOperatorLoc(),
11954     Self.PDiag(diag::note_precedence_silence)
11955       << Bop->getOpcodeStr(),
11956     Bop->getSourceRange());
11957 }
11958 
11959 /// \brief Returns true if the given expression can be evaluated as a constant
11960 /// 'true'.
11961 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11962   bool Res;
11963   return !E->isValueDependent() &&
11964          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11965 }
11966 
11967 /// \brief Returns true if the given expression can be evaluated as a constant
11968 /// 'false'.
11969 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11970   bool Res;
11971   return !E->isValueDependent() &&
11972          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11973 }
11974 
11975 /// \brief Look for '&&' in the left hand of a '||' expr.
11976 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11977                                              Expr *LHSExpr, Expr *RHSExpr) {
11978   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11979     if (Bop->getOpcode() == BO_LAnd) {
11980       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11981       if (EvaluatesAsFalse(S, RHSExpr))
11982         return;
11983       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11984       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11985         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11986     } else if (Bop->getOpcode() == BO_LOr) {
11987       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11988         // If it's "a || b && 1 || c" we didn't warn earlier for
11989         // "a || b && 1", but warn now.
11990         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11991           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11992       }
11993     }
11994   }
11995 }
11996 
11997 /// \brief Look for '&&' in the right hand of a '||' expr.
11998 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11999                                              Expr *LHSExpr, Expr *RHSExpr) {
12000   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12001     if (Bop->getOpcode() == BO_LAnd) {
12002       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12003       if (EvaluatesAsFalse(S, LHSExpr))
12004         return;
12005       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12006       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12007         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12008     }
12009   }
12010 }
12011 
12012 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
12013 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12014 /// the '&' expression in parentheses.
12015 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12016                                          SourceLocation OpLoc, Expr *SubExpr) {
12017   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12018     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12019       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12020         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12021         << Bop->getSourceRange() << OpLoc;
12022       SuggestParentheses(S, Bop->getOperatorLoc(),
12023         S.PDiag(diag::note_precedence_silence)
12024           << Bop->getOpcodeStr(),
12025         Bop->getSourceRange());
12026     }
12027   }
12028 }
12029 
12030 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12031                                     Expr *SubExpr, StringRef Shift) {
12032   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12033     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12034       StringRef Op = Bop->getOpcodeStr();
12035       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12036           << Bop->getSourceRange() << OpLoc << Shift << Op;
12037       SuggestParentheses(S, Bop->getOperatorLoc(),
12038           S.PDiag(diag::note_precedence_silence) << Op,
12039           Bop->getSourceRange());
12040     }
12041   }
12042 }
12043 
12044 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12045                                  Expr *LHSExpr, Expr *RHSExpr) {
12046   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12047   if (!OCE)
12048     return;
12049 
12050   FunctionDecl *FD = OCE->getDirectCallee();
12051   if (!FD || !FD->isOverloadedOperator())
12052     return;
12053 
12054   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12055   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12056     return;
12057 
12058   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12059       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12060       << (Kind == OO_LessLess);
12061   SuggestParentheses(S, OCE->getOperatorLoc(),
12062                      S.PDiag(diag::note_precedence_silence)
12063                          << (Kind == OO_LessLess ? "<<" : ">>"),
12064                      OCE->getSourceRange());
12065   SuggestParentheses(S, OpLoc,
12066                      S.PDiag(diag::note_evaluate_comparison_first),
12067                      SourceRange(OCE->getArg(1)->getLocStart(),
12068                                  RHSExpr->getLocEnd()));
12069 }
12070 
12071 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12072 /// precedence.
12073 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12074                                     SourceLocation OpLoc, Expr *LHSExpr,
12075                                     Expr *RHSExpr){
12076   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12077   if (BinaryOperator::isBitwiseOp(Opc))
12078     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12079 
12080   // Diagnose "arg1 & arg2 | arg3"
12081   if ((Opc == BO_Or || Opc == BO_Xor) &&
12082       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12083     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12084     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12085   }
12086 
12087   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12088   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12089   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12090     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12091     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12092   }
12093 
12094   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12095       || Opc == BO_Shr) {
12096     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12097     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12098     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12099   }
12100 
12101   // Warn on overloaded shift operators and comparisons, such as:
12102   // cout << 5 == 4;
12103   if (BinaryOperator::isComparisonOp(Opc))
12104     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12105 }
12106 
12107 // Binary Operators.  'Tok' is the token for the operator.
12108 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12109                             tok::TokenKind Kind,
12110                             Expr *LHSExpr, Expr *RHSExpr) {
12111   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12112   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12113   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12114 
12115   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12116   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12117 
12118   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12119 }
12120 
12121 /// Build an overloaded binary operator expression in the given scope.
12122 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12123                                        BinaryOperatorKind Opc,
12124                                        Expr *LHS, Expr *RHS) {
12125   switch (Opc) {
12126   case BO_Assign:
12127   case BO_DivAssign:
12128   case BO_RemAssign:
12129   case BO_SubAssign:
12130   case BO_AndAssign:
12131   case BO_OrAssign:
12132   case BO_XorAssign:
12133     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12134     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12135     break;
12136   default:
12137     break;
12138   }
12139 
12140   // Find all of the overloaded operators visible from this
12141   // point. We perform both an operator-name lookup from the local
12142   // scope and an argument-dependent lookup based on the types of
12143   // the arguments.
12144   UnresolvedSet<16> Functions;
12145   OverloadedOperatorKind OverOp
12146     = BinaryOperator::getOverloadedOperator(Opc);
12147   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12148     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12149                                    RHS->getType(), Functions);
12150 
12151   // Build the (potentially-overloaded, potentially-dependent)
12152   // binary operation.
12153   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12154 }
12155 
12156 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12157                             BinaryOperatorKind Opc,
12158                             Expr *LHSExpr, Expr *RHSExpr) {
12159   ExprResult LHS, RHS;
12160   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12161   if (!LHS.isUsable() || !RHS.isUsable())
12162     return ExprError();
12163   LHSExpr = LHS.get();
12164   RHSExpr = RHS.get();
12165 
12166   // We want to end up calling one of checkPseudoObjectAssignment
12167   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12168   // both expressions are overloadable or either is type-dependent),
12169   // or CreateBuiltinBinOp (in any other case).  We also want to get
12170   // any placeholder types out of the way.
12171 
12172   // Handle pseudo-objects in the LHS.
12173   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12174     // Assignments with a pseudo-object l-value need special analysis.
12175     if (pty->getKind() == BuiltinType::PseudoObject &&
12176         BinaryOperator::isAssignmentOp(Opc))
12177       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12178 
12179     // Don't resolve overloads if the other type is overloadable.
12180     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12181       // We can't actually test that if we still have a placeholder,
12182       // though.  Fortunately, none of the exceptions we see in that
12183       // code below are valid when the LHS is an overload set.  Note
12184       // that an overload set can be dependently-typed, but it never
12185       // instantiates to having an overloadable type.
12186       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12187       if (resolvedRHS.isInvalid()) return ExprError();
12188       RHSExpr = resolvedRHS.get();
12189 
12190       if (RHSExpr->isTypeDependent() ||
12191           RHSExpr->getType()->isOverloadableType())
12192         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12193     }
12194 
12195     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12196     // template, diagnose the missing 'template' keyword instead of diagnosing
12197     // an invalid use of a bound member function.
12198     //
12199     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12200     // to C++1z [over.over]/1.4, but we already checked for that case above.
12201     if (Opc == BO_LT && inTemplateInstantiation() &&
12202         (pty->getKind() == BuiltinType::BoundMember ||
12203          pty->getKind() == BuiltinType::Overload)) {
12204       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12205       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12206           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12207             return isa<FunctionTemplateDecl>(ND);
12208           })) {
12209         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12210                                 : OE->getNameLoc(),
12211              diag::err_template_kw_missing)
12212           << OE->getName().getAsString() << "";
12213         return ExprError();
12214       }
12215     }
12216 
12217     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12218     if (LHS.isInvalid()) return ExprError();
12219     LHSExpr = LHS.get();
12220   }
12221 
12222   // Handle pseudo-objects in the RHS.
12223   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12224     // An overload in the RHS can potentially be resolved by the type
12225     // being assigned to.
12226     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12227       if (getLangOpts().CPlusPlus &&
12228           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12229            LHSExpr->getType()->isOverloadableType()))
12230         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12231 
12232       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12233     }
12234 
12235     // Don't resolve overloads if the other type is overloadable.
12236     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12237         LHSExpr->getType()->isOverloadableType())
12238       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12239 
12240     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12241     if (!resolvedRHS.isUsable()) return ExprError();
12242     RHSExpr = resolvedRHS.get();
12243   }
12244 
12245   if (getLangOpts().CPlusPlus) {
12246     // If either expression is type-dependent, always build an
12247     // overloaded op.
12248     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12249       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12250 
12251     // Otherwise, build an overloaded op if either expression has an
12252     // overloadable type.
12253     if (LHSExpr->getType()->isOverloadableType() ||
12254         RHSExpr->getType()->isOverloadableType())
12255       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12256   }
12257 
12258   // Build a built-in binary operation.
12259   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12260 }
12261 
12262 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12263   if (T.isNull() || T->isDependentType())
12264     return false;
12265 
12266   if (!T->isPromotableIntegerType())
12267     return true;
12268 
12269   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12270 }
12271 
12272 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12273                                       UnaryOperatorKind Opc,
12274                                       Expr *InputExpr) {
12275   ExprResult Input = InputExpr;
12276   ExprValueKind VK = VK_RValue;
12277   ExprObjectKind OK = OK_Ordinary;
12278   QualType resultType;
12279   bool CanOverflow = false;
12280 
12281   bool ConvertHalfVec = false;
12282   if (getLangOpts().OpenCL) {
12283     QualType Ty = InputExpr->getType();
12284     // The only legal unary operation for atomics is '&'.
12285     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12286     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12287     // only with a builtin functions and therefore should be disallowed here.
12288         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12289         || Ty->isBlockPointerType())) {
12290       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12291                        << InputExpr->getType()
12292                        << Input.get()->getSourceRange());
12293     }
12294   }
12295   switch (Opc) {
12296   case UO_PreInc:
12297   case UO_PreDec:
12298   case UO_PostInc:
12299   case UO_PostDec:
12300     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12301                                                 OpLoc,
12302                                                 Opc == UO_PreInc ||
12303                                                 Opc == UO_PostInc,
12304                                                 Opc == UO_PreInc ||
12305                                                 Opc == UO_PreDec);
12306     CanOverflow = isOverflowingIntegerType(Context, resultType);
12307     break;
12308   case UO_AddrOf:
12309     resultType = CheckAddressOfOperand(Input, OpLoc);
12310     RecordModifiableNonNullParam(*this, InputExpr);
12311     break;
12312   case UO_Deref: {
12313     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12314     if (Input.isInvalid()) return ExprError();
12315     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12316     break;
12317   }
12318   case UO_Plus:
12319   case UO_Minus:
12320     CanOverflow = Opc == UO_Minus &&
12321                   isOverflowingIntegerType(Context, Input.get()->getType());
12322     Input = UsualUnaryConversions(Input.get());
12323     if (Input.isInvalid()) return ExprError();
12324     // Unary plus and minus require promoting an operand of half vector to a
12325     // float vector and truncating the result back to a half vector. For now, we
12326     // do this only when HalfArgsAndReturns is set (that is, when the target is
12327     // arm or arm64).
12328     ConvertHalfVec =
12329         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12330 
12331     // If the operand is a half vector, promote it to a float vector.
12332     if (ConvertHalfVec)
12333       Input = convertVector(Input.get(), Context.FloatTy, *this);
12334     resultType = Input.get()->getType();
12335     if (resultType->isDependentType())
12336       break;
12337     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12338       break;
12339     else if (resultType->isVectorType() &&
12340              // The z vector extensions don't allow + or - with bool vectors.
12341              (!Context.getLangOpts().ZVector ||
12342               resultType->getAs<VectorType>()->getVectorKind() !=
12343               VectorType::AltiVecBool))
12344       break;
12345     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12346              Opc == UO_Plus &&
12347              resultType->isPointerType())
12348       break;
12349 
12350     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12351       << resultType << Input.get()->getSourceRange());
12352 
12353   case UO_Not: // bitwise complement
12354     Input = UsualUnaryConversions(Input.get());
12355     if (Input.isInvalid())
12356       return ExprError();
12357     resultType = Input.get()->getType();
12358 
12359     if (resultType->isDependentType())
12360       break;
12361     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12362     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12363       // C99 does not support '~' for complex conjugation.
12364       Diag(OpLoc, diag::ext_integer_complement_complex)
12365           << resultType << Input.get()->getSourceRange();
12366     else if (resultType->hasIntegerRepresentation())
12367       break;
12368     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12369       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12370       // on vector float types.
12371       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12372       if (!T->isIntegerType())
12373         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12374                           << resultType << Input.get()->getSourceRange());
12375     } else {
12376       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12377                        << resultType << Input.get()->getSourceRange());
12378     }
12379     break;
12380 
12381   case UO_LNot: // logical negation
12382     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12383     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12384     if (Input.isInvalid()) return ExprError();
12385     resultType = Input.get()->getType();
12386 
12387     // Though we still have to promote half FP to float...
12388     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12389       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12390       resultType = Context.FloatTy;
12391     }
12392 
12393     if (resultType->isDependentType())
12394       break;
12395     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12396       // C99 6.5.3.3p1: ok, fallthrough;
12397       if (Context.getLangOpts().CPlusPlus) {
12398         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12399         // operand contextually converted to bool.
12400         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12401                                   ScalarTypeToBooleanCastKind(resultType));
12402       } else if (Context.getLangOpts().OpenCL &&
12403                  Context.getLangOpts().OpenCLVersion < 120) {
12404         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12405         // operate on scalar float types.
12406         if (!resultType->isIntegerType() && !resultType->isPointerType())
12407           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12408                            << resultType << Input.get()->getSourceRange());
12409       }
12410     } else if (resultType->isExtVectorType()) {
12411       if (Context.getLangOpts().OpenCL &&
12412           Context.getLangOpts().OpenCLVersion < 120) {
12413         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12414         // operate on vector float types.
12415         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12416         if (!T->isIntegerType())
12417           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12418                            << resultType << Input.get()->getSourceRange());
12419       }
12420       // Vector logical not returns the signed variant of the operand type.
12421       resultType = GetSignedVectorType(resultType);
12422       break;
12423     } else {
12424       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12425       //        type in C++. We should allow that here too.
12426       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12427         << resultType << Input.get()->getSourceRange());
12428     }
12429 
12430     // LNot always has type int. C99 6.5.3.3p5.
12431     // In C++, it's bool. C++ 5.3.1p8
12432     resultType = Context.getLogicalOperationType();
12433     break;
12434   case UO_Real:
12435   case UO_Imag:
12436     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12437     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12438     // complex l-values to ordinary l-values and all other values to r-values.
12439     if (Input.isInvalid()) return ExprError();
12440     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12441       if (Input.get()->getValueKind() != VK_RValue &&
12442           Input.get()->getObjectKind() == OK_Ordinary)
12443         VK = Input.get()->getValueKind();
12444     } else if (!getLangOpts().CPlusPlus) {
12445       // In C, a volatile scalar is read by __imag. In C++, it is not.
12446       Input = DefaultLvalueConversion(Input.get());
12447     }
12448     break;
12449   case UO_Extension:
12450     resultType = Input.get()->getType();
12451     VK = Input.get()->getValueKind();
12452     OK = Input.get()->getObjectKind();
12453     break;
12454   case UO_Coawait:
12455     // It's unnecessary to represent the pass-through operator co_await in the
12456     // AST; just return the input expression instead.
12457     assert(!Input.get()->getType()->isDependentType() &&
12458                    "the co_await expression must be non-dependant before "
12459                    "building operator co_await");
12460     return Input;
12461   }
12462   if (resultType.isNull() || Input.isInvalid())
12463     return ExprError();
12464 
12465   // Check for array bounds violations in the operand of the UnaryOperator,
12466   // except for the '*' and '&' operators that have to be handled specially
12467   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12468   // that are explicitly defined as valid by the standard).
12469   if (Opc != UO_AddrOf && Opc != UO_Deref)
12470     CheckArrayAccess(Input.get());
12471 
12472   auto *UO = new (Context)
12473       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12474   // Convert the result back to a half vector.
12475   if (ConvertHalfVec)
12476     return convertVector(UO, Context.HalfTy, *this);
12477   return UO;
12478 }
12479 
12480 /// \brief Determine whether the given expression is a qualified member
12481 /// access expression, of a form that could be turned into a pointer to member
12482 /// with the address-of operator.
12483 static bool isQualifiedMemberAccess(Expr *E) {
12484   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12485     if (!DRE->getQualifier())
12486       return false;
12487 
12488     ValueDecl *VD = DRE->getDecl();
12489     if (!VD->isCXXClassMember())
12490       return false;
12491 
12492     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12493       return true;
12494     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12495       return Method->isInstance();
12496 
12497     return false;
12498   }
12499 
12500   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12501     if (!ULE->getQualifier())
12502       return false;
12503 
12504     for (NamedDecl *D : ULE->decls()) {
12505       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12506         if (Method->isInstance())
12507           return true;
12508       } else {
12509         // Overload set does not contain methods.
12510         break;
12511       }
12512     }
12513 
12514     return false;
12515   }
12516 
12517   return false;
12518 }
12519 
12520 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12521                               UnaryOperatorKind Opc, Expr *Input) {
12522   // First things first: handle placeholders so that the
12523   // overloaded-operator check considers the right type.
12524   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12525     // Increment and decrement of pseudo-object references.
12526     if (pty->getKind() == BuiltinType::PseudoObject &&
12527         UnaryOperator::isIncrementDecrementOp(Opc))
12528       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12529 
12530     // extension is always a builtin operator.
12531     if (Opc == UO_Extension)
12532       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12533 
12534     // & gets special logic for several kinds of placeholder.
12535     // The builtin code knows what to do.
12536     if (Opc == UO_AddrOf &&
12537         (pty->getKind() == BuiltinType::Overload ||
12538          pty->getKind() == BuiltinType::UnknownAny ||
12539          pty->getKind() == BuiltinType::BoundMember))
12540       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12541 
12542     // Anything else needs to be handled now.
12543     ExprResult Result = CheckPlaceholderExpr(Input);
12544     if (Result.isInvalid()) return ExprError();
12545     Input = Result.get();
12546   }
12547 
12548   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12549       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12550       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12551     // Find all of the overloaded operators visible from this
12552     // point. We perform both an operator-name lookup from the local
12553     // scope and an argument-dependent lookup based on the types of
12554     // the arguments.
12555     UnresolvedSet<16> Functions;
12556     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12557     if (S && OverOp != OO_None)
12558       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12559                                    Functions);
12560 
12561     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12562   }
12563 
12564   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12565 }
12566 
12567 // Unary Operators.  'Tok' is the token for the operator.
12568 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12569                               tok::TokenKind Op, Expr *Input) {
12570   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12571 }
12572 
12573 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12574 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12575                                 LabelDecl *TheDecl) {
12576   TheDecl->markUsed(Context);
12577   // Create the AST node.  The address of a label always has type 'void*'.
12578   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12579                                      Context.getPointerType(Context.VoidTy));
12580 }
12581 
12582 /// Given the last statement in a statement-expression, check whether
12583 /// the result is a producing expression (like a call to an
12584 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12585 /// release out of the full-expression.  Otherwise, return null.
12586 /// Cannot fail.
12587 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12588   // Should always be wrapped with one of these.
12589   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12590   if (!cleanups) return nullptr;
12591 
12592   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12593   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12594     return nullptr;
12595 
12596   // Splice out the cast.  This shouldn't modify any interesting
12597   // features of the statement.
12598   Expr *producer = cast->getSubExpr();
12599   assert(producer->getType() == cast->getType());
12600   assert(producer->getValueKind() == cast->getValueKind());
12601   cleanups->setSubExpr(producer);
12602   return cleanups;
12603 }
12604 
12605 void Sema::ActOnStartStmtExpr() {
12606   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12607 }
12608 
12609 void Sema::ActOnStmtExprError() {
12610   // Note that function is also called by TreeTransform when leaving a
12611   // StmtExpr scope without rebuilding anything.
12612 
12613   DiscardCleanupsInEvaluationContext();
12614   PopExpressionEvaluationContext();
12615 }
12616 
12617 ExprResult
12618 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12619                     SourceLocation RPLoc) { // "({..})"
12620   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12621   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12622 
12623   if (hasAnyUnrecoverableErrorsInThisFunction())
12624     DiscardCleanupsInEvaluationContext();
12625   assert(!Cleanup.exprNeedsCleanups() &&
12626          "cleanups within StmtExpr not correctly bound!");
12627   PopExpressionEvaluationContext();
12628 
12629   // FIXME: there are a variety of strange constraints to enforce here, for
12630   // example, it is not possible to goto into a stmt expression apparently.
12631   // More semantic analysis is needed.
12632 
12633   // If there are sub-stmts in the compound stmt, take the type of the last one
12634   // as the type of the stmtexpr.
12635   QualType Ty = Context.VoidTy;
12636   bool StmtExprMayBindToTemp = false;
12637   if (!Compound->body_empty()) {
12638     Stmt *LastStmt = Compound->body_back();
12639     LabelStmt *LastLabelStmt = nullptr;
12640     // If LastStmt is a label, skip down through into the body.
12641     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12642       LastLabelStmt = Label;
12643       LastStmt = Label->getSubStmt();
12644     }
12645 
12646     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12647       // Do function/array conversion on the last expression, but not
12648       // lvalue-to-rvalue.  However, initialize an unqualified type.
12649       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12650       if (LastExpr.isInvalid())
12651         return ExprError();
12652       Ty = LastExpr.get()->getType().getUnqualifiedType();
12653 
12654       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12655         // In ARC, if the final expression ends in a consume, splice
12656         // the consume out and bind it later.  In the alternate case
12657         // (when dealing with a retainable type), the result
12658         // initialization will create a produce.  In both cases the
12659         // result will be +1, and we'll need to balance that out with
12660         // a bind.
12661         if (Expr *rebuiltLastStmt
12662               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12663           LastExpr = rebuiltLastStmt;
12664         } else {
12665           LastExpr = PerformCopyInitialization(
12666                             InitializedEntity::InitializeResult(LPLoc,
12667                                                                 Ty,
12668                                                                 false),
12669                                                    SourceLocation(),
12670                                                LastExpr);
12671         }
12672 
12673         if (LastExpr.isInvalid())
12674           return ExprError();
12675         if (LastExpr.get() != nullptr) {
12676           if (!LastLabelStmt)
12677             Compound->setLastStmt(LastExpr.get());
12678           else
12679             LastLabelStmt->setSubStmt(LastExpr.get());
12680           StmtExprMayBindToTemp = true;
12681         }
12682       }
12683     }
12684   }
12685 
12686   // FIXME: Check that expression type is complete/non-abstract; statement
12687   // expressions are not lvalues.
12688   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12689   if (StmtExprMayBindToTemp)
12690     return MaybeBindToTemporary(ResStmtExpr);
12691   return ResStmtExpr;
12692 }
12693 
12694 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12695                                       TypeSourceInfo *TInfo,
12696                                       ArrayRef<OffsetOfComponent> Components,
12697                                       SourceLocation RParenLoc) {
12698   QualType ArgTy = TInfo->getType();
12699   bool Dependent = ArgTy->isDependentType();
12700   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12701 
12702   // We must have at least one component that refers to the type, and the first
12703   // one is known to be a field designator.  Verify that the ArgTy represents
12704   // a struct/union/class.
12705   if (!Dependent && !ArgTy->isRecordType())
12706     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12707                        << ArgTy << TypeRange);
12708 
12709   // Type must be complete per C99 7.17p3 because a declaring a variable
12710   // with an incomplete type would be ill-formed.
12711   if (!Dependent
12712       && RequireCompleteType(BuiltinLoc, ArgTy,
12713                              diag::err_offsetof_incomplete_type, TypeRange))
12714     return ExprError();
12715 
12716   bool DidWarnAboutNonPOD = false;
12717   QualType CurrentType = ArgTy;
12718   SmallVector<OffsetOfNode, 4> Comps;
12719   SmallVector<Expr*, 4> Exprs;
12720   for (const OffsetOfComponent &OC : Components) {
12721     if (OC.isBrackets) {
12722       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12723       if (!CurrentType->isDependentType()) {
12724         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12725         if(!AT)
12726           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12727                            << CurrentType);
12728         CurrentType = AT->getElementType();
12729       } else
12730         CurrentType = Context.DependentTy;
12731 
12732       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12733       if (IdxRval.isInvalid())
12734         return ExprError();
12735       Expr *Idx = IdxRval.get();
12736 
12737       // The expression must be an integral expression.
12738       // FIXME: An integral constant expression?
12739       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12740           !Idx->getType()->isIntegerType())
12741         return ExprError(Diag(Idx->getLocStart(),
12742                               diag::err_typecheck_subscript_not_integer)
12743                          << Idx->getSourceRange());
12744 
12745       // Record this array index.
12746       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12747       Exprs.push_back(Idx);
12748       continue;
12749     }
12750 
12751     // Offset of a field.
12752     if (CurrentType->isDependentType()) {
12753       // We have the offset of a field, but we can't look into the dependent
12754       // type. Just record the identifier of the field.
12755       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12756       CurrentType = Context.DependentTy;
12757       continue;
12758     }
12759 
12760     // We need to have a complete type to look into.
12761     if (RequireCompleteType(OC.LocStart, CurrentType,
12762                             diag::err_offsetof_incomplete_type))
12763       return ExprError();
12764 
12765     // Look for the designated field.
12766     const RecordType *RC = CurrentType->getAs<RecordType>();
12767     if (!RC)
12768       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12769                        << CurrentType);
12770     RecordDecl *RD = RC->getDecl();
12771 
12772     // C++ [lib.support.types]p5:
12773     //   The macro offsetof accepts a restricted set of type arguments in this
12774     //   International Standard. type shall be a POD structure or a POD union
12775     //   (clause 9).
12776     // C++11 [support.types]p4:
12777     //   If type is not a standard-layout class (Clause 9), the results are
12778     //   undefined.
12779     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12780       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12781       unsigned DiagID =
12782         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12783                             : diag::ext_offsetof_non_pod_type;
12784 
12785       if (!IsSafe && !DidWarnAboutNonPOD &&
12786           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12787                               PDiag(DiagID)
12788                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12789                               << CurrentType))
12790         DidWarnAboutNonPOD = true;
12791     }
12792 
12793     // Look for the field.
12794     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12795     LookupQualifiedName(R, RD);
12796     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12797     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12798     if (!MemberDecl) {
12799       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12800         MemberDecl = IndirectMemberDecl->getAnonField();
12801     }
12802 
12803     if (!MemberDecl)
12804       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12805                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12806                                                               OC.LocEnd));
12807 
12808     // C99 7.17p3:
12809     //   (If the specified member is a bit-field, the behavior is undefined.)
12810     //
12811     // We diagnose this as an error.
12812     if (MemberDecl->isBitField()) {
12813       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12814         << MemberDecl->getDeclName()
12815         << SourceRange(BuiltinLoc, RParenLoc);
12816       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12817       return ExprError();
12818     }
12819 
12820     RecordDecl *Parent = MemberDecl->getParent();
12821     if (IndirectMemberDecl)
12822       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12823 
12824     // If the member was found in a base class, introduce OffsetOfNodes for
12825     // the base class indirections.
12826     CXXBasePaths Paths;
12827     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12828                       Paths)) {
12829       if (Paths.getDetectedVirtual()) {
12830         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12831           << MemberDecl->getDeclName()
12832           << SourceRange(BuiltinLoc, RParenLoc);
12833         return ExprError();
12834       }
12835 
12836       CXXBasePath &Path = Paths.front();
12837       for (const CXXBasePathElement &B : Path)
12838         Comps.push_back(OffsetOfNode(B.Base));
12839     }
12840 
12841     if (IndirectMemberDecl) {
12842       for (auto *FI : IndirectMemberDecl->chain()) {
12843         assert(isa<FieldDecl>(FI));
12844         Comps.push_back(OffsetOfNode(OC.LocStart,
12845                                      cast<FieldDecl>(FI), OC.LocEnd));
12846       }
12847     } else
12848       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12849 
12850     CurrentType = MemberDecl->getType().getNonReferenceType();
12851   }
12852 
12853   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12854                               Comps, Exprs, RParenLoc);
12855 }
12856 
12857 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12858                                       SourceLocation BuiltinLoc,
12859                                       SourceLocation TypeLoc,
12860                                       ParsedType ParsedArgTy,
12861                                       ArrayRef<OffsetOfComponent> Components,
12862                                       SourceLocation RParenLoc) {
12863 
12864   TypeSourceInfo *ArgTInfo;
12865   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12866   if (ArgTy.isNull())
12867     return ExprError();
12868 
12869   if (!ArgTInfo)
12870     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12871 
12872   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12873 }
12874 
12875 
12876 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12877                                  Expr *CondExpr,
12878                                  Expr *LHSExpr, Expr *RHSExpr,
12879                                  SourceLocation RPLoc) {
12880   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12881 
12882   ExprValueKind VK = VK_RValue;
12883   ExprObjectKind OK = OK_Ordinary;
12884   QualType resType;
12885   bool ValueDependent = false;
12886   bool CondIsTrue = false;
12887   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12888     resType = Context.DependentTy;
12889     ValueDependent = true;
12890   } else {
12891     // The conditional expression is required to be a constant expression.
12892     llvm::APSInt condEval(32);
12893     ExprResult CondICE
12894       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12895           diag::err_typecheck_choose_expr_requires_constant, false);
12896     if (CondICE.isInvalid())
12897       return ExprError();
12898     CondExpr = CondICE.get();
12899     CondIsTrue = condEval.getZExtValue();
12900 
12901     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12902     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12903 
12904     resType = ActiveExpr->getType();
12905     ValueDependent = ActiveExpr->isValueDependent();
12906     VK = ActiveExpr->getValueKind();
12907     OK = ActiveExpr->getObjectKind();
12908   }
12909 
12910   return new (Context)
12911       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12912                  CondIsTrue, resType->isDependentType(), ValueDependent);
12913 }
12914 
12915 //===----------------------------------------------------------------------===//
12916 // Clang Extensions.
12917 //===----------------------------------------------------------------------===//
12918 
12919 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12920 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12921   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12922 
12923   if (LangOpts.CPlusPlus) {
12924     Decl *ManglingContextDecl;
12925     if (MangleNumberingContext *MCtx =
12926             getCurrentMangleNumberContext(Block->getDeclContext(),
12927                                           ManglingContextDecl)) {
12928       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12929       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12930     }
12931   }
12932 
12933   PushBlockScope(CurScope, Block);
12934   CurContext->addDecl(Block);
12935   if (CurScope)
12936     PushDeclContext(CurScope, Block);
12937   else
12938     CurContext = Block;
12939 
12940   getCurBlock()->HasImplicitReturnType = true;
12941 
12942   // Enter a new evaluation context to insulate the block from any
12943   // cleanups from the enclosing full-expression.
12944   PushExpressionEvaluationContext(
12945       ExpressionEvaluationContext::PotentiallyEvaluated);
12946 }
12947 
12948 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12949                                Scope *CurScope) {
12950   assert(ParamInfo.getIdentifier() == nullptr &&
12951          "block-id should have no identifier!");
12952   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
12953   BlockScopeInfo *CurBlock = getCurBlock();
12954 
12955   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12956   QualType T = Sig->getType();
12957 
12958   // FIXME: We should allow unexpanded parameter packs here, but that would,
12959   // in turn, make the block expression contain unexpanded parameter packs.
12960   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12961     // Drop the parameters.
12962     FunctionProtoType::ExtProtoInfo EPI;
12963     EPI.HasTrailingReturn = false;
12964     EPI.TypeQuals |= DeclSpec::TQ_const;
12965     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12966     Sig = Context.getTrivialTypeSourceInfo(T);
12967   }
12968 
12969   // GetTypeForDeclarator always produces a function type for a block
12970   // literal signature.  Furthermore, it is always a FunctionProtoType
12971   // unless the function was written with a typedef.
12972   assert(T->isFunctionType() &&
12973          "GetTypeForDeclarator made a non-function block signature");
12974 
12975   // Look for an explicit signature in that function type.
12976   FunctionProtoTypeLoc ExplicitSignature;
12977 
12978   if ((ExplicitSignature =
12979            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
12980 
12981     // Check whether that explicit signature was synthesized by
12982     // GetTypeForDeclarator.  If so, don't save that as part of the
12983     // written signature.
12984     if (ExplicitSignature.getLocalRangeBegin() ==
12985         ExplicitSignature.getLocalRangeEnd()) {
12986       // This would be much cheaper if we stored TypeLocs instead of
12987       // TypeSourceInfos.
12988       TypeLoc Result = ExplicitSignature.getReturnLoc();
12989       unsigned Size = Result.getFullDataSize();
12990       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12991       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12992 
12993       ExplicitSignature = FunctionProtoTypeLoc();
12994     }
12995   }
12996 
12997   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12998   CurBlock->FunctionType = T;
12999 
13000   const FunctionType *Fn = T->getAs<FunctionType>();
13001   QualType RetTy = Fn->getReturnType();
13002   bool isVariadic =
13003     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13004 
13005   CurBlock->TheDecl->setIsVariadic(isVariadic);
13006 
13007   // Context.DependentTy is used as a placeholder for a missing block
13008   // return type.  TODO:  what should we do with declarators like:
13009   //   ^ * { ... }
13010   // If the answer is "apply template argument deduction"....
13011   if (RetTy != Context.DependentTy) {
13012     CurBlock->ReturnType = RetTy;
13013     CurBlock->TheDecl->setBlockMissingReturnType(false);
13014     CurBlock->HasImplicitReturnType = false;
13015   }
13016 
13017   // Push block parameters from the declarator if we had them.
13018   SmallVector<ParmVarDecl*, 8> Params;
13019   if (ExplicitSignature) {
13020     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13021       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13022       if (Param->getIdentifier() == nullptr &&
13023           !Param->isImplicit() &&
13024           !Param->isInvalidDecl() &&
13025           !getLangOpts().CPlusPlus)
13026         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13027       Params.push_back(Param);
13028     }
13029 
13030   // Fake up parameter variables if we have a typedef, like
13031   //   ^ fntype { ... }
13032   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13033     for (const auto &I : Fn->param_types()) {
13034       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13035           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13036       Params.push_back(Param);
13037     }
13038   }
13039 
13040   // Set the parameters on the block decl.
13041   if (!Params.empty()) {
13042     CurBlock->TheDecl->setParams(Params);
13043     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13044                              /*CheckParameterNames=*/false);
13045   }
13046 
13047   // Finally we can process decl attributes.
13048   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13049 
13050   // Put the parameter variables in scope.
13051   for (auto AI : CurBlock->TheDecl->parameters()) {
13052     AI->setOwningFunction(CurBlock->TheDecl);
13053 
13054     // If this has an identifier, add it to the scope stack.
13055     if (AI->getIdentifier()) {
13056       CheckShadow(CurBlock->TheScope, AI);
13057 
13058       PushOnScopeChains(AI, CurBlock->TheScope);
13059     }
13060   }
13061 }
13062 
13063 /// ActOnBlockError - If there is an error parsing a block, this callback
13064 /// is invoked to pop the information about the block from the action impl.
13065 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13066   // Leave the expression-evaluation context.
13067   DiscardCleanupsInEvaluationContext();
13068   PopExpressionEvaluationContext();
13069 
13070   // Pop off CurBlock, handle nested blocks.
13071   PopDeclContext();
13072   PopFunctionScopeInfo();
13073 }
13074 
13075 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13076 /// literal was successfully completed.  ^(int x){...}
13077 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13078                                     Stmt *Body, Scope *CurScope) {
13079   // If blocks are disabled, emit an error.
13080   if (!LangOpts.Blocks)
13081     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13082 
13083   // Leave the expression-evaluation context.
13084   if (hasAnyUnrecoverableErrorsInThisFunction())
13085     DiscardCleanupsInEvaluationContext();
13086   assert(!Cleanup.exprNeedsCleanups() &&
13087          "cleanups within block not correctly bound!");
13088   PopExpressionEvaluationContext();
13089 
13090   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13091 
13092   if (BSI->HasImplicitReturnType)
13093     deduceClosureReturnType(*BSI);
13094 
13095   PopDeclContext();
13096 
13097   QualType RetTy = Context.VoidTy;
13098   if (!BSI->ReturnType.isNull())
13099     RetTy = BSI->ReturnType;
13100 
13101   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13102   QualType BlockTy;
13103 
13104   // Set the captured variables on the block.
13105   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13106   SmallVector<BlockDecl::Capture, 4> Captures;
13107   for (Capture &Cap : BSI->Captures) {
13108     if (Cap.isThisCapture())
13109       continue;
13110     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13111                               Cap.isNested(), Cap.getInitExpr());
13112     Captures.push_back(NewCap);
13113   }
13114   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13115 
13116   // If the user wrote a function type in some form, try to use that.
13117   if (!BSI->FunctionType.isNull()) {
13118     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13119 
13120     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13121     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13122 
13123     // Turn protoless block types into nullary block types.
13124     if (isa<FunctionNoProtoType>(FTy)) {
13125       FunctionProtoType::ExtProtoInfo EPI;
13126       EPI.ExtInfo = Ext;
13127       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13128 
13129     // Otherwise, if we don't need to change anything about the function type,
13130     // preserve its sugar structure.
13131     } else if (FTy->getReturnType() == RetTy &&
13132                (!NoReturn || FTy->getNoReturnAttr())) {
13133       BlockTy = BSI->FunctionType;
13134 
13135     // Otherwise, make the minimal modifications to the function type.
13136     } else {
13137       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13138       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13139       EPI.TypeQuals = 0; // FIXME: silently?
13140       EPI.ExtInfo = Ext;
13141       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13142     }
13143 
13144   // If we don't have a function type, just build one from nothing.
13145   } else {
13146     FunctionProtoType::ExtProtoInfo EPI;
13147     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13148     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13149   }
13150 
13151   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13152   BlockTy = Context.getBlockPointerType(BlockTy);
13153 
13154   // If needed, diagnose invalid gotos and switches in the block.
13155   if (getCurFunction()->NeedsScopeChecking() &&
13156       !PP.isCodeCompletionEnabled())
13157     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13158 
13159   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13160 
13161   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13162     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13163 
13164   // Try to apply the named return value optimization. We have to check again
13165   // if we can do this, though, because blocks keep return statements around
13166   // to deduce an implicit return type.
13167   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13168       !BSI->TheDecl->isDependentContext())
13169     computeNRVO(Body, BSI);
13170 
13171   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13172   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13173   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13174 
13175   // If the block isn't obviously global, i.e. it captures anything at
13176   // all, then we need to do a few things in the surrounding context:
13177   if (Result->getBlockDecl()->hasCaptures()) {
13178     // First, this expression has a new cleanup object.
13179     ExprCleanupObjects.push_back(Result->getBlockDecl());
13180     Cleanup.setExprNeedsCleanups(true);
13181 
13182     // It also gets a branch-protected scope if any of the captured
13183     // variables needs destruction.
13184     for (const auto &CI : Result->getBlockDecl()->captures()) {
13185       const VarDecl *var = CI.getVariable();
13186       if (var->getType().isDestructedType() != QualType::DK_none) {
13187         setFunctionHasBranchProtectedScope();
13188         break;
13189       }
13190     }
13191   }
13192 
13193   return Result;
13194 }
13195 
13196 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13197                             SourceLocation RPLoc) {
13198   TypeSourceInfo *TInfo;
13199   GetTypeFromParser(Ty, &TInfo);
13200   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13201 }
13202 
13203 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13204                                 Expr *E, TypeSourceInfo *TInfo,
13205                                 SourceLocation RPLoc) {
13206   Expr *OrigExpr = E;
13207   bool IsMS = false;
13208 
13209   // CUDA device code does not support varargs.
13210   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13211     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13212       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13213       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13214         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13215     }
13216   }
13217 
13218   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13219   // as Microsoft ABI on an actual Microsoft platform, where
13220   // __builtin_ms_va_list and __builtin_va_list are the same.)
13221   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13222       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13223     QualType MSVaListType = Context.getBuiltinMSVaListType();
13224     if (Context.hasSameType(MSVaListType, E->getType())) {
13225       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13226         return ExprError();
13227       IsMS = true;
13228     }
13229   }
13230 
13231   // Get the va_list type
13232   QualType VaListType = Context.getBuiltinVaListType();
13233   if (!IsMS) {
13234     if (VaListType->isArrayType()) {
13235       // Deal with implicit array decay; for example, on x86-64,
13236       // va_list is an array, but it's supposed to decay to
13237       // a pointer for va_arg.
13238       VaListType = Context.getArrayDecayedType(VaListType);
13239       // Make sure the input expression also decays appropriately.
13240       ExprResult Result = UsualUnaryConversions(E);
13241       if (Result.isInvalid())
13242         return ExprError();
13243       E = Result.get();
13244     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13245       // If va_list is a record type and we are compiling in C++ mode,
13246       // check the argument using reference binding.
13247       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13248           Context, Context.getLValueReferenceType(VaListType), false);
13249       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13250       if (Init.isInvalid())
13251         return ExprError();
13252       E = Init.getAs<Expr>();
13253     } else {
13254       // Otherwise, the va_list argument must be an l-value because
13255       // it is modified by va_arg.
13256       if (!E->isTypeDependent() &&
13257           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13258         return ExprError();
13259     }
13260   }
13261 
13262   if (!IsMS && !E->isTypeDependent() &&
13263       !Context.hasSameType(VaListType, E->getType()))
13264     return ExprError(Diag(E->getLocStart(),
13265                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13266       << OrigExpr->getType() << E->getSourceRange());
13267 
13268   if (!TInfo->getType()->isDependentType()) {
13269     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13270                             diag::err_second_parameter_to_va_arg_incomplete,
13271                             TInfo->getTypeLoc()))
13272       return ExprError();
13273 
13274     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13275                                TInfo->getType(),
13276                                diag::err_second_parameter_to_va_arg_abstract,
13277                                TInfo->getTypeLoc()))
13278       return ExprError();
13279 
13280     if (!TInfo->getType().isPODType(Context)) {
13281       Diag(TInfo->getTypeLoc().getBeginLoc(),
13282            TInfo->getType()->isObjCLifetimeType()
13283              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13284              : diag::warn_second_parameter_to_va_arg_not_pod)
13285         << TInfo->getType()
13286         << TInfo->getTypeLoc().getSourceRange();
13287     }
13288 
13289     // Check for va_arg where arguments of the given type will be promoted
13290     // (i.e. this va_arg is guaranteed to have undefined behavior).
13291     QualType PromoteType;
13292     if (TInfo->getType()->isPromotableIntegerType()) {
13293       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13294       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13295         PromoteType = QualType();
13296     }
13297     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13298       PromoteType = Context.DoubleTy;
13299     if (!PromoteType.isNull())
13300       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13301                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13302                           << TInfo->getType()
13303                           << PromoteType
13304                           << TInfo->getTypeLoc().getSourceRange());
13305   }
13306 
13307   QualType T = TInfo->getType().getNonLValueExprType(Context);
13308   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13309 }
13310 
13311 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13312   // The type of __null will be int or long, depending on the size of
13313   // pointers on the target.
13314   QualType Ty;
13315   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13316   if (pw == Context.getTargetInfo().getIntWidth())
13317     Ty = Context.IntTy;
13318   else if (pw == Context.getTargetInfo().getLongWidth())
13319     Ty = Context.LongTy;
13320   else if (pw == Context.getTargetInfo().getLongLongWidth())
13321     Ty = Context.LongLongTy;
13322   else {
13323     llvm_unreachable("I don't know size of pointer!");
13324   }
13325 
13326   return new (Context) GNUNullExpr(Ty, TokenLoc);
13327 }
13328 
13329 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13330                                               bool Diagnose) {
13331   if (!getLangOpts().ObjC1)
13332     return false;
13333 
13334   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13335   if (!PT)
13336     return false;
13337 
13338   if (!PT->isObjCIdType()) {
13339     // Check if the destination is the 'NSString' interface.
13340     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13341     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13342       return false;
13343   }
13344 
13345   // Ignore any parens, implicit casts (should only be
13346   // array-to-pointer decays), and not-so-opaque values.  The last is
13347   // important for making this trigger for property assignments.
13348   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13349   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13350     if (OV->getSourceExpr())
13351       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13352 
13353   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13354   if (!SL || !SL->isAscii())
13355     return false;
13356   if (Diagnose) {
13357     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13358       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13359     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13360   }
13361   return true;
13362 }
13363 
13364 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13365                                               const Expr *SrcExpr) {
13366   if (!DstType->isFunctionPointerType() ||
13367       !SrcExpr->getType()->isFunctionType())
13368     return false;
13369 
13370   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13371   if (!DRE)
13372     return false;
13373 
13374   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13375   if (!FD)
13376     return false;
13377 
13378   return !S.checkAddressOfFunctionIsAvailable(FD,
13379                                               /*Complain=*/true,
13380                                               SrcExpr->getLocStart());
13381 }
13382 
13383 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13384                                     SourceLocation Loc,
13385                                     QualType DstType, QualType SrcType,
13386                                     Expr *SrcExpr, AssignmentAction Action,
13387                                     bool *Complained) {
13388   if (Complained)
13389     *Complained = false;
13390 
13391   // Decode the result (notice that AST's are still created for extensions).
13392   bool CheckInferredResultType = false;
13393   bool isInvalid = false;
13394   unsigned DiagKind = 0;
13395   FixItHint Hint;
13396   ConversionFixItGenerator ConvHints;
13397   bool MayHaveConvFixit = false;
13398   bool MayHaveFunctionDiff = false;
13399   const ObjCInterfaceDecl *IFace = nullptr;
13400   const ObjCProtocolDecl *PDecl = nullptr;
13401 
13402   switch (ConvTy) {
13403   case Compatible:
13404       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13405       return false;
13406 
13407   case PointerToInt:
13408     DiagKind = diag::ext_typecheck_convert_pointer_int;
13409     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13410     MayHaveConvFixit = true;
13411     break;
13412   case IntToPointer:
13413     DiagKind = diag::ext_typecheck_convert_int_pointer;
13414     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13415     MayHaveConvFixit = true;
13416     break;
13417   case IncompatiblePointer:
13418     if (Action == AA_Passing_CFAudited)
13419       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13420     else if (SrcType->isFunctionPointerType() &&
13421              DstType->isFunctionPointerType())
13422       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13423     else
13424       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13425 
13426     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13427       SrcType->isObjCObjectPointerType();
13428     if (Hint.isNull() && !CheckInferredResultType) {
13429       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13430     }
13431     else if (CheckInferredResultType) {
13432       SrcType = SrcType.getUnqualifiedType();
13433       DstType = DstType.getUnqualifiedType();
13434     }
13435     MayHaveConvFixit = true;
13436     break;
13437   case IncompatiblePointerSign:
13438     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13439     break;
13440   case FunctionVoidPointer:
13441     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13442     break;
13443   case IncompatiblePointerDiscardsQualifiers: {
13444     // Perform array-to-pointer decay if necessary.
13445     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13446 
13447     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13448     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13449     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13450       DiagKind = diag::err_typecheck_incompatible_address_space;
13451       break;
13452 
13453 
13454     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13455       DiagKind = diag::err_typecheck_incompatible_ownership;
13456       break;
13457     }
13458 
13459     llvm_unreachable("unknown error case for discarding qualifiers!");
13460     // fallthrough
13461   }
13462   case CompatiblePointerDiscardsQualifiers:
13463     // If the qualifiers lost were because we were applying the
13464     // (deprecated) C++ conversion from a string literal to a char*
13465     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13466     // Ideally, this check would be performed in
13467     // checkPointerTypesForAssignment. However, that would require a
13468     // bit of refactoring (so that the second argument is an
13469     // expression, rather than a type), which should be done as part
13470     // of a larger effort to fix checkPointerTypesForAssignment for
13471     // C++ semantics.
13472     if (getLangOpts().CPlusPlus &&
13473         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13474       return false;
13475     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13476     break;
13477   case IncompatibleNestedPointerQualifiers:
13478     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13479     break;
13480   case IntToBlockPointer:
13481     DiagKind = diag::err_int_to_block_pointer;
13482     break;
13483   case IncompatibleBlockPointer:
13484     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13485     break;
13486   case IncompatibleObjCQualifiedId: {
13487     if (SrcType->isObjCQualifiedIdType()) {
13488       const ObjCObjectPointerType *srcOPT =
13489                 SrcType->getAs<ObjCObjectPointerType>();
13490       for (auto *srcProto : srcOPT->quals()) {
13491         PDecl = srcProto;
13492         break;
13493       }
13494       if (const ObjCInterfaceType *IFaceT =
13495             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13496         IFace = IFaceT->getDecl();
13497     }
13498     else if (DstType->isObjCQualifiedIdType()) {
13499       const ObjCObjectPointerType *dstOPT =
13500         DstType->getAs<ObjCObjectPointerType>();
13501       for (auto *dstProto : dstOPT->quals()) {
13502         PDecl = dstProto;
13503         break;
13504       }
13505       if (const ObjCInterfaceType *IFaceT =
13506             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13507         IFace = IFaceT->getDecl();
13508     }
13509     DiagKind = diag::warn_incompatible_qualified_id;
13510     break;
13511   }
13512   case IncompatibleVectors:
13513     DiagKind = diag::warn_incompatible_vectors;
13514     break;
13515   case IncompatibleObjCWeakRef:
13516     DiagKind = diag::err_arc_weak_unavailable_assign;
13517     break;
13518   case Incompatible:
13519     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13520       if (Complained)
13521         *Complained = true;
13522       return true;
13523     }
13524 
13525     DiagKind = diag::err_typecheck_convert_incompatible;
13526     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13527     MayHaveConvFixit = true;
13528     isInvalid = true;
13529     MayHaveFunctionDiff = true;
13530     break;
13531   }
13532 
13533   QualType FirstType, SecondType;
13534   switch (Action) {
13535   case AA_Assigning:
13536   case AA_Initializing:
13537     // The destination type comes first.
13538     FirstType = DstType;
13539     SecondType = SrcType;
13540     break;
13541 
13542   case AA_Returning:
13543   case AA_Passing:
13544   case AA_Passing_CFAudited:
13545   case AA_Converting:
13546   case AA_Sending:
13547   case AA_Casting:
13548     // The source type comes first.
13549     FirstType = SrcType;
13550     SecondType = DstType;
13551     break;
13552   }
13553 
13554   PartialDiagnostic FDiag = PDiag(DiagKind);
13555   if (Action == AA_Passing_CFAudited)
13556     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13557   else
13558     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13559 
13560   // If we can fix the conversion, suggest the FixIts.
13561   assert(ConvHints.isNull() || Hint.isNull());
13562   if (!ConvHints.isNull()) {
13563     for (FixItHint &H : ConvHints.Hints)
13564       FDiag << H;
13565   } else {
13566     FDiag << Hint;
13567   }
13568   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13569 
13570   if (MayHaveFunctionDiff)
13571     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13572 
13573   Diag(Loc, FDiag);
13574   if (DiagKind == diag::warn_incompatible_qualified_id &&
13575       PDecl && IFace && !IFace->hasDefinition())
13576       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13577         << IFace << PDecl;
13578 
13579   if (SecondType == Context.OverloadTy)
13580     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13581                               FirstType, /*TakingAddress=*/true);
13582 
13583   if (CheckInferredResultType)
13584     EmitRelatedResultTypeNote(SrcExpr);
13585 
13586   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13587     EmitRelatedResultTypeNoteForReturn(DstType);
13588 
13589   if (Complained)
13590     *Complained = true;
13591   return isInvalid;
13592 }
13593 
13594 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13595                                                  llvm::APSInt *Result) {
13596   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13597   public:
13598     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13599       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13600     }
13601   } Diagnoser;
13602 
13603   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13604 }
13605 
13606 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13607                                                  llvm::APSInt *Result,
13608                                                  unsigned DiagID,
13609                                                  bool AllowFold) {
13610   class IDDiagnoser : public VerifyICEDiagnoser {
13611     unsigned DiagID;
13612 
13613   public:
13614     IDDiagnoser(unsigned DiagID)
13615       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13616 
13617     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13618       S.Diag(Loc, DiagID) << SR;
13619     }
13620   } Diagnoser(DiagID);
13621 
13622   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13623 }
13624 
13625 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13626                                             SourceRange SR) {
13627   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13628 }
13629 
13630 ExprResult
13631 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13632                                       VerifyICEDiagnoser &Diagnoser,
13633                                       bool AllowFold) {
13634   SourceLocation DiagLoc = E->getLocStart();
13635 
13636   if (getLangOpts().CPlusPlus11) {
13637     // C++11 [expr.const]p5:
13638     //   If an expression of literal class type is used in a context where an
13639     //   integral constant expression is required, then that class type shall
13640     //   have a single non-explicit conversion function to an integral or
13641     //   unscoped enumeration type
13642     ExprResult Converted;
13643     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13644     public:
13645       CXX11ConvertDiagnoser(bool Silent)
13646           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13647                                 Silent, true) {}
13648 
13649       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13650                                            QualType T) override {
13651         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13652       }
13653 
13654       SemaDiagnosticBuilder diagnoseIncomplete(
13655           Sema &S, SourceLocation Loc, QualType T) override {
13656         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13657       }
13658 
13659       SemaDiagnosticBuilder diagnoseExplicitConv(
13660           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13661         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13662       }
13663 
13664       SemaDiagnosticBuilder noteExplicitConv(
13665           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13666         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13667                  << ConvTy->isEnumeralType() << ConvTy;
13668       }
13669 
13670       SemaDiagnosticBuilder diagnoseAmbiguous(
13671           Sema &S, SourceLocation Loc, QualType T) override {
13672         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13673       }
13674 
13675       SemaDiagnosticBuilder noteAmbiguous(
13676           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13677         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13678                  << ConvTy->isEnumeralType() << ConvTy;
13679       }
13680 
13681       SemaDiagnosticBuilder diagnoseConversion(
13682           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13683         llvm_unreachable("conversion functions are permitted");
13684       }
13685     } ConvertDiagnoser(Diagnoser.Suppress);
13686 
13687     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13688                                                     ConvertDiagnoser);
13689     if (Converted.isInvalid())
13690       return Converted;
13691     E = Converted.get();
13692     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13693       return ExprError();
13694   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13695     // An ICE must be of integral or unscoped enumeration type.
13696     if (!Diagnoser.Suppress)
13697       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13698     return ExprError();
13699   }
13700 
13701   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13702   // in the non-ICE case.
13703   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13704     if (Result)
13705       *Result = E->EvaluateKnownConstInt(Context);
13706     return E;
13707   }
13708 
13709   Expr::EvalResult EvalResult;
13710   SmallVector<PartialDiagnosticAt, 8> Notes;
13711   EvalResult.Diag = &Notes;
13712 
13713   // Try to evaluate the expression, and produce diagnostics explaining why it's
13714   // not a constant expression as a side-effect.
13715   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13716                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13717 
13718   // In C++11, we can rely on diagnostics being produced for any expression
13719   // which is not a constant expression. If no diagnostics were produced, then
13720   // this is a constant expression.
13721   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13722     if (Result)
13723       *Result = EvalResult.Val.getInt();
13724     return E;
13725   }
13726 
13727   // If our only note is the usual "invalid subexpression" note, just point
13728   // the caret at its location rather than producing an essentially
13729   // redundant note.
13730   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13731         diag::note_invalid_subexpr_in_const_expr) {
13732     DiagLoc = Notes[0].first;
13733     Notes.clear();
13734   }
13735 
13736   if (!Folded || !AllowFold) {
13737     if (!Diagnoser.Suppress) {
13738       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13739       for (const PartialDiagnosticAt &Note : Notes)
13740         Diag(Note.first, Note.second);
13741     }
13742 
13743     return ExprError();
13744   }
13745 
13746   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13747   for (const PartialDiagnosticAt &Note : Notes)
13748     Diag(Note.first, Note.second);
13749 
13750   if (Result)
13751     *Result = EvalResult.Val.getInt();
13752   return E;
13753 }
13754 
13755 namespace {
13756   // Handle the case where we conclude a expression which we speculatively
13757   // considered to be unevaluated is actually evaluated.
13758   class TransformToPE : public TreeTransform<TransformToPE> {
13759     typedef TreeTransform<TransformToPE> BaseTransform;
13760 
13761   public:
13762     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13763 
13764     // Make sure we redo semantic analysis
13765     bool AlwaysRebuild() { return true; }
13766 
13767     // Make sure we handle LabelStmts correctly.
13768     // FIXME: This does the right thing, but maybe we need a more general
13769     // fix to TreeTransform?
13770     StmtResult TransformLabelStmt(LabelStmt *S) {
13771       S->getDecl()->setStmt(nullptr);
13772       return BaseTransform::TransformLabelStmt(S);
13773     }
13774 
13775     // We need to special-case DeclRefExprs referring to FieldDecls which
13776     // are not part of a member pointer formation; normal TreeTransforming
13777     // doesn't catch this case because of the way we represent them in the AST.
13778     // FIXME: This is a bit ugly; is it really the best way to handle this
13779     // case?
13780     //
13781     // Error on DeclRefExprs referring to FieldDecls.
13782     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13783       if (isa<FieldDecl>(E->getDecl()) &&
13784           !SemaRef.isUnevaluatedContext())
13785         return SemaRef.Diag(E->getLocation(),
13786                             diag::err_invalid_non_static_member_use)
13787             << E->getDecl() << E->getSourceRange();
13788 
13789       return BaseTransform::TransformDeclRefExpr(E);
13790     }
13791 
13792     // Exception: filter out member pointer formation
13793     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13794       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13795         return E;
13796 
13797       return BaseTransform::TransformUnaryOperator(E);
13798     }
13799 
13800     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13801       // Lambdas never need to be transformed.
13802       return E;
13803     }
13804   };
13805 }
13806 
13807 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13808   assert(isUnevaluatedContext() &&
13809          "Should only transform unevaluated expressions");
13810   ExprEvalContexts.back().Context =
13811       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13812   if (isUnevaluatedContext())
13813     return E;
13814   return TransformToPE(*this).TransformExpr(E);
13815 }
13816 
13817 void
13818 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13819                                       Decl *LambdaContextDecl,
13820                                       bool IsDecltype) {
13821   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13822                                 LambdaContextDecl, IsDecltype);
13823   Cleanup.reset();
13824   if (!MaybeODRUseExprs.empty())
13825     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13826 }
13827 
13828 void
13829 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13830                                       ReuseLambdaContextDecl_t,
13831                                       bool IsDecltype) {
13832   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13833   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13834 }
13835 
13836 void Sema::PopExpressionEvaluationContext() {
13837   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13838   unsigned NumTypos = Rec.NumTypos;
13839 
13840   if (!Rec.Lambdas.empty()) {
13841     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13842       unsigned D;
13843       if (Rec.isUnevaluated()) {
13844         // C++11 [expr.prim.lambda]p2:
13845         //   A lambda-expression shall not appear in an unevaluated operand
13846         //   (Clause 5).
13847         D = diag::err_lambda_unevaluated_operand;
13848       } else {
13849         // C++1y [expr.const]p2:
13850         //   A conditional-expression e is a core constant expression unless the
13851         //   evaluation of e, following the rules of the abstract machine, would
13852         //   evaluate [...] a lambda-expression.
13853         D = diag::err_lambda_in_constant_expression;
13854       }
13855 
13856       // C++1z allows lambda expressions as core constant expressions.
13857       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13858       // 1607) from appearing within template-arguments and array-bounds that
13859       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13860       // unevaluated contexts) might lift some of these restrictions in a
13861       // future version.
13862       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
13863         for (const auto *L : Rec.Lambdas)
13864           Diag(L->getLocStart(), D);
13865     } else {
13866       // Mark the capture expressions odr-used. This was deferred
13867       // during lambda expression creation.
13868       for (auto *Lambda : Rec.Lambdas) {
13869         for (auto *C : Lambda->capture_inits())
13870           MarkDeclarationsReferencedInExpr(C);
13871       }
13872     }
13873   }
13874 
13875   // When are coming out of an unevaluated context, clear out any
13876   // temporaries that we may have created as part of the evaluation of
13877   // the expression in that context: they aren't relevant because they
13878   // will never be constructed.
13879   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13880     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13881                              ExprCleanupObjects.end());
13882     Cleanup = Rec.ParentCleanup;
13883     CleanupVarDeclMarking();
13884     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13885   // Otherwise, merge the contexts together.
13886   } else {
13887     Cleanup.mergeFrom(Rec.ParentCleanup);
13888     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13889                             Rec.SavedMaybeODRUseExprs.end());
13890   }
13891 
13892   // Pop the current expression evaluation context off the stack.
13893   ExprEvalContexts.pop_back();
13894 
13895   if (!ExprEvalContexts.empty())
13896     ExprEvalContexts.back().NumTypos += NumTypos;
13897   else
13898     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13899                             "last ExpressionEvaluationContextRecord");
13900 }
13901 
13902 void Sema::DiscardCleanupsInEvaluationContext() {
13903   ExprCleanupObjects.erase(
13904          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13905          ExprCleanupObjects.end());
13906   Cleanup.reset();
13907   MaybeODRUseExprs.clear();
13908 }
13909 
13910 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13911   if (!E->getType()->isVariablyModifiedType())
13912     return E;
13913   return TransformToPotentiallyEvaluated(E);
13914 }
13915 
13916 /// Are we within a context in which some evaluation could be performed (be it
13917 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13918 /// captured by C++'s idea of an "unevaluated context".
13919 static bool isEvaluatableContext(Sema &SemaRef) {
13920   switch (SemaRef.ExprEvalContexts.back().Context) {
13921     case Sema::ExpressionEvaluationContext::Unevaluated:
13922     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13923     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13924       // Expressions in this context are never evaluated.
13925       return false;
13926 
13927     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13928     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13929     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13930       // Expressions in this context could be evaluated.
13931       return true;
13932 
13933     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13934       // Referenced declarations will only be used if the construct in the
13935       // containing expression is used, at which point we'll be given another
13936       // turn to mark them.
13937       return false;
13938   }
13939   llvm_unreachable("Invalid context");
13940 }
13941 
13942 /// Are we within a context in which references to resolved functions or to
13943 /// variables result in odr-use?
13944 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13945   // An expression in a template is not really an expression until it's been
13946   // instantiated, so it doesn't trigger odr-use.
13947   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13948     return false;
13949 
13950   switch (SemaRef.ExprEvalContexts.back().Context) {
13951     case Sema::ExpressionEvaluationContext::Unevaluated:
13952     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13953     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13954     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13955       return false;
13956 
13957     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13958     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13959       return true;
13960 
13961     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13962       return false;
13963   }
13964   llvm_unreachable("Invalid context");
13965 }
13966 
13967 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13968   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13969   return Func->isConstexpr() &&
13970          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13971 }
13972 
13973 /// \brief Mark a function referenced, and check whether it is odr-used
13974 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13975 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13976                                   bool MightBeOdrUse) {
13977   assert(Func && "No function?");
13978 
13979   Func->setReferenced();
13980 
13981   // C++11 [basic.def.odr]p3:
13982   //   A function whose name appears as a potentially-evaluated expression is
13983   //   odr-used if it is the unique lookup result or the selected member of a
13984   //   set of overloaded functions [...].
13985   //
13986   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13987   // can just check that here.
13988   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13989 
13990   // Determine whether we require a function definition to exist, per
13991   // C++11 [temp.inst]p3:
13992   //   Unless a function template specialization has been explicitly
13993   //   instantiated or explicitly specialized, the function template
13994   //   specialization is implicitly instantiated when the specialization is
13995   //   referenced in a context that requires a function definition to exist.
13996   //
13997   // That is either when this is an odr-use, or when a usage of a constexpr
13998   // function occurs within an evaluatable context.
13999   bool NeedDefinition =
14000       OdrUse || (isEvaluatableContext(*this) &&
14001                  isImplicitlyDefinableConstexprFunction(Func));
14002 
14003   // C++14 [temp.expl.spec]p6:
14004   //   If a template [...] is explicitly specialized then that specialization
14005   //   shall be declared before the first use of that specialization that would
14006   //   cause an implicit instantiation to take place, in every translation unit
14007   //   in which such a use occurs
14008   if (NeedDefinition &&
14009       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14010        Func->getMemberSpecializationInfo()))
14011     checkSpecializationVisibility(Loc, Func);
14012 
14013   // C++14 [except.spec]p17:
14014   //   An exception-specification is considered to be needed when:
14015   //   - the function is odr-used or, if it appears in an unevaluated operand,
14016   //     would be odr-used if the expression were potentially-evaluated;
14017   //
14018   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14019   // function is a pure virtual function we're calling, and in that case the
14020   // function was selected by overload resolution and we need to resolve its
14021   // exception specification for a different reason.
14022   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14023   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14024     ResolveExceptionSpec(Loc, FPT);
14025 
14026   // If we don't need to mark the function as used, and we don't need to
14027   // try to provide a definition, there's nothing more to do.
14028   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14029       (!NeedDefinition || Func->getBody()))
14030     return;
14031 
14032   // Note that this declaration has been used.
14033   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14034     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14035     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14036       if (Constructor->isDefaultConstructor()) {
14037         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14038           return;
14039         DefineImplicitDefaultConstructor(Loc, Constructor);
14040       } else if (Constructor->isCopyConstructor()) {
14041         DefineImplicitCopyConstructor(Loc, Constructor);
14042       } else if (Constructor->isMoveConstructor()) {
14043         DefineImplicitMoveConstructor(Loc, Constructor);
14044       }
14045     } else if (Constructor->getInheritedConstructor()) {
14046       DefineInheritingConstructor(Loc, Constructor);
14047     }
14048   } else if (CXXDestructorDecl *Destructor =
14049                  dyn_cast<CXXDestructorDecl>(Func)) {
14050     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14051     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14052       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14053         return;
14054       DefineImplicitDestructor(Loc, Destructor);
14055     }
14056     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14057       MarkVTableUsed(Loc, Destructor->getParent());
14058   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14059     if (MethodDecl->isOverloadedOperator() &&
14060         MethodDecl->getOverloadedOperator() == OO_Equal) {
14061       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14062       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14063         if (MethodDecl->isCopyAssignmentOperator())
14064           DefineImplicitCopyAssignment(Loc, MethodDecl);
14065         else if (MethodDecl->isMoveAssignmentOperator())
14066           DefineImplicitMoveAssignment(Loc, MethodDecl);
14067       }
14068     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14069                MethodDecl->getParent()->isLambda()) {
14070       CXXConversionDecl *Conversion =
14071           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14072       if (Conversion->isLambdaToBlockPointerConversion())
14073         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14074       else
14075         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14076     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14077       MarkVTableUsed(Loc, MethodDecl->getParent());
14078   }
14079 
14080   // Recursive functions should be marked when used from another function.
14081   // FIXME: Is this really right?
14082   if (CurContext == Func) return;
14083 
14084   // Implicit instantiation of function templates and member functions of
14085   // class templates.
14086   if (Func->isImplicitlyInstantiable()) {
14087     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14088     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14089     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14090     if (FirstInstantiation) {
14091       PointOfInstantiation = Loc;
14092       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14093     } else if (TSK != TSK_ImplicitInstantiation) {
14094       // Use the point of use as the point of instantiation, instead of the
14095       // point of explicit instantiation (which we track as the actual point of
14096       // instantiation). This gives better backtraces in diagnostics.
14097       PointOfInstantiation = Loc;
14098     }
14099 
14100     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14101         Func->isConstexpr()) {
14102       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14103           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14104           CodeSynthesisContexts.size())
14105         PendingLocalImplicitInstantiations.push_back(
14106             std::make_pair(Func, PointOfInstantiation));
14107       else if (Func->isConstexpr())
14108         // Do not defer instantiations of constexpr functions, to avoid the
14109         // expression evaluator needing to call back into Sema if it sees a
14110         // call to such a function.
14111         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14112       else {
14113         Func->setInstantiationIsPending(true);
14114         PendingInstantiations.push_back(std::make_pair(Func,
14115                                                        PointOfInstantiation));
14116         // Notify the consumer that a function was implicitly instantiated.
14117         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14118       }
14119     }
14120   } else {
14121     // Walk redefinitions, as some of them may be instantiable.
14122     for (auto i : Func->redecls()) {
14123       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14124         MarkFunctionReferenced(Loc, i, OdrUse);
14125     }
14126   }
14127 
14128   if (!OdrUse) return;
14129 
14130   // Keep track of used but undefined functions.
14131   if (!Func->isDefined()) {
14132     if (mightHaveNonExternalLinkage(Func))
14133       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14134     else if (Func->getMostRecentDecl()->isInlined() &&
14135              !LangOpts.GNUInline &&
14136              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14137       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14138     else if (isExternalWithNoLinkageType(Func))
14139       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14140   }
14141 
14142   Func->markUsed(Context);
14143 }
14144 
14145 static void
14146 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14147                                    ValueDecl *var, DeclContext *DC) {
14148   DeclContext *VarDC = var->getDeclContext();
14149 
14150   //  If the parameter still belongs to the translation unit, then
14151   //  we're actually just using one parameter in the declaration of
14152   //  the next.
14153   if (isa<ParmVarDecl>(var) &&
14154       isa<TranslationUnitDecl>(VarDC))
14155     return;
14156 
14157   // For C code, don't diagnose about capture if we're not actually in code
14158   // right now; it's impossible to write a non-constant expression outside of
14159   // function context, so we'll get other (more useful) diagnostics later.
14160   //
14161   // For C++, things get a bit more nasty... it would be nice to suppress this
14162   // diagnostic for certain cases like using a local variable in an array bound
14163   // for a member of a local class, but the correct predicate is not obvious.
14164   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14165     return;
14166 
14167   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14168   unsigned ContextKind = 3; // unknown
14169   if (isa<CXXMethodDecl>(VarDC) &&
14170       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14171     ContextKind = 2;
14172   } else if (isa<FunctionDecl>(VarDC)) {
14173     ContextKind = 0;
14174   } else if (isa<BlockDecl>(VarDC)) {
14175     ContextKind = 1;
14176   }
14177 
14178   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14179     << var << ValueKind << ContextKind << VarDC;
14180   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14181       << var;
14182 
14183   // FIXME: Add additional diagnostic info about class etc. which prevents
14184   // capture.
14185 }
14186 
14187 
14188 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14189                                       bool &SubCapturesAreNested,
14190                                       QualType &CaptureType,
14191                                       QualType &DeclRefType) {
14192    // Check whether we've already captured it.
14193   if (CSI->CaptureMap.count(Var)) {
14194     // If we found a capture, any subcaptures are nested.
14195     SubCapturesAreNested = true;
14196 
14197     // Retrieve the capture type for this variable.
14198     CaptureType = CSI->getCapture(Var).getCaptureType();
14199 
14200     // Compute the type of an expression that refers to this variable.
14201     DeclRefType = CaptureType.getNonReferenceType();
14202 
14203     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14204     // are mutable in the sense that user can change their value - they are
14205     // private instances of the captured declarations.
14206     const Capture &Cap = CSI->getCapture(Var);
14207     if (Cap.isCopyCapture() &&
14208         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14209         !(isa<CapturedRegionScopeInfo>(CSI) &&
14210           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14211       DeclRefType.addConst();
14212     return true;
14213   }
14214   return false;
14215 }
14216 
14217 // Only block literals, captured statements, and lambda expressions can
14218 // capture; other scopes don't work.
14219 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14220                                  SourceLocation Loc,
14221                                  const bool Diagnose, Sema &S) {
14222   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14223     return getLambdaAwareParentOfDeclContext(DC);
14224   else if (Var->hasLocalStorage()) {
14225     if (Diagnose)
14226        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14227   }
14228   return nullptr;
14229 }
14230 
14231 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14232 // certain types of variables (unnamed, variably modified types etc.)
14233 // so check for eligibility.
14234 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14235                                  SourceLocation Loc,
14236                                  const bool Diagnose, Sema &S) {
14237 
14238   bool IsBlock = isa<BlockScopeInfo>(CSI);
14239   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14240 
14241   // Lambdas are not allowed to capture unnamed variables
14242   // (e.g. anonymous unions).
14243   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14244   // assuming that's the intent.
14245   if (IsLambda && !Var->getDeclName()) {
14246     if (Diagnose) {
14247       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14248       S.Diag(Var->getLocation(), diag::note_declared_at);
14249     }
14250     return false;
14251   }
14252 
14253   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14254   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14255     if (Diagnose) {
14256       S.Diag(Loc, diag::err_ref_vm_type);
14257       S.Diag(Var->getLocation(), diag::note_previous_decl)
14258         << Var->getDeclName();
14259     }
14260     return false;
14261   }
14262   // Prohibit structs with flexible array members too.
14263   // We cannot capture what is in the tail end of the struct.
14264   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14265     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14266       if (Diagnose) {
14267         if (IsBlock)
14268           S.Diag(Loc, diag::err_ref_flexarray_type);
14269         else
14270           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14271             << Var->getDeclName();
14272         S.Diag(Var->getLocation(), diag::note_previous_decl)
14273           << Var->getDeclName();
14274       }
14275       return false;
14276     }
14277   }
14278   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14279   // Lambdas and captured statements are not allowed to capture __block
14280   // variables; they don't support the expected semantics.
14281   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14282     if (Diagnose) {
14283       S.Diag(Loc, diag::err_capture_block_variable)
14284         << Var->getDeclName() << !IsLambda;
14285       S.Diag(Var->getLocation(), diag::note_previous_decl)
14286         << Var->getDeclName();
14287     }
14288     return false;
14289   }
14290   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14291   if (S.getLangOpts().OpenCL && IsBlock &&
14292       Var->getType()->isBlockPointerType()) {
14293     if (Diagnose)
14294       S.Diag(Loc, diag::err_opencl_block_ref_block);
14295     return false;
14296   }
14297 
14298   return true;
14299 }
14300 
14301 // Returns true if the capture by block was successful.
14302 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14303                                  SourceLocation Loc,
14304                                  const bool BuildAndDiagnose,
14305                                  QualType &CaptureType,
14306                                  QualType &DeclRefType,
14307                                  const bool Nested,
14308                                  Sema &S) {
14309   Expr *CopyExpr = nullptr;
14310   bool ByRef = false;
14311 
14312   // Blocks are not allowed to capture arrays.
14313   if (CaptureType->isArrayType()) {
14314     if (BuildAndDiagnose) {
14315       S.Diag(Loc, diag::err_ref_array_type);
14316       S.Diag(Var->getLocation(), diag::note_previous_decl)
14317       << Var->getDeclName();
14318     }
14319     return false;
14320   }
14321 
14322   // Forbid the block-capture of autoreleasing variables.
14323   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14324     if (BuildAndDiagnose) {
14325       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14326         << /*block*/ 0;
14327       S.Diag(Var->getLocation(), diag::note_previous_decl)
14328         << Var->getDeclName();
14329     }
14330     return false;
14331   }
14332 
14333   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14334   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14335     // This function finds out whether there is an AttributedType of kind
14336     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14337     // attr_objc_ownership implies __autoreleasing was explicitly specified
14338     // rather than being added implicitly by the compiler.
14339     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14340       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14341         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14342           return true;
14343 
14344         // Peel off AttributedTypes that are not of kind objc_ownership.
14345         Ty = AttrTy->getModifiedType();
14346       }
14347 
14348       return false;
14349     };
14350 
14351     QualType PointeeTy = PT->getPointeeType();
14352 
14353     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14354         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14355         !IsObjCOwnershipAttributedType(PointeeTy)) {
14356       if (BuildAndDiagnose) {
14357         SourceLocation VarLoc = Var->getLocation();
14358         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14359         {
14360           auto AddAutoreleaseNote =
14361               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
14362           // Provide a fix-it for the '__autoreleasing' keyword at the
14363           // appropriate location in the variable's type.
14364           if (const auto *TSI = Var->getTypeSourceInfo()) {
14365             PointerTypeLoc PTL =
14366                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
14367             if (PTL) {
14368               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
14369               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
14370                                                S.getLangOpts());
14371               if (Loc.isValid()) {
14372                 StringRef CharAtLoc = Lexer::getSourceText(
14373                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
14374                     S.getSourceManager(), S.getLangOpts());
14375                 AddAutoreleaseNote << FixItHint::CreateInsertion(
14376                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
14377                              ? " __autoreleasing "
14378                              : " __autoreleasing");
14379               }
14380             }
14381           }
14382         }
14383         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14384       }
14385     }
14386   }
14387 
14388   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14389   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14390       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14391     // Block capture by reference does not change the capture or
14392     // declaration reference types.
14393     ByRef = true;
14394   } else {
14395     // Block capture by copy introduces 'const'.
14396     CaptureType = CaptureType.getNonReferenceType().withConst();
14397     DeclRefType = CaptureType;
14398 
14399     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14400       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14401         // The capture logic needs the destructor, so make sure we mark it.
14402         // Usually this is unnecessary because most local variables have
14403         // their destructors marked at declaration time, but parameters are
14404         // an exception because it's technically only the call site that
14405         // actually requires the destructor.
14406         if (isa<ParmVarDecl>(Var))
14407           S.FinalizeVarWithDestructor(Var, Record);
14408 
14409         // Enter a new evaluation context to insulate the copy
14410         // full-expression.
14411         EnterExpressionEvaluationContext scope(
14412             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14413 
14414         // According to the blocks spec, the capture of a variable from
14415         // the stack requires a const copy constructor.  This is not true
14416         // of the copy/move done to move a __block variable to the heap.
14417         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14418                                                   DeclRefType.withConst(),
14419                                                   VK_LValue, Loc);
14420 
14421         ExprResult Result
14422           = S.PerformCopyInitialization(
14423               InitializedEntity::InitializeBlock(Var->getLocation(),
14424                                                   CaptureType, false),
14425               Loc, DeclRef);
14426 
14427         // Build a full-expression copy expression if initialization
14428         // succeeded and used a non-trivial constructor.  Recover from
14429         // errors by pretending that the copy isn't necessary.
14430         if (!Result.isInvalid() &&
14431             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14432                 ->isTrivial()) {
14433           Result = S.MaybeCreateExprWithCleanups(Result);
14434           CopyExpr = Result.get();
14435         }
14436       }
14437     }
14438   }
14439 
14440   // Actually capture the variable.
14441   if (BuildAndDiagnose)
14442     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14443                     SourceLocation(), CaptureType, CopyExpr);
14444 
14445   return true;
14446 
14447 }
14448 
14449 
14450 /// \brief Capture the given variable in the captured region.
14451 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14452                                     VarDecl *Var,
14453                                     SourceLocation Loc,
14454                                     const bool BuildAndDiagnose,
14455                                     QualType &CaptureType,
14456                                     QualType &DeclRefType,
14457                                     const bool RefersToCapturedVariable,
14458                                     Sema &S) {
14459   // By default, capture variables by reference.
14460   bool ByRef = true;
14461   // Using an LValue reference type is consistent with Lambdas (see below).
14462   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14463     if (S.isOpenMPCapturedDecl(Var)) {
14464       bool HasConst = DeclRefType.isConstQualified();
14465       DeclRefType = DeclRefType.getUnqualifiedType();
14466       // Don't lose diagnostics about assignments to const.
14467       if (HasConst)
14468         DeclRefType.addConst();
14469     }
14470     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14471   }
14472 
14473   if (ByRef)
14474     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14475   else
14476     CaptureType = DeclRefType;
14477 
14478   Expr *CopyExpr = nullptr;
14479   if (BuildAndDiagnose) {
14480     // The current implementation assumes that all variables are captured
14481     // by references. Since there is no capture by copy, no expression
14482     // evaluation will be needed.
14483     RecordDecl *RD = RSI->TheRecordDecl;
14484 
14485     FieldDecl *Field
14486       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14487                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14488                           nullptr, false, ICIS_NoInit);
14489     Field->setImplicit(true);
14490     Field->setAccess(AS_private);
14491     RD->addDecl(Field);
14492     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14493       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14494 
14495     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14496                                             DeclRefType, VK_LValue, Loc);
14497     Var->setReferenced(true);
14498     Var->markUsed(S.Context);
14499   }
14500 
14501   // Actually capture the variable.
14502   if (BuildAndDiagnose)
14503     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14504                     SourceLocation(), CaptureType, CopyExpr);
14505 
14506 
14507   return true;
14508 }
14509 
14510 /// \brief Create a field within the lambda class for the variable
14511 /// being captured.
14512 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14513                                     QualType FieldType, QualType DeclRefType,
14514                                     SourceLocation Loc,
14515                                     bool RefersToCapturedVariable) {
14516   CXXRecordDecl *Lambda = LSI->Lambda;
14517 
14518   // Build the non-static data member.
14519   FieldDecl *Field
14520     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14521                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14522                         nullptr, false, ICIS_NoInit);
14523   Field->setImplicit(true);
14524   Field->setAccess(AS_private);
14525   Lambda->addDecl(Field);
14526 }
14527 
14528 /// \brief Capture the given variable in the lambda.
14529 static bool captureInLambda(LambdaScopeInfo *LSI,
14530                             VarDecl *Var,
14531                             SourceLocation Loc,
14532                             const bool BuildAndDiagnose,
14533                             QualType &CaptureType,
14534                             QualType &DeclRefType,
14535                             const bool RefersToCapturedVariable,
14536                             const Sema::TryCaptureKind Kind,
14537                             SourceLocation EllipsisLoc,
14538                             const bool IsTopScope,
14539                             Sema &S) {
14540 
14541   // Determine whether we are capturing by reference or by value.
14542   bool ByRef = false;
14543   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14544     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14545   } else {
14546     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14547   }
14548 
14549   // Compute the type of the field that will capture this variable.
14550   if (ByRef) {
14551     // C++11 [expr.prim.lambda]p15:
14552     //   An entity is captured by reference if it is implicitly or
14553     //   explicitly captured but not captured by copy. It is
14554     //   unspecified whether additional unnamed non-static data
14555     //   members are declared in the closure type for entities
14556     //   captured by reference.
14557     //
14558     // FIXME: It is not clear whether we want to build an lvalue reference
14559     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14560     // to do the former, while EDG does the latter. Core issue 1249 will
14561     // clarify, but for now we follow GCC because it's a more permissive and
14562     // easily defensible position.
14563     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14564   } else {
14565     // C++11 [expr.prim.lambda]p14:
14566     //   For each entity captured by copy, an unnamed non-static
14567     //   data member is declared in the closure type. The
14568     //   declaration order of these members is unspecified. The type
14569     //   of such a data member is the type of the corresponding
14570     //   captured entity if the entity is not a reference to an
14571     //   object, or the referenced type otherwise. [Note: If the
14572     //   captured entity is a reference to a function, the
14573     //   corresponding data member is also a reference to a
14574     //   function. - end note ]
14575     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14576       if (!RefType->getPointeeType()->isFunctionType())
14577         CaptureType = RefType->getPointeeType();
14578     }
14579 
14580     // Forbid the lambda copy-capture of autoreleasing variables.
14581     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14582       if (BuildAndDiagnose) {
14583         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14584         S.Diag(Var->getLocation(), diag::note_previous_decl)
14585           << Var->getDeclName();
14586       }
14587       return false;
14588     }
14589 
14590     // Make sure that by-copy captures are of a complete and non-abstract type.
14591     if (BuildAndDiagnose) {
14592       if (!CaptureType->isDependentType() &&
14593           S.RequireCompleteType(Loc, CaptureType,
14594                                 diag::err_capture_of_incomplete_type,
14595                                 Var->getDeclName()))
14596         return false;
14597 
14598       if (S.RequireNonAbstractType(Loc, CaptureType,
14599                                    diag::err_capture_of_abstract_type))
14600         return false;
14601     }
14602   }
14603 
14604   // Capture this variable in the lambda.
14605   if (BuildAndDiagnose)
14606     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14607                             RefersToCapturedVariable);
14608 
14609   // Compute the type of a reference to this captured variable.
14610   if (ByRef)
14611     DeclRefType = CaptureType.getNonReferenceType();
14612   else {
14613     // C++ [expr.prim.lambda]p5:
14614     //   The closure type for a lambda-expression has a public inline
14615     //   function call operator [...]. This function call operator is
14616     //   declared const (9.3.1) if and only if the lambda-expression's
14617     //   parameter-declaration-clause is not followed by mutable.
14618     DeclRefType = CaptureType.getNonReferenceType();
14619     if (!LSI->Mutable && !CaptureType->isReferenceType())
14620       DeclRefType.addConst();
14621   }
14622 
14623   // Add the capture.
14624   if (BuildAndDiagnose)
14625     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14626                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14627 
14628   return true;
14629 }
14630 
14631 bool Sema::tryCaptureVariable(
14632     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14633     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14634     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14635   // An init-capture is notionally from the context surrounding its
14636   // declaration, but its parent DC is the lambda class.
14637   DeclContext *VarDC = Var->getDeclContext();
14638   if (Var->isInitCapture())
14639     VarDC = VarDC->getParent();
14640 
14641   DeclContext *DC = CurContext;
14642   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14643       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14644   // We need to sync up the Declaration Context with the
14645   // FunctionScopeIndexToStopAt
14646   if (FunctionScopeIndexToStopAt) {
14647     unsigned FSIndex = FunctionScopes.size() - 1;
14648     while (FSIndex != MaxFunctionScopesIndex) {
14649       DC = getLambdaAwareParentOfDeclContext(DC);
14650       --FSIndex;
14651     }
14652   }
14653 
14654 
14655   // If the variable is declared in the current context, there is no need to
14656   // capture it.
14657   if (VarDC == DC) return true;
14658 
14659   // Capture global variables if it is required to use private copy of this
14660   // variable.
14661   bool IsGlobal = !Var->hasLocalStorage();
14662   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14663     return true;
14664   Var = Var->getCanonicalDecl();
14665 
14666   // Walk up the stack to determine whether we can capture the variable,
14667   // performing the "simple" checks that don't depend on type. We stop when
14668   // we've either hit the declared scope of the variable or find an existing
14669   // capture of that variable.  We start from the innermost capturing-entity
14670   // (the DC) and ensure that all intervening capturing-entities
14671   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14672   // declcontext can either capture the variable or have already captured
14673   // the variable.
14674   CaptureType = Var->getType();
14675   DeclRefType = CaptureType.getNonReferenceType();
14676   bool Nested = false;
14677   bool Explicit = (Kind != TryCapture_Implicit);
14678   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14679   do {
14680     // Only block literals, captured statements, and lambda expressions can
14681     // capture; other scopes don't work.
14682     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14683                                                               ExprLoc,
14684                                                               BuildAndDiagnose,
14685                                                               *this);
14686     // We need to check for the parent *first* because, if we *have*
14687     // private-captured a global variable, we need to recursively capture it in
14688     // intermediate blocks, lambdas, etc.
14689     if (!ParentDC) {
14690       if (IsGlobal) {
14691         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14692         break;
14693       }
14694       return true;
14695     }
14696 
14697     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14698     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14699 
14700 
14701     // Check whether we've already captured it.
14702     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14703                                              DeclRefType)) {
14704       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14705       break;
14706     }
14707     // If we are instantiating a generic lambda call operator body,
14708     // we do not want to capture new variables.  What was captured
14709     // during either a lambdas transformation or initial parsing
14710     // should be used.
14711     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14712       if (BuildAndDiagnose) {
14713         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14714         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14715           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14716           Diag(Var->getLocation(), diag::note_previous_decl)
14717              << Var->getDeclName();
14718           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14719         } else
14720           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14721       }
14722       return true;
14723     }
14724     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14725     // certain types of variables (unnamed, variably modified types etc.)
14726     // so check for eligibility.
14727     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14728        return true;
14729 
14730     // Try to capture variable-length arrays types.
14731     if (Var->getType()->isVariablyModifiedType()) {
14732       // We're going to walk down into the type and look for VLA
14733       // expressions.
14734       QualType QTy = Var->getType();
14735       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14736         QTy = PVD->getOriginalType();
14737       captureVariablyModifiedType(Context, QTy, CSI);
14738     }
14739 
14740     if (getLangOpts().OpenMP) {
14741       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14742         // OpenMP private variables should not be captured in outer scope, so
14743         // just break here. Similarly, global variables that are captured in a
14744         // target region should not be captured outside the scope of the region.
14745         if (RSI->CapRegionKind == CR_OpenMP) {
14746           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
14747           auto IsTargetCap = !IsOpenMPPrivateDecl &&
14748                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14749           // When we detect target captures we are looking from inside the
14750           // target region, therefore we need to propagate the capture from the
14751           // enclosing region. Therefore, the capture is not initially nested.
14752           if (IsTargetCap)
14753             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
14754 
14755           if (IsTargetCap || IsOpenMPPrivateDecl) {
14756             Nested = !IsTargetCap;
14757             DeclRefType = DeclRefType.getUnqualifiedType();
14758             CaptureType = Context.getLValueReferenceType(DeclRefType);
14759             break;
14760           }
14761         }
14762       }
14763     }
14764     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14765       // No capture-default, and this is not an explicit capture
14766       // so cannot capture this variable.
14767       if (BuildAndDiagnose) {
14768         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14769         Diag(Var->getLocation(), diag::note_previous_decl)
14770           << Var->getDeclName();
14771         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14772           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14773                diag::note_lambda_decl);
14774         // FIXME: If we error out because an outer lambda can not implicitly
14775         // capture a variable that an inner lambda explicitly captures, we
14776         // should have the inner lambda do the explicit capture - because
14777         // it makes for cleaner diagnostics later.  This would purely be done
14778         // so that the diagnostic does not misleadingly claim that a variable
14779         // can not be captured by a lambda implicitly even though it is captured
14780         // explicitly.  Suggestion:
14781         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14782         //    at the function head
14783         //  - cache the StartingDeclContext - this must be a lambda
14784         //  - captureInLambda in the innermost lambda the variable.
14785       }
14786       return true;
14787     }
14788 
14789     FunctionScopesIndex--;
14790     DC = ParentDC;
14791     Explicit = false;
14792   } while (!VarDC->Equals(DC));
14793 
14794   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14795   // computing the type of the capture at each step, checking type-specific
14796   // requirements, and adding captures if requested.
14797   // If the variable had already been captured previously, we start capturing
14798   // at the lambda nested within that one.
14799   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14800        ++I) {
14801     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14802 
14803     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14804       if (!captureInBlock(BSI, Var, ExprLoc,
14805                           BuildAndDiagnose, CaptureType,
14806                           DeclRefType, Nested, *this))
14807         return true;
14808       Nested = true;
14809     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14810       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14811                                    BuildAndDiagnose, CaptureType,
14812                                    DeclRefType, Nested, *this))
14813         return true;
14814       Nested = true;
14815     } else {
14816       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14817       if (!captureInLambda(LSI, Var, ExprLoc,
14818                            BuildAndDiagnose, CaptureType,
14819                            DeclRefType, Nested, Kind, EllipsisLoc,
14820                             /*IsTopScope*/I == N - 1, *this))
14821         return true;
14822       Nested = true;
14823     }
14824   }
14825   return false;
14826 }
14827 
14828 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14829                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14830   QualType CaptureType;
14831   QualType DeclRefType;
14832   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14833                             /*BuildAndDiagnose=*/true, CaptureType,
14834                             DeclRefType, nullptr);
14835 }
14836 
14837 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14838   QualType CaptureType;
14839   QualType DeclRefType;
14840   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14841                              /*BuildAndDiagnose=*/false, CaptureType,
14842                              DeclRefType, nullptr);
14843 }
14844 
14845 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14846   QualType CaptureType;
14847   QualType DeclRefType;
14848 
14849   // Determine whether we can capture this variable.
14850   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14851                          /*BuildAndDiagnose=*/false, CaptureType,
14852                          DeclRefType, nullptr))
14853     return QualType();
14854 
14855   return DeclRefType;
14856 }
14857 
14858 
14859 
14860 // If either the type of the variable or the initializer is dependent,
14861 // return false. Otherwise, determine whether the variable is a constant
14862 // expression. Use this if you need to know if a variable that might or
14863 // might not be dependent is truly a constant expression.
14864 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14865     ASTContext &Context) {
14866 
14867   if (Var->getType()->isDependentType())
14868     return false;
14869   const VarDecl *DefVD = nullptr;
14870   Var->getAnyInitializer(DefVD);
14871   if (!DefVD)
14872     return false;
14873   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14874   Expr *Init = cast<Expr>(Eval->Value);
14875   if (Init->isValueDependent())
14876     return false;
14877   return IsVariableAConstantExpression(Var, Context);
14878 }
14879 
14880 
14881 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14882   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14883   // an object that satisfies the requirements for appearing in a
14884   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14885   // is immediately applied."  This function handles the lvalue-to-rvalue
14886   // conversion part.
14887   MaybeODRUseExprs.erase(E->IgnoreParens());
14888 
14889   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14890   // to a variable that is a constant expression, and if so, identify it as
14891   // a reference to a variable that does not involve an odr-use of that
14892   // variable.
14893   if (LambdaScopeInfo *LSI = getCurLambda()) {
14894     Expr *SansParensExpr = E->IgnoreParens();
14895     VarDecl *Var = nullptr;
14896     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14897       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14898     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14899       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14900 
14901     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14902       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14903   }
14904 }
14905 
14906 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14907   Res = CorrectDelayedTyposInExpr(Res);
14908 
14909   if (!Res.isUsable())
14910     return Res;
14911 
14912   // If a constant-expression is a reference to a variable where we delay
14913   // deciding whether it is an odr-use, just assume we will apply the
14914   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14915   // (a non-type template argument), we have special handling anyway.
14916   UpdateMarkingForLValueToRValue(Res.get());
14917   return Res;
14918 }
14919 
14920 void Sema::CleanupVarDeclMarking() {
14921   for (Expr *E : MaybeODRUseExprs) {
14922     VarDecl *Var;
14923     SourceLocation Loc;
14924     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14925       Var = cast<VarDecl>(DRE->getDecl());
14926       Loc = DRE->getLocation();
14927     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14928       Var = cast<VarDecl>(ME->getMemberDecl());
14929       Loc = ME->getMemberLoc();
14930     } else {
14931       llvm_unreachable("Unexpected expression");
14932     }
14933 
14934     MarkVarDeclODRUsed(Var, Loc, *this,
14935                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14936   }
14937 
14938   MaybeODRUseExprs.clear();
14939 }
14940 
14941 
14942 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14943                                     VarDecl *Var, Expr *E) {
14944   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14945          "Invalid Expr argument to DoMarkVarDeclReferenced");
14946   Var->setReferenced();
14947 
14948   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14949 
14950   bool OdrUseContext = isOdrUseContext(SemaRef);
14951   bool UsableInConstantExpr =
14952       Var->isUsableInConstantExpressions(SemaRef.Context);
14953   bool NeedDefinition =
14954       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
14955 
14956   VarTemplateSpecializationDecl *VarSpec =
14957       dyn_cast<VarTemplateSpecializationDecl>(Var);
14958   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14959          "Can't instantiate a partial template specialization.");
14960 
14961   // If this might be a member specialization of a static data member, check
14962   // the specialization is visible. We already did the checks for variable
14963   // template specializations when we created them.
14964   if (NeedDefinition && TSK != TSK_Undeclared &&
14965       !isa<VarTemplateSpecializationDecl>(Var))
14966     SemaRef.checkSpecializationVisibility(Loc, Var);
14967 
14968   // Perform implicit instantiation of static data members, static data member
14969   // templates of class templates, and variable template specializations. Delay
14970   // instantiations of variable templates, except for those that could be used
14971   // in a constant expression.
14972   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14973     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
14974     // instantiation declaration if a variable is usable in a constant
14975     // expression (among other cases).
14976     bool TryInstantiating =
14977         TSK == TSK_ImplicitInstantiation ||
14978         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
14979 
14980     if (TryInstantiating) {
14981       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14982       bool FirstInstantiation = PointOfInstantiation.isInvalid();
14983       if (FirstInstantiation) {
14984         PointOfInstantiation = Loc;
14985         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14986       }
14987 
14988       bool InstantiationDependent = false;
14989       bool IsNonDependent =
14990           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14991                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14992                   : true;
14993 
14994       // Do not instantiate specializations that are still type-dependent.
14995       if (IsNonDependent) {
14996         if (UsableInConstantExpr) {
14997           // Do not defer instantiations of variables that could be used in a
14998           // constant expression.
14999           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15000         } else if (FirstInstantiation ||
15001                    isa<VarTemplateSpecializationDecl>(Var)) {
15002           // FIXME: For a specialization of a variable template, we don't
15003           // distinguish between "declaration and type implicitly instantiated"
15004           // and "implicit instantiation of definition requested", so we have
15005           // no direct way to avoid enqueueing the pending instantiation
15006           // multiple times.
15007           SemaRef.PendingInstantiations
15008               .push_back(std::make_pair(Var, PointOfInstantiation));
15009         }
15010       }
15011     }
15012   }
15013 
15014   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15015   // the requirements for appearing in a constant expression (5.19) and, if
15016   // it is an object, the lvalue-to-rvalue conversion (4.1)
15017   // is immediately applied."  We check the first part here, and
15018   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15019   // Note that we use the C++11 definition everywhere because nothing in
15020   // C++03 depends on whether we get the C++03 version correct. The second
15021   // part does not apply to references, since they are not objects.
15022   if (OdrUseContext && E &&
15023       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15024     // A reference initialized by a constant expression can never be
15025     // odr-used, so simply ignore it.
15026     if (!Var->getType()->isReferenceType() ||
15027         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15028       SemaRef.MaybeODRUseExprs.insert(E);
15029   } else if (OdrUseContext) {
15030     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15031                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15032   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15033     // If this is a dependent context, we don't need to mark variables as
15034     // odr-used, but we may still need to track them for lambda capture.
15035     // FIXME: Do we also need to do this inside dependent typeid expressions
15036     // (which are modeled as unevaluated at this point)?
15037     const bool RefersToEnclosingScope =
15038         (SemaRef.CurContext != Var->getDeclContext() &&
15039          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15040     if (RefersToEnclosingScope) {
15041       LambdaScopeInfo *const LSI =
15042           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15043       if (LSI && (!LSI->CallOperator ||
15044                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15045         // If a variable could potentially be odr-used, defer marking it so
15046         // until we finish analyzing the full expression for any
15047         // lvalue-to-rvalue
15048         // or discarded value conversions that would obviate odr-use.
15049         // Add it to the list of potential captures that will be analyzed
15050         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15051         // unless the variable is a reference that was initialized by a constant
15052         // expression (this will never need to be captured or odr-used).
15053         assert(E && "Capture variable should be used in an expression.");
15054         if (!Var->getType()->isReferenceType() ||
15055             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15056           LSI->addPotentialCapture(E->IgnoreParens());
15057       }
15058     }
15059   }
15060 }
15061 
15062 /// \brief Mark a variable referenced, and check whether it is odr-used
15063 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15064 /// used directly for normal expressions referring to VarDecl.
15065 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15066   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15067 }
15068 
15069 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15070                                Decl *D, Expr *E, bool MightBeOdrUse) {
15071   if (SemaRef.isInOpenMPDeclareTargetContext())
15072     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15073 
15074   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15075     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15076     return;
15077   }
15078 
15079   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15080 
15081   // If this is a call to a method via a cast, also mark the method in the
15082   // derived class used in case codegen can devirtualize the call.
15083   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15084   if (!ME)
15085     return;
15086   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15087   if (!MD)
15088     return;
15089   // Only attempt to devirtualize if this is truly a virtual call.
15090   bool IsVirtualCall = MD->isVirtual() &&
15091                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15092   if (!IsVirtualCall)
15093     return;
15094 
15095   // If it's possible to devirtualize the call, mark the called function
15096   // referenced.
15097   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15098       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15099   if (DM)
15100     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15101 }
15102 
15103 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
15104 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15105   // TODO: update this with DR# once a defect report is filed.
15106   // C++11 defect. The address of a pure member should not be an ODR use, even
15107   // if it's a qualified reference.
15108   bool OdrUse = true;
15109   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15110     if (Method->isVirtual() &&
15111         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15112       OdrUse = false;
15113   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15114 }
15115 
15116 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
15117 void Sema::MarkMemberReferenced(MemberExpr *E) {
15118   // C++11 [basic.def.odr]p2:
15119   //   A non-overloaded function whose name appears as a potentially-evaluated
15120   //   expression or a member of a set of candidate functions, if selected by
15121   //   overload resolution when referred to from a potentially-evaluated
15122   //   expression, is odr-used, unless it is a pure virtual function and its
15123   //   name is not explicitly qualified.
15124   bool MightBeOdrUse = true;
15125   if (E->performsVirtualDispatch(getLangOpts())) {
15126     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15127       if (Method->isPure())
15128         MightBeOdrUse = false;
15129   }
15130   SourceLocation Loc = E->getMemberLoc().isValid() ?
15131                             E->getMemberLoc() : E->getLocStart();
15132   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15133 }
15134 
15135 /// \brief Perform marking for a reference to an arbitrary declaration.  It
15136 /// marks the declaration referenced, and performs odr-use checking for
15137 /// functions and variables. This method should not be used when building a
15138 /// normal expression which refers to a variable.
15139 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15140                                  bool MightBeOdrUse) {
15141   if (MightBeOdrUse) {
15142     if (auto *VD = dyn_cast<VarDecl>(D)) {
15143       MarkVariableReferenced(Loc, VD);
15144       return;
15145     }
15146   }
15147   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15148     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15149     return;
15150   }
15151   D->setReferenced();
15152 }
15153 
15154 namespace {
15155   // Mark all of the declarations used by a type as referenced.
15156   // FIXME: Not fully implemented yet! We need to have a better understanding
15157   // of when we're entering a context we should not recurse into.
15158   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15159   // TreeTransforms rebuilding the type in a new context. Rather than
15160   // duplicating the TreeTransform logic, we should consider reusing it here.
15161   // Currently that causes problems when rebuilding LambdaExprs.
15162   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15163     Sema &S;
15164     SourceLocation Loc;
15165 
15166   public:
15167     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15168 
15169     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15170 
15171     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15172   };
15173 }
15174 
15175 bool MarkReferencedDecls::TraverseTemplateArgument(
15176     const TemplateArgument &Arg) {
15177   {
15178     // A non-type template argument is a constant-evaluated context.
15179     EnterExpressionEvaluationContext Evaluated(
15180         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15181     if (Arg.getKind() == TemplateArgument::Declaration) {
15182       if (Decl *D = Arg.getAsDecl())
15183         S.MarkAnyDeclReferenced(Loc, D, true);
15184     } else if (Arg.getKind() == TemplateArgument::Expression) {
15185       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15186     }
15187   }
15188 
15189   return Inherited::TraverseTemplateArgument(Arg);
15190 }
15191 
15192 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15193   MarkReferencedDecls Marker(*this, Loc);
15194   Marker.TraverseType(T);
15195 }
15196 
15197 namespace {
15198   /// \brief Helper class that marks all of the declarations referenced by
15199   /// potentially-evaluated subexpressions as "referenced".
15200   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15201     Sema &S;
15202     bool SkipLocalVariables;
15203 
15204   public:
15205     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15206 
15207     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15208       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15209 
15210     void VisitDeclRefExpr(DeclRefExpr *E) {
15211       // If we were asked not to visit local variables, don't.
15212       if (SkipLocalVariables) {
15213         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15214           if (VD->hasLocalStorage())
15215             return;
15216       }
15217 
15218       S.MarkDeclRefReferenced(E);
15219     }
15220 
15221     void VisitMemberExpr(MemberExpr *E) {
15222       S.MarkMemberReferenced(E);
15223       Inherited::VisitMemberExpr(E);
15224     }
15225 
15226     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15227       S.MarkFunctionReferenced(E->getLocStart(),
15228             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15229       Visit(E->getSubExpr());
15230     }
15231 
15232     void VisitCXXNewExpr(CXXNewExpr *E) {
15233       if (E->getOperatorNew())
15234         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15235       if (E->getOperatorDelete())
15236         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15237       Inherited::VisitCXXNewExpr(E);
15238     }
15239 
15240     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15241       if (E->getOperatorDelete())
15242         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15243       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15244       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15245         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15246         S.MarkFunctionReferenced(E->getLocStart(),
15247                                     S.LookupDestructor(Record));
15248       }
15249 
15250       Inherited::VisitCXXDeleteExpr(E);
15251     }
15252 
15253     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15254       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15255       Inherited::VisitCXXConstructExpr(E);
15256     }
15257 
15258     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15259       Visit(E->getExpr());
15260     }
15261 
15262     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15263       Inherited::VisitImplicitCastExpr(E);
15264 
15265       if (E->getCastKind() == CK_LValueToRValue)
15266         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15267     }
15268   };
15269 }
15270 
15271 /// \brief Mark any declarations that appear within this expression or any
15272 /// potentially-evaluated subexpressions as "referenced".
15273 ///
15274 /// \param SkipLocalVariables If true, don't mark local variables as
15275 /// 'referenced'.
15276 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15277                                             bool SkipLocalVariables) {
15278   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15279 }
15280 
15281 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
15282 /// of the program being compiled.
15283 ///
15284 /// This routine emits the given diagnostic when the code currently being
15285 /// type-checked is "potentially evaluated", meaning that there is a
15286 /// possibility that the code will actually be executable. Code in sizeof()
15287 /// expressions, code used only during overload resolution, etc., are not
15288 /// potentially evaluated. This routine will suppress such diagnostics or,
15289 /// in the absolutely nutty case of potentially potentially evaluated
15290 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15291 /// later.
15292 ///
15293 /// This routine should be used for all diagnostics that describe the run-time
15294 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15295 /// Failure to do so will likely result in spurious diagnostics or failures
15296 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15297 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15298                                const PartialDiagnostic &PD) {
15299   switch (ExprEvalContexts.back().Context) {
15300   case ExpressionEvaluationContext::Unevaluated:
15301   case ExpressionEvaluationContext::UnevaluatedList:
15302   case ExpressionEvaluationContext::UnevaluatedAbstract:
15303   case ExpressionEvaluationContext::DiscardedStatement:
15304     // The argument will never be evaluated, so don't complain.
15305     break;
15306 
15307   case ExpressionEvaluationContext::ConstantEvaluated:
15308     // Relevant diagnostics should be produced by constant evaluation.
15309     break;
15310 
15311   case ExpressionEvaluationContext::PotentiallyEvaluated:
15312   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15313     if (Statement && getCurFunctionOrMethodDecl()) {
15314       FunctionScopes.back()->PossiblyUnreachableDiags.
15315         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15316       return true;
15317     }
15318 
15319     // The initializer of a constexpr variable or of the first declaration of a
15320     // static data member is not syntactically a constant evaluated constant,
15321     // but nonetheless is always required to be a constant expression, so we
15322     // can skip diagnosing.
15323     // FIXME: Using the mangling context here is a hack.
15324     if (auto *VD = dyn_cast_or_null<VarDecl>(
15325             ExprEvalContexts.back().ManglingContextDecl)) {
15326       if (VD->isConstexpr() ||
15327           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15328         break;
15329       // FIXME: For any other kind of variable, we should build a CFG for its
15330       // initializer and check whether the context in question is reachable.
15331     }
15332 
15333     Diag(Loc, PD);
15334     return true;
15335   }
15336 
15337   return false;
15338 }
15339 
15340 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15341                                CallExpr *CE, FunctionDecl *FD) {
15342   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15343     return false;
15344 
15345   // If we're inside a decltype's expression, don't check for a valid return
15346   // type or construct temporaries until we know whether this is the last call.
15347   if (ExprEvalContexts.back().IsDecltype) {
15348     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15349     return false;
15350   }
15351 
15352   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15353     FunctionDecl *FD;
15354     CallExpr *CE;
15355 
15356   public:
15357     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15358       : FD(FD), CE(CE) { }
15359 
15360     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15361       if (!FD) {
15362         S.Diag(Loc, diag::err_call_incomplete_return)
15363           << T << CE->getSourceRange();
15364         return;
15365       }
15366 
15367       S.Diag(Loc, diag::err_call_function_incomplete_return)
15368         << CE->getSourceRange() << FD->getDeclName() << T;
15369       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15370           << FD->getDeclName();
15371     }
15372   } Diagnoser(FD, CE);
15373 
15374   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15375     return true;
15376 
15377   return false;
15378 }
15379 
15380 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15381 // will prevent this condition from triggering, which is what we want.
15382 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15383   SourceLocation Loc;
15384 
15385   unsigned diagnostic = diag::warn_condition_is_assignment;
15386   bool IsOrAssign = false;
15387 
15388   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15389     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15390       return;
15391 
15392     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15393 
15394     // Greylist some idioms by putting them into a warning subcategory.
15395     if (ObjCMessageExpr *ME
15396           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15397       Selector Sel = ME->getSelector();
15398 
15399       // self = [<foo> init...]
15400       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15401         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15402 
15403       // <foo> = [<bar> nextObject]
15404       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15405         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15406     }
15407 
15408     Loc = Op->getOperatorLoc();
15409   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15410     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15411       return;
15412 
15413     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15414     Loc = Op->getOperatorLoc();
15415   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15416     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15417   else {
15418     // Not an assignment.
15419     return;
15420   }
15421 
15422   Diag(Loc, diagnostic) << E->getSourceRange();
15423 
15424   SourceLocation Open = E->getLocStart();
15425   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15426   Diag(Loc, diag::note_condition_assign_silence)
15427         << FixItHint::CreateInsertion(Open, "(")
15428         << FixItHint::CreateInsertion(Close, ")");
15429 
15430   if (IsOrAssign)
15431     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15432       << FixItHint::CreateReplacement(Loc, "!=");
15433   else
15434     Diag(Loc, diag::note_condition_assign_to_comparison)
15435       << FixItHint::CreateReplacement(Loc, "==");
15436 }
15437 
15438 /// \brief Redundant parentheses over an equality comparison can indicate
15439 /// that the user intended an assignment used as condition.
15440 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15441   // Don't warn if the parens came from a macro.
15442   SourceLocation parenLoc = ParenE->getLocStart();
15443   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15444     return;
15445   // Don't warn for dependent expressions.
15446   if (ParenE->isTypeDependent())
15447     return;
15448 
15449   Expr *E = ParenE->IgnoreParens();
15450 
15451   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15452     if (opE->getOpcode() == BO_EQ &&
15453         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15454                                                            == Expr::MLV_Valid) {
15455       SourceLocation Loc = opE->getOperatorLoc();
15456 
15457       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15458       SourceRange ParenERange = ParenE->getSourceRange();
15459       Diag(Loc, diag::note_equality_comparison_silence)
15460         << FixItHint::CreateRemoval(ParenERange.getBegin())
15461         << FixItHint::CreateRemoval(ParenERange.getEnd());
15462       Diag(Loc, diag::note_equality_comparison_to_assign)
15463         << FixItHint::CreateReplacement(Loc, "=");
15464     }
15465 }
15466 
15467 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15468                                        bool IsConstexpr) {
15469   DiagnoseAssignmentAsCondition(E);
15470   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15471     DiagnoseEqualityWithExtraParens(parenE);
15472 
15473   ExprResult result = CheckPlaceholderExpr(E);
15474   if (result.isInvalid()) return ExprError();
15475   E = result.get();
15476 
15477   if (!E->isTypeDependent()) {
15478     if (getLangOpts().CPlusPlus)
15479       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15480 
15481     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15482     if (ERes.isInvalid())
15483       return ExprError();
15484     E = ERes.get();
15485 
15486     QualType T = E->getType();
15487     if (!T->isScalarType()) { // C99 6.8.4.1p1
15488       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15489         << T << E->getSourceRange();
15490       return ExprError();
15491     }
15492     CheckBoolLikeConversion(E, Loc);
15493   }
15494 
15495   return E;
15496 }
15497 
15498 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15499                                            Expr *SubExpr, ConditionKind CK) {
15500   // Empty conditions are valid in for-statements.
15501   if (!SubExpr)
15502     return ConditionResult();
15503 
15504   ExprResult Cond;
15505   switch (CK) {
15506   case ConditionKind::Boolean:
15507     Cond = CheckBooleanCondition(Loc, SubExpr);
15508     break;
15509 
15510   case ConditionKind::ConstexprIf:
15511     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15512     break;
15513 
15514   case ConditionKind::Switch:
15515     Cond = CheckSwitchCondition(Loc, SubExpr);
15516     break;
15517   }
15518   if (Cond.isInvalid())
15519     return ConditionError();
15520 
15521   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15522   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15523   if (!FullExpr.get())
15524     return ConditionError();
15525 
15526   return ConditionResult(*this, nullptr, FullExpr,
15527                          CK == ConditionKind::ConstexprIf);
15528 }
15529 
15530 namespace {
15531   /// A visitor for rebuilding a call to an __unknown_any expression
15532   /// to have an appropriate type.
15533   struct RebuildUnknownAnyFunction
15534     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15535 
15536     Sema &S;
15537 
15538     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15539 
15540     ExprResult VisitStmt(Stmt *S) {
15541       llvm_unreachable("unexpected statement!");
15542     }
15543 
15544     ExprResult VisitExpr(Expr *E) {
15545       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15546         << E->getSourceRange();
15547       return ExprError();
15548     }
15549 
15550     /// Rebuild an expression which simply semantically wraps another
15551     /// expression which it shares the type and value kind of.
15552     template <class T> ExprResult rebuildSugarExpr(T *E) {
15553       ExprResult SubResult = Visit(E->getSubExpr());
15554       if (SubResult.isInvalid()) return ExprError();
15555 
15556       Expr *SubExpr = SubResult.get();
15557       E->setSubExpr(SubExpr);
15558       E->setType(SubExpr->getType());
15559       E->setValueKind(SubExpr->getValueKind());
15560       assert(E->getObjectKind() == OK_Ordinary);
15561       return E;
15562     }
15563 
15564     ExprResult VisitParenExpr(ParenExpr *E) {
15565       return rebuildSugarExpr(E);
15566     }
15567 
15568     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15569       return rebuildSugarExpr(E);
15570     }
15571 
15572     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15573       ExprResult SubResult = Visit(E->getSubExpr());
15574       if (SubResult.isInvalid()) return ExprError();
15575 
15576       Expr *SubExpr = SubResult.get();
15577       E->setSubExpr(SubExpr);
15578       E->setType(S.Context.getPointerType(SubExpr->getType()));
15579       assert(E->getValueKind() == VK_RValue);
15580       assert(E->getObjectKind() == OK_Ordinary);
15581       return E;
15582     }
15583 
15584     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15585       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15586 
15587       E->setType(VD->getType());
15588 
15589       assert(E->getValueKind() == VK_RValue);
15590       if (S.getLangOpts().CPlusPlus &&
15591           !(isa<CXXMethodDecl>(VD) &&
15592             cast<CXXMethodDecl>(VD)->isInstance()))
15593         E->setValueKind(VK_LValue);
15594 
15595       return E;
15596     }
15597 
15598     ExprResult VisitMemberExpr(MemberExpr *E) {
15599       return resolveDecl(E, E->getMemberDecl());
15600     }
15601 
15602     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15603       return resolveDecl(E, E->getDecl());
15604     }
15605   };
15606 }
15607 
15608 /// Given a function expression of unknown-any type, try to rebuild it
15609 /// to have a function type.
15610 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15611   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15612   if (Result.isInvalid()) return ExprError();
15613   return S.DefaultFunctionArrayConversion(Result.get());
15614 }
15615 
15616 namespace {
15617   /// A visitor for rebuilding an expression of type __unknown_anytype
15618   /// into one which resolves the type directly on the referring
15619   /// expression.  Strict preservation of the original source
15620   /// structure is not a goal.
15621   struct RebuildUnknownAnyExpr
15622     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15623 
15624     Sema &S;
15625 
15626     /// The current destination type.
15627     QualType DestType;
15628 
15629     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15630       : S(S), DestType(CastType) {}
15631 
15632     ExprResult VisitStmt(Stmt *S) {
15633       llvm_unreachable("unexpected statement!");
15634     }
15635 
15636     ExprResult VisitExpr(Expr *E) {
15637       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15638         << E->getSourceRange();
15639       return ExprError();
15640     }
15641 
15642     ExprResult VisitCallExpr(CallExpr *E);
15643     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15644 
15645     /// Rebuild an expression which simply semantically wraps another
15646     /// expression which it shares the type and value kind of.
15647     template <class T> ExprResult rebuildSugarExpr(T *E) {
15648       ExprResult SubResult = Visit(E->getSubExpr());
15649       if (SubResult.isInvalid()) return ExprError();
15650       Expr *SubExpr = SubResult.get();
15651       E->setSubExpr(SubExpr);
15652       E->setType(SubExpr->getType());
15653       E->setValueKind(SubExpr->getValueKind());
15654       assert(E->getObjectKind() == OK_Ordinary);
15655       return E;
15656     }
15657 
15658     ExprResult VisitParenExpr(ParenExpr *E) {
15659       return rebuildSugarExpr(E);
15660     }
15661 
15662     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15663       return rebuildSugarExpr(E);
15664     }
15665 
15666     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15667       const PointerType *Ptr = DestType->getAs<PointerType>();
15668       if (!Ptr) {
15669         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15670           << E->getSourceRange();
15671         return ExprError();
15672       }
15673 
15674       if (isa<CallExpr>(E->getSubExpr())) {
15675         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15676           << E->getSourceRange();
15677         return ExprError();
15678       }
15679 
15680       assert(E->getValueKind() == VK_RValue);
15681       assert(E->getObjectKind() == OK_Ordinary);
15682       E->setType(DestType);
15683 
15684       // Build the sub-expression as if it were an object of the pointee type.
15685       DestType = Ptr->getPointeeType();
15686       ExprResult SubResult = Visit(E->getSubExpr());
15687       if (SubResult.isInvalid()) return ExprError();
15688       E->setSubExpr(SubResult.get());
15689       return E;
15690     }
15691 
15692     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15693 
15694     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15695 
15696     ExprResult VisitMemberExpr(MemberExpr *E) {
15697       return resolveDecl(E, E->getMemberDecl());
15698     }
15699 
15700     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15701       return resolveDecl(E, E->getDecl());
15702     }
15703   };
15704 }
15705 
15706 /// Rebuilds a call expression which yielded __unknown_anytype.
15707 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15708   Expr *CalleeExpr = E->getCallee();
15709 
15710   enum FnKind {
15711     FK_MemberFunction,
15712     FK_FunctionPointer,
15713     FK_BlockPointer
15714   };
15715 
15716   FnKind Kind;
15717   QualType CalleeType = CalleeExpr->getType();
15718   if (CalleeType == S.Context.BoundMemberTy) {
15719     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15720     Kind = FK_MemberFunction;
15721     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15722   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15723     CalleeType = Ptr->getPointeeType();
15724     Kind = FK_FunctionPointer;
15725   } else {
15726     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15727     Kind = FK_BlockPointer;
15728   }
15729   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15730 
15731   // Verify that this is a legal result type of a function.
15732   if (DestType->isArrayType() || DestType->isFunctionType()) {
15733     unsigned diagID = diag::err_func_returning_array_function;
15734     if (Kind == FK_BlockPointer)
15735       diagID = diag::err_block_returning_array_function;
15736 
15737     S.Diag(E->getExprLoc(), diagID)
15738       << DestType->isFunctionType() << DestType;
15739     return ExprError();
15740   }
15741 
15742   // Otherwise, go ahead and set DestType as the call's result.
15743   E->setType(DestType.getNonLValueExprType(S.Context));
15744   E->setValueKind(Expr::getValueKindForType(DestType));
15745   assert(E->getObjectKind() == OK_Ordinary);
15746 
15747   // Rebuild the function type, replacing the result type with DestType.
15748   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15749   if (Proto) {
15750     // __unknown_anytype(...) is a special case used by the debugger when
15751     // it has no idea what a function's signature is.
15752     //
15753     // We want to build this call essentially under the K&R
15754     // unprototyped rules, but making a FunctionNoProtoType in C++
15755     // would foul up all sorts of assumptions.  However, we cannot
15756     // simply pass all arguments as variadic arguments, nor can we
15757     // portably just call the function under a non-variadic type; see
15758     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15759     // However, it turns out that in practice it is generally safe to
15760     // call a function declared as "A foo(B,C,D);" under the prototype
15761     // "A foo(B,C,D,...);".  The only known exception is with the
15762     // Windows ABI, where any variadic function is implicitly cdecl
15763     // regardless of its normal CC.  Therefore we change the parameter
15764     // types to match the types of the arguments.
15765     //
15766     // This is a hack, but it is far superior to moving the
15767     // corresponding target-specific code from IR-gen to Sema/AST.
15768 
15769     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15770     SmallVector<QualType, 8> ArgTypes;
15771     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15772       ArgTypes.reserve(E->getNumArgs());
15773       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15774         Expr *Arg = E->getArg(i);
15775         QualType ArgType = Arg->getType();
15776         if (E->isLValue()) {
15777           ArgType = S.Context.getLValueReferenceType(ArgType);
15778         } else if (E->isXValue()) {
15779           ArgType = S.Context.getRValueReferenceType(ArgType);
15780         }
15781         ArgTypes.push_back(ArgType);
15782       }
15783       ParamTypes = ArgTypes;
15784     }
15785     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15786                                          Proto->getExtProtoInfo());
15787   } else {
15788     DestType = S.Context.getFunctionNoProtoType(DestType,
15789                                                 FnType->getExtInfo());
15790   }
15791 
15792   // Rebuild the appropriate pointer-to-function type.
15793   switch (Kind) {
15794   case FK_MemberFunction:
15795     // Nothing to do.
15796     break;
15797 
15798   case FK_FunctionPointer:
15799     DestType = S.Context.getPointerType(DestType);
15800     break;
15801 
15802   case FK_BlockPointer:
15803     DestType = S.Context.getBlockPointerType(DestType);
15804     break;
15805   }
15806 
15807   // Finally, we can recurse.
15808   ExprResult CalleeResult = Visit(CalleeExpr);
15809   if (!CalleeResult.isUsable()) return ExprError();
15810   E->setCallee(CalleeResult.get());
15811 
15812   // Bind a temporary if necessary.
15813   return S.MaybeBindToTemporary(E);
15814 }
15815 
15816 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15817   // Verify that this is a legal result type of a call.
15818   if (DestType->isArrayType() || DestType->isFunctionType()) {
15819     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15820       << DestType->isFunctionType() << DestType;
15821     return ExprError();
15822   }
15823 
15824   // Rewrite the method result type if available.
15825   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15826     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15827     Method->setReturnType(DestType);
15828   }
15829 
15830   // Change the type of the message.
15831   E->setType(DestType.getNonReferenceType());
15832   E->setValueKind(Expr::getValueKindForType(DestType));
15833 
15834   return S.MaybeBindToTemporary(E);
15835 }
15836 
15837 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15838   // The only case we should ever see here is a function-to-pointer decay.
15839   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15840     assert(E->getValueKind() == VK_RValue);
15841     assert(E->getObjectKind() == OK_Ordinary);
15842 
15843     E->setType(DestType);
15844 
15845     // Rebuild the sub-expression as the pointee (function) type.
15846     DestType = DestType->castAs<PointerType>()->getPointeeType();
15847 
15848     ExprResult Result = Visit(E->getSubExpr());
15849     if (!Result.isUsable()) return ExprError();
15850 
15851     E->setSubExpr(Result.get());
15852     return E;
15853   } else if (E->getCastKind() == CK_LValueToRValue) {
15854     assert(E->getValueKind() == VK_RValue);
15855     assert(E->getObjectKind() == OK_Ordinary);
15856 
15857     assert(isa<BlockPointerType>(E->getType()));
15858 
15859     E->setType(DestType);
15860 
15861     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15862     DestType = S.Context.getLValueReferenceType(DestType);
15863 
15864     ExprResult Result = Visit(E->getSubExpr());
15865     if (!Result.isUsable()) return ExprError();
15866 
15867     E->setSubExpr(Result.get());
15868     return E;
15869   } else {
15870     llvm_unreachable("Unhandled cast type!");
15871   }
15872 }
15873 
15874 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15875   ExprValueKind ValueKind = VK_LValue;
15876   QualType Type = DestType;
15877 
15878   // We know how to make this work for certain kinds of decls:
15879 
15880   //  - functions
15881   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15882     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15883       DestType = Ptr->getPointeeType();
15884       ExprResult Result = resolveDecl(E, VD);
15885       if (Result.isInvalid()) return ExprError();
15886       return S.ImpCastExprToType(Result.get(), Type,
15887                                  CK_FunctionToPointerDecay, VK_RValue);
15888     }
15889 
15890     if (!Type->isFunctionType()) {
15891       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15892         << VD << E->getSourceRange();
15893       return ExprError();
15894     }
15895     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15896       // We must match the FunctionDecl's type to the hack introduced in
15897       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15898       // type. See the lengthy commentary in that routine.
15899       QualType FDT = FD->getType();
15900       const FunctionType *FnType = FDT->castAs<FunctionType>();
15901       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15902       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15903       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15904         SourceLocation Loc = FD->getLocation();
15905         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15906                                       FD->getDeclContext(),
15907                                       Loc, Loc, FD->getNameInfo().getName(),
15908                                       DestType, FD->getTypeSourceInfo(),
15909                                       SC_None, false/*isInlineSpecified*/,
15910                                       FD->hasPrototype(),
15911                                       false/*isConstexprSpecified*/);
15912 
15913         if (FD->getQualifier())
15914           NewFD->setQualifierInfo(FD->getQualifierLoc());
15915 
15916         SmallVector<ParmVarDecl*, 16> Params;
15917         for (const auto &AI : FT->param_types()) {
15918           ParmVarDecl *Param =
15919             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15920           Param->setScopeInfo(0, Params.size());
15921           Params.push_back(Param);
15922         }
15923         NewFD->setParams(Params);
15924         DRE->setDecl(NewFD);
15925         VD = DRE->getDecl();
15926       }
15927     }
15928 
15929     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15930       if (MD->isInstance()) {
15931         ValueKind = VK_RValue;
15932         Type = S.Context.BoundMemberTy;
15933       }
15934 
15935     // Function references aren't l-values in C.
15936     if (!S.getLangOpts().CPlusPlus)
15937       ValueKind = VK_RValue;
15938 
15939   //  - variables
15940   } else if (isa<VarDecl>(VD)) {
15941     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15942       Type = RefTy->getPointeeType();
15943     } else if (Type->isFunctionType()) {
15944       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15945         << VD << E->getSourceRange();
15946       return ExprError();
15947     }
15948 
15949   //  - nothing else
15950   } else {
15951     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15952       << VD << E->getSourceRange();
15953     return ExprError();
15954   }
15955 
15956   // Modifying the declaration like this is friendly to IR-gen but
15957   // also really dangerous.
15958   VD->setType(DestType);
15959   E->setType(Type);
15960   E->setValueKind(ValueKind);
15961   return E;
15962 }
15963 
15964 /// Check a cast of an unknown-any type.  We intentionally only
15965 /// trigger this for C-style casts.
15966 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15967                                      Expr *CastExpr, CastKind &CastKind,
15968                                      ExprValueKind &VK, CXXCastPath &Path) {
15969   // The type we're casting to must be either void or complete.
15970   if (!CastType->isVoidType() &&
15971       RequireCompleteType(TypeRange.getBegin(), CastType,
15972                           diag::err_typecheck_cast_to_incomplete))
15973     return ExprError();
15974 
15975   // Rewrite the casted expression from scratch.
15976   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15977   if (!result.isUsable()) return ExprError();
15978 
15979   CastExpr = result.get();
15980   VK = CastExpr->getValueKind();
15981   CastKind = CK_NoOp;
15982 
15983   return CastExpr;
15984 }
15985 
15986 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15987   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15988 }
15989 
15990 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15991                                     Expr *arg, QualType &paramType) {
15992   // If the syntactic form of the argument is not an explicit cast of
15993   // any sort, just do default argument promotion.
15994   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15995   if (!castArg) {
15996     ExprResult result = DefaultArgumentPromotion(arg);
15997     if (result.isInvalid()) return ExprError();
15998     paramType = result.get()->getType();
15999     return result;
16000   }
16001 
16002   // Otherwise, use the type that was written in the explicit cast.
16003   assert(!arg->hasPlaceholderType());
16004   paramType = castArg->getTypeAsWritten();
16005 
16006   // Copy-initialize a parameter of that type.
16007   InitializedEntity entity =
16008     InitializedEntity::InitializeParameter(Context, paramType,
16009                                            /*consumed*/ false);
16010   return PerformCopyInitialization(entity, callLoc, arg);
16011 }
16012 
16013 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16014   Expr *orig = E;
16015   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16016   while (true) {
16017     E = E->IgnoreParenImpCasts();
16018     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16019       E = call->getCallee();
16020       diagID = diag::err_uncasted_call_of_unknown_any;
16021     } else {
16022       break;
16023     }
16024   }
16025 
16026   SourceLocation loc;
16027   NamedDecl *d;
16028   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16029     loc = ref->getLocation();
16030     d = ref->getDecl();
16031   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16032     loc = mem->getMemberLoc();
16033     d = mem->getMemberDecl();
16034   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16035     diagID = diag::err_uncasted_call_of_unknown_any;
16036     loc = msg->getSelectorStartLoc();
16037     d = msg->getMethodDecl();
16038     if (!d) {
16039       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16040         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16041         << orig->getSourceRange();
16042       return ExprError();
16043     }
16044   } else {
16045     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16046       << E->getSourceRange();
16047     return ExprError();
16048   }
16049 
16050   S.Diag(loc, diagID) << d << orig->getSourceRange();
16051 
16052   // Never recoverable.
16053   return ExprError();
16054 }
16055 
16056 /// Check for operands with placeholder types and complain if found.
16057 /// Returns ExprError() if there was an error and no recovery was possible.
16058 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16059   if (!getLangOpts().CPlusPlus) {
16060     // C cannot handle TypoExpr nodes on either side of a binop because it
16061     // doesn't handle dependent types properly, so make sure any TypoExprs have
16062     // been dealt with before checking the operands.
16063     ExprResult Result = CorrectDelayedTyposInExpr(E);
16064     if (!Result.isUsable()) return ExprError();
16065     E = Result.get();
16066   }
16067 
16068   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16069   if (!placeholderType) return E;
16070 
16071   switch (placeholderType->getKind()) {
16072 
16073   // Overloaded expressions.
16074   case BuiltinType::Overload: {
16075     // Try to resolve a single function template specialization.
16076     // This is obligatory.
16077     ExprResult Result = E;
16078     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16079       return Result;
16080 
16081     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16082     // leaves Result unchanged on failure.
16083     Result = E;
16084     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16085       return Result;
16086 
16087     // If that failed, try to recover with a call.
16088     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16089                          /*complain*/ true);
16090     return Result;
16091   }
16092 
16093   // Bound member functions.
16094   case BuiltinType::BoundMember: {
16095     ExprResult result = E;
16096     const Expr *BME = E->IgnoreParens();
16097     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16098     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16099     if (isa<CXXPseudoDestructorExpr>(BME)) {
16100       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16101     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16102       if (ME->getMemberNameInfo().getName().getNameKind() ==
16103           DeclarationName::CXXDestructorName)
16104         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16105     }
16106     tryToRecoverWithCall(result, PD,
16107                          /*complain*/ true);
16108     return result;
16109   }
16110 
16111   // ARC unbridged casts.
16112   case BuiltinType::ARCUnbridgedCast: {
16113     Expr *realCast = stripARCUnbridgedCast(E);
16114     diagnoseARCUnbridgedCast(realCast);
16115     return realCast;
16116   }
16117 
16118   // Expressions of unknown type.
16119   case BuiltinType::UnknownAny:
16120     return diagnoseUnknownAnyExpr(*this, E);
16121 
16122   // Pseudo-objects.
16123   case BuiltinType::PseudoObject:
16124     return checkPseudoObjectRValue(E);
16125 
16126   case BuiltinType::BuiltinFn: {
16127     // Accept __noop without parens by implicitly converting it to a call expr.
16128     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16129     if (DRE) {
16130       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16131       if (FD->getBuiltinID() == Builtin::BI__noop) {
16132         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16133                               CK_BuiltinFnToFnPtr).get();
16134         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16135                                       VK_RValue, SourceLocation());
16136       }
16137     }
16138 
16139     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16140     return ExprError();
16141   }
16142 
16143   // Expressions of unknown type.
16144   case BuiltinType::OMPArraySection:
16145     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16146     return ExprError();
16147 
16148   // Everything else should be impossible.
16149 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16150   case BuiltinType::Id:
16151 #include "clang/Basic/OpenCLImageTypes.def"
16152 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16153 #define PLACEHOLDER_TYPE(Id, SingletonId)
16154 #include "clang/AST/BuiltinTypes.def"
16155     break;
16156   }
16157 
16158   llvm_unreachable("invalid placeholder type!");
16159 }
16160 
16161 bool Sema::CheckCaseExpression(Expr *E) {
16162   if (E->isTypeDependent())
16163     return true;
16164   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16165     return E->getType()->isIntegralOrEnumerationType();
16166   return false;
16167 }
16168 
16169 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16170 ExprResult
16171 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16172   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16173          "Unknown Objective-C Boolean value!");
16174   QualType BoolT = Context.ObjCBuiltinBoolTy;
16175   if (!Context.getBOOLDecl()) {
16176     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16177                         Sema::LookupOrdinaryName);
16178     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16179       NamedDecl *ND = Result.getFoundDecl();
16180       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16181         Context.setBOOLDecl(TD);
16182     }
16183   }
16184   if (Context.getBOOLDecl())
16185     BoolT = Context.getBOOLType();
16186   return new (Context)
16187       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16188 }
16189 
16190 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16191     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16192     SourceLocation RParen) {
16193 
16194   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16195 
16196   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16197                            [&](const AvailabilitySpec &Spec) {
16198                              return Spec.getPlatform() == Platform;
16199                            });
16200 
16201   VersionTuple Version;
16202   if (Spec != AvailSpecs.end())
16203     Version = Spec->getVersion();
16204 
16205   // The use of `@available` in the enclosing function should be analyzed to
16206   // warn when it's used inappropriately (i.e. not if(@available)).
16207   if (getCurFunctionOrMethodDecl())
16208     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16209   else if (getCurBlock() || getCurLambda())
16210     getCurFunction()->HasPotentialAvailabilityViolations = true;
16211 
16212   return new (Context)
16213       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16214 }
16215